auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private RexNode simplifyNot(RexCall call) { final RexNode a = call.getOperands().get(0); if (a.isAlwaysTrue()) { return rexBuilder.makeLiteral(false); } else if (a.isAlwaysFalse()) { return rexBuilder.makeLiteral(true); } switch (a.getKind()) { case NOT: return simplify_(((RexCall) a).getOperands().get(0)); } final SqlKind negateKind = a.getKind().negate(); if (a.getKind() != negateKind) { return simplify_( rexBuilder.makeCall(RexUtil.op(negateKind), ((RexCall) a).getOperands())); } final SqlKind negateKind2 = a.getKind().negateNullSafe(); if (a.getKind() != negateKind2) { return simplify_( rexBuilder.makeCall(RexUtil.op(negateKind2), ((RexCall) a).getOperands())); } if (a.getKind() == SqlKind.AND) { final List<RexNode> newOperands = new ArrayList<>(); for (RexNode operand : ((RexCall) a).getOperands()) { newOperands.add( simplify_(rexBuilder.makeCall(SqlStdOperatorTable.NOT, operand))); } return simplify_( rexBuilder.makeCall(SqlStdOperatorTable.OR, newOperands)); } if (a.getKind() == SqlKind.OR) { final List<RexNode> newOperands = new ArrayList<>(); for (RexNode operand : ((RexCall) a).getOperands()) { newOperands.add( simplify_(rexBuilder.makeCall(SqlStdOperatorTable.NOT, operand))); } return simplify_( rexBuilder.makeCall(SqlStdOperatorTable.AND, newOperands)); } return call; }

Target:
private RexNode simplifyNot(RexCall call) { final RexNode a = call.getOperands().get(0); switch (a.getKind()) { case NOT: return simplify_(((RexCall) a).getOperands().get(0)); case LITERAL: if (a.getType().getSqlTypeName() == SqlTypeName.BOOLEAN && !RexLiteral.isNullLiteral(a)) { return rexBuilder.makeLiteral(!RexLiteral.booleanValue(a)); } } final SqlKind negateKind = a.getKind().negate(); if (a.getKind() != negateKind) { return simplify_( rexBuilder.makeCall(RexUtil.op(negateKind), ((RexCall) a).getOperands())); } final SqlKind negateKind2 = a.getKind().negateNullSafe(); if (a.getKind() != negateKind2) { return simplify_( rexBuilder.makeCall(RexUtil.op(negateKind2), ((RexCall) a).getOperands())); } if (a.getKind() == SqlKind.AND) { final List<RexNode> newOperands = new ArrayList<>(); for (RexNode operand : ((RexCall) a).getOperands()) { newOperands.add( simplify_(rexBuilder.makeCall(SqlStdOperatorTable.NOT, operand))); } return simplify_( rexBuilder.makeCall(SqlStdOperatorTable.OR, newOperands)); } if (a.getKind() == SqlKind.OR) { final List<RexNode> newOperands = new ArrayList<>(); for (RexNode operand : ((RexCall) a).getOperands()) { newOperands.add( simplify_(rexBuilder.makeCall(SqlStdOperatorTable.NOT, operand))); } return simplify_( rexBuilder.makeCall(SqlStdOperatorTable.AND, newOperands)); } return call; }
Source:
public ChannelFuture getHandshakeFuture() { return handshakePromise; }

Target:
ChannelFuture getHandshakeFuture() { return handshakePromise; }
Source:
public void testMiniBatchBalanced() { int miniBatchSize = 10; DataSetIterator iterator = new IrisDataSetIterator(miniBatchSize, 150); BalanceMinibatches balanceMinibatches = BalanceMinibatches.builder().dataSetIterator(iterator).miniBatchSize(miniBatchSize) .numLabels(iterator.totalOutcomes()).rootDir(new File("minibatches")).rootSaveDir(new File("minibatchessave")).build(); balanceMinibatches.balance(); DataSetIterator balanced = new ExistingMiniBatchDataSetIterator(balanceMinibatches.getRootSaveDir()); assert(iterator.resetSupported()); iterator.reset(); ArrayList<Double> totalCounts = new ArrayList<Double>(iterator.totalOutcomes()); while (iterator.hasNext()) { Map<Integer, Double> outcomes = iterator.next().labelCounts(); for (int i = 0; i < iterator.totalOutcomes(); i++) { if (outcomes.containsKey(i)) { totalCounts.set(i, totalCounts.get(i) + outcomes.get(i)); } } } ArrayList<Integer> fullBatches = new ArrayList<Integer>(totalCounts.size()); for (int i = 0; i < totalCounts.size(); i++) { fullBatches.set(i, totalCounts.get(i).intValue() * iterator.totalOutcomes() / miniBatchSize); } int fullyBalanceableBatches = Collections.min(fullBatches); for (int b = 0; b < fullyBalanceableBatches; b++){ Map<Integer, Double> balancedCounts = balanced.next().labelCounts(); for (int i = 0; i < iterator.totalOutcomes(); i++) { assertTrue(balancedCounts.containsKey(i) && balancedCounts.get(i) >= miniBatchSize / iterator.totalOutcomes()); } } }

Target:
public void testMiniBatchBalanced() { int miniBatchSize = 10; DataSetIterator iterator = new IrisDataSetIterator(miniBatchSize, 150); BalanceMinibatches balanceMinibatches = BalanceMinibatches.builder().dataSetIterator(iterator).miniBatchSize(miniBatchSize) .numLabels(iterator.totalOutcomes()).rootDir(new File("minibatches")).rootSaveDir(new File("minibatchessave")).build(); balanceMinibatches.balance(); DataSetIterator balanced = new ExistingMiniBatchDataSetIterator(balanceMinibatches.getRootSaveDir()); assertTrue(iterator.resetSupported()); iterator.reset(); List<Double> totalCounts = new ArrayList<Double>(iterator.totalOutcomes()); while (iterator.hasNext()) { Map<Integer, Double> outcomes = iterator.next().labelCounts(); for (int i = 0; i < iterator.totalOutcomes(); i++) { if (outcomes.containsKey(i)) { totalCounts.set(i, totalCounts.get(i) + outcomes.get(i)); } } } List<Integer> fullBatches = new ArrayList<Integer>(totalCounts.size()); for (int i = 0; i < totalCounts.size(); i++) { fullBatches.set(i, totalCounts.get(i).intValue() * iterator.totalOutcomes() / miniBatchSize); } int fullyBalanceableBatches = Collections.min(fullBatches); for (int b = 0; b < fullyBalanceableBatches; b++){ Map<Integer, Double> balancedCounts = balanced.next().labelCounts(); for (int i = 0; i < iterator.totalOutcomes(); i++) { assertTrue(balancedCounts.containsKey(i) && balancedCounts.get(i) >= miniBatchSize / iterator.totalOutcomes()); } } }
Source:
public static boolean isPortInUse(int port) { if(port < 0 || port >= 65536) { return false; } try { new ServerSocket(port).close(); return false; } catch (IOException e) { return true; } }

Target:
public static boolean isPortInUse(int port) { if(port < 0 || port >= 65536) { return false; } try { new ServerSocket(port).close(); return false; } catch (IOException e) { } try (Socket socket = new Socket("localhost", port)) { return true; } catch (IOException e) { return false; } }
Source:
public static void writeSegmentFile(final TargetCollection<AllelicCount> snps, final String sampleName, final File outputFile) { try { final File targetsFromSNPCountsFile = File.createTempFile("targets-from-snps", ".tsv"); List<TargetCoverage> targetsFromSNPCounts = snps.targets().stream() .map(count -> count.toMinorAlleleFractionTargetCoverage("snp-target" + count.getContig() + ":" + count.getStart() + "_" + count.getEnd())).collect(Collectors.toList()); TargetCoverageUtils.writeTargetsWithCoverage(targetsFromSNPCountsFile, sampleName, targetsFromSNPCounts); RCBSSegmenter.writeSegmentFile(sampleName, targetsFromSNPCountsFile.getAbsolutePath(), outputFile.getAbsolutePath(), false); } catch (final IOException e) { throw new UserException.CouldNotCreateOutputFile("Could not create temporary output file during " + "SNP segmentation.", e); } }

Target:
public static void writeSegmentFile(final TargetCollection<AllelicCount> snps, final String sampleName, final File outputFile) { try { final File targetsFromSNPCountsFile = File.createTempFile("targets-from-snps", ".tsv"); List<TargetCoverage> targetsFromSNPCounts = snps.targets().stream() .map(count -> count.toMinorAlleleFractionTargetCoverage("snp-target" + count.getContig() + ":" + count.getStart() + "-" + count.getEnd())).collect(Collectors.toList()); TargetCoverageUtils.writeTargetsWithCoverage(targetsFromSNPCountsFile, sampleName, targetsFromSNPCounts); RCBSSegmenter.writeSegmentFile(sampleName, targetsFromSNPCountsFile.getAbsolutePath(), outputFile.getAbsolutePath(), false); } catch (final IOException e) { throw new UserException.CouldNotCreateOutputFile("Could not create temporary output file during " + "SNP segmentation.", e); } }
Source:
public WeldConfiguration(ServiceRegistry services, Deployment deployment) { Preconditions.checkArgumentNotNull(deployment, "deployment"); this.properties = init(services, deployment); this.proxyDumpFilePath = initProxyDumpFilePath(); this.proxyIgnoreFinalMethodsPattern = initProxyIgnoreFinalMethodsPattern(); StringJoiner logOutputBuilder = new StringJoiner(", ", "{", "}"); for (Entry<ConfigurationKey, Object> entry : properties.entrySet()) { logOutputBuilder.add(entry.getKey().get() + "=" + properties.get(entry.getKey())); } ConfigurationLogger.LOG.configurationInitialized(logOutputBuilder.toString()); }

Target:
public WeldConfiguration(ServiceRegistry services, Deployment deployment) { Preconditions.checkArgumentNotNull(deployment, "deployment"); this.properties = init(services, deployment); this.proxyDumpFilePath = initProxyDumpFilePath(); this.proxyIgnoreFinalMethodsPattern = initProxyIgnoreFinalMethodsPattern(); StringJoiner logOutputBuilder = new StringJoiner(", ", "{", "}"); for (Entry<ConfigurationKey, Object> entry : properties.entrySet()) { logOutputBuilder.add(entry.getKey().get() + "=" + entry.getValue()); } ConfigurationLogger.LOG.configurationInitialized(logOutputBuilder.toString()); }
Source:
public void stopCacheSafely(GridCacheContext<?, ?> cctx) { stopCacheSafely(cctx, true); }

Target:
private void stopCacheSafely(GridCacheContext<?, ?> cctx) { stopCacheSafely(cctx, true); }
Source:
public long getFromValueFromIntRange(AnnotatedTypeMirror atm) { AnnotationMirror anno = atm.getAnnotation(IntRange.class); if (AnnotationUtils.hasElementValue(anno, "from")) { return AnnotationUtils.getElementValue(anno, "from", Long.class, false); } long from; TypeMirror type = atm.getUnderlyingType(); switch (type.getKind()) { case INT: from = Integer.MIN_VALUE; break; case SHORT: from = Short.MIN_VALUE; break; case BYTE: from = Byte.MIN_VALUE; break; case CHAR: from = Character.MIN_VALUE; break; case DECLARED: String qualifiedName = TypesUtils.getQualifiedName((DeclaredType) type).toString(); switch (qualifiedName) { case "java.lang.Integer": from = Integer.MIN_VALUE; break; case "java.lang.Short": from = Short.MIN_VALUE; break; case "java.lang.Byte": from = Byte.MIN_VALUE; break; case "java.lang.Character": from = Character.MIN_VALUE; break; default: from = Long.MIN_VALUE; } break; default: from = Long.MIN_VALUE; } return from; }

Target:
public long getFromValueFromIntRange(AnnotatedTypeMirror atm) { AnnotationMirror anno = atm.getAnnotation(IntRange.class); if (AnnotationUtils.hasElementValue(anno, "from")) { return AnnotationUtils.getElementValue(anno, "from", Long.class, false); } long from; TypeMirror type = atm.getUnderlyingType(); switch (type.getKind()) { case INT: from = Integer.MIN_VALUE; break; case SHORT: from = Short.MIN_VALUE; break; case BYTE: from = Byte.MIN_VALUE; break; case CHAR: from = Character.MIN_VALUE; break; case LONG: from = Long.MIN_VALUE; break; case DECLARED: String qualifiedName = TypesUtils.getQualifiedName((DeclaredType) type).toString(); switch (qualifiedName) { case "java.lang.Integer": from = Integer.MIN_VALUE; break; case "java.lang.Short": from = Short.MIN_VALUE; break; case "java.lang.Byte": from = Byte.MIN_VALUE; break; case "java.lang.Character": from = Character.MIN_VALUE; break; case "java.lang.Long": from = Long.MIN_VALUE; break; default: throw new UserError( "Illegal type \"@IntRange " + qualifiedName + "\". @IntRange can be applied to Java integral types."); } break; default: throw new BugInCF(anno.toString() + " on a type of kind " + type.getKind()); } return from; }
Source:
public void missedUpdate() throws IOException { ByteArrayOutputStream buf = new ByteArrayOutputStream(); ReftableWriter writer = new ReftableWriter(buf) .setMinUpdateIndex(1) .setMaxUpdateIndex(3) .begin(); writer.writeRef(ref("refs/heads/a", 1), 1); writer.writeRef(ref("refs/heads/c", 3), 3); writer.finish(); byte[] base = buf.toByteArray(); byte[] delta = write(Arrays.asList( ref("refs/heads/b", 2), ref("refs/heads/c", 4)), 2); MergedReftable mr = merge(base, delta); assertEquals(1, mr.minUpdateIndex()); assertEquals(3, mr.maxUpdateIndex()); try (RefCursor rc = mr.allRefs()) { assertTrue(rc.next()); assertEquals("refs/heads/a", rc.getRef().getName()); assertEquals(id(1), rc.getRef().getObjectId()); assertEquals(1, rc.getRef().getUpdateIndex()); assertTrue(rc.next()); assertEquals("refs/heads/b", rc.getRef().getName()); assertEquals(id(2), rc.getRef().getObjectId()); assertEquals(2, rc.getRef().getUpdateIndex()); assertTrue(rc.next()); assertEquals("refs/heads/c", rc.getRef().getName()); assertEquals(id(3), rc.getRef().getObjectId()); assertEquals(3, rc.getRef().getUpdateIndex()); } }

Target:
public void missedUpdate() throws IOException { ByteArrayOutputStream buf = new ByteArrayOutputStream(); ReftableWriter writer = new ReftableWriter(buf) .setMinUpdateIndex(1) .setMaxUpdateIndex(3) .begin(); writer.writeRef(ref("refs/heads/a", 1), 1); writer.writeRef(ref("refs/heads/c", 3), 3); writer.finish(); byte[] base = buf.toByteArray(); byte[] delta = write(Arrays.asList( ref("refs/heads/b", 2), ref("refs/heads/c", 4)), 2); MergedReftable mr = merge(base, delta); try (RefCursor rc = mr.allRefs()) { assertTrue(rc.next()); assertEquals("refs/heads/a", rc.getRef().getName()); assertEquals(id(1), rc.getRef().getObjectId()); assertEquals(1, rc.getRef().getUpdateIndex()); assertTrue(rc.next()); assertEquals("refs/heads/b", rc.getRef().getName()); assertEquals(id(2), rc.getRef().getObjectId()); assertEquals(2, rc.getRef().getUpdateIndex()); assertTrue(rc.next()); assertEquals("refs/heads/c", rc.getRef().getName()); assertEquals(id(3), rc.getRef().getObjectId()); assertEquals(3, rc.getRef().getUpdateIndex()); } }
Source:
public void invalidateVisualState() { super.invalidateVisualState(); ObservableList<XYChart.Series<Double, Double>> lineChartData = FXCollections.observableArrayList(); double step = 0.01; double min = x.getLowerBound(); double max = x.getUpperBound(); Expr expr = new Apply( new Ident("putStrLn"), new Apply( new Ident("unwords"), new Apply( new Apply( new Ident("map"), new Ident("show") ), new Apply( new Apply( new Ident("map"), getExpr() ), new Ident(String.format(Locale.US,"[%f,%f..%f]", min, min+step, max)) ) ) ) ); try { String results = getPane().getGhciSession().get().pull(expr); LineChart.Series<Double, Double> series = new LineChart.Series<>(); ObservableList<XYChart.Data<Double, Double>> data = series.getData(); Iterator<String> v = Splitter.on(' ').split(results).iterator(); for (double i = min; i < max; i += step) { data.add(new XYChart.Data<>(i, Double.valueOf(v.next()))); } lineChartData.add(series); } catch (HaskellException | NoSuchElementException | NumberFormatException ignored) { assert Boolean.TRUE; } chart.setData(lineChartData); }

Target:
public void invalidateVisualState() { super.invalidateVisualState(); ObservableList<XYChart.Series<Double, Double>> lineChartData = FXCollections.observableArrayList(); double step = 0.01; double min = x.getLowerBound(); double max = x.getUpperBound(); Expr expr = new Apply( new Ident("putStrLn"), new Apply( new Ident("unwords"), new Apply( new Apply( new Ident("map"), new Ident("show") ), new Apply( new Apply( new Ident("map"), getExpr() ), new Ident(String.format(Locale.US, "[%f,%f..%f]", min, min+step, max)) ) ) ) ); try { String results = getPane().getGhciSession().get().pull(expr); LineChart.Series<Double, Double> series = new LineChart.Series<>(); ObservableList<XYChart.Data<Double, Double>> data = series.getData(); Iterator<String> v = Splitter.on(' ').split(results).iterator(); for (double i = min; i < max; i += step) { data.add(new XYChart.Data<>(i, Double.valueOf(v.next()))); } lineChartData.add(series); } catch (HaskellException | NoSuchElementException | NumberFormatException ignored) { } chart.setData(lineChartData); }
Source:
public java.lang.Class<? extends Rule> getType(Topology.Rule proto) { switch (proto.getType()) { case JUMP_RULE: return JumpRule.class; case LITERAL_RULE: return LiteralRule.class; case TRACE_RULE: return TraceRule.class; case NAT_RULE: if (proto.getMatchForwardFlow()) return ForwardNatRule.class; else if (proto.getMatchReturnFlow()) return ReverseNatRule.class; else throw new ZoomConvert.ConvertException("Rule: " + proto.getId() + " is neither a forward nor a " + "reverse NAT rule"); default: throw new ZoomConvert.ConvertException("Unknown rule " + "type: " + proto.getType()); } }

Target:
public Class<? extends Rule> getType(Topology.Rule proto) { switch (proto.getType()) { case JUMP_RULE: return JumpRule.class; case LITERAL_RULE: return LiteralRule.class; case TRACE_RULE: return TraceRule.class; case NAT_RULE: if (proto.getMatchForwardFlow()) return ForwardNatRule.class; else if (proto.getMatchReturnFlow()) return ReverseNatRule.class; else throw new ZoomConvert.ConvertException("Rule: " + proto.getId() + " is neither a forward nor a " + "reverse NAT rule"); default: throw new ZoomConvert.ConvertException("Unknown rule " + "type: " + proto.getType()); } }
Source:
private void processEntries(String registerName, String[] entries) { final List<byte[]> entriesAsBytes = Arrays.stream(entries) .map(e -> { try { final JsonNode jsonNode = canonicalJsonMapper.readFromBytes(e.getBytes(StandardCharsets.UTF_8)); entryValidator.validateEntry(registerName, jsonNode); return canonicalJsonMapper.writeToBytes(hashedEntry(jsonNode)); } catch (Throwable throwable) { throw new RuntimeException(throwable); } }) .collect(Collectors.toList()); entriesUpdateDAO.add(entriesAsBytes); }

Target:
private void processEntries(String registerName, String[] entries) { final List<byte[]> entriesAsBytes = Arrays.stream(entries) .map(e -> { try { final JsonNode jsonNode = canonicalJsonMapper.readFromBytes(e.getBytes(StandardCharsets.UTF_8)); entryValidator.validateEntry(registerName, jsonNode); return canonicalJsonMapper.writeToBytes(hashedEntry(jsonNode)); } catch (Exception ex) { throw Throwables.propagate(ex); } }) .collect(Collectors.toList()); entriesUpdateDAO.add(entriesAsBytes); }
Source:
private XDesktop simpleBootstrap(List<URL> jarUrls) throws IllegalAccessException, InvocationTargetException, BootstrapException, CreationException, IOException, ClassNotFoundException { URL[] urls = jarUrls.toArray(new URL[3]); Class<Bootstrap> clazz = (Class<Bootstrap>) Class.forName("com.sun.star.comp.helper.Bootstrap", true, new ChildFirstClassLoader(urls, null)); Bootstrap boot = null; try { boot = clazz.getDeclaredConstructor().newInstance(); } catch (InstantiationException | java.lang.IllegalArgumentException | NoSuchMethodException | SecurityException e1) { e1.printStackTrace(); } XComponentContext xContext = boot.bootstrap(); XMultiComponentFactory xServiceManager = xContext.getServiceManager(); Object desktop; try { desktop = xServiceManager.createInstanceWithContext("com.sun.star.frame.Desktop", xContext); } catch (Exception e) { throw new CreationException(e.getMessage()); } XDesktop resultDesktop = UnoRuntime.queryInterface(XDesktop.class, desktop); UnoRuntime.queryInterface(XComponentLoader.class, desktop); return resultDesktop; }

Target:
private XDesktop simpleBootstrap(List<URL> jarUrls) throws CreationException, BootstrapException { URL[] urls = jarUrls.toArray(new URL[1]); URLClassLoader loader = new URLClassLoader(urls, null); XComponentContext xContext = org.jabref.gui.openoffice.Bootstrap.bootstrap(loader); XMultiComponentFactory xServiceManager = xContext.getServiceManager(); Object desktop; try { desktop = xServiceManager.createInstanceWithContext("com.sun.star.frame.Desktop", xContext); } catch (Exception e) { throw new CreationException(e.getMessage()); } XDesktop resultDesktop = UnoRuntime.queryInterface(XDesktop.class, desktop); UnoRuntime.queryInterface(XComponentLoader.class, desktop); return resultDesktop; }
Source:
public DataSeriesReader(final DataSeriesType valueType, final EncodingParams params, final BitInputStream bitInputStream, final Map<Integer, InputStream> inputMap) { final EncodingFactory f = new EncodingFactory(); final Encoding<T> encoding = f.createEncoding(valueType, params.id); if (encoding == null) throw new RuntimeException("Encoding not found: value type=" + valueType.name() + ", encoding id=" + params.id.name()); encoding.fromByteArray(params.params); this.codec = encoding.buildCodec(inputMap, null); this.bitInputStream = bitInputStream; }

Target:
public DataSeriesReader(final DataSeriesType valueType, final EncodingParams params, final BitInputStream bitInputStream, final Map<Integer, InputStream> inputMap) { final EncodingFactory f = new EncodingFactory(); final Encoding<T> encoding = f.createEncoding(valueType, params.id); if (encoding == null) { throw new IllegalArgumentException("Encoding not found: value type=" + valueType.name() + ", encoding id=" + params.id.name()); } encoding.fromByteArray(params.params); this.codec = encoding.buildCodec(inputMap, null); this.bitInputStream = bitInputStream; }
Source:
public void validateExcept(String... prefixesToSkip) { validateFactoryOptions(tableFactory, allOptions); final Set<String> remainingOptionKeys = new HashSet<>(allOptions.keySet()); remainingOptionKeys.removeAll(consumedOptionKeys); for (String prefix : prefixesToSkip) { remainingOptionKeys.removeIf(key -> key.startsWith(prefix)); } if (remainingOptionKeys.size() > 0) { throw new ValidationException( String.format( "Unsupported options found for connector '%s'.\n\n" + "Unsupported options:\n\n" + "%s\n\n" + "Supported options:\n\n" + "%s", tableFactory.factoryIdentifier(), remainingOptionKeys.stream() .sorted() .collect(Collectors.joining("\n")), consumedOptionKeys.stream() .sorted() .collect(Collectors.joining("\n")))); } }

Target:
public void validateExcept(String... prefixesToSkip) { Preconditions.checkArgument(prefixesToSkip.length > 0, "Prefixes to skip can not be empty."); final List<String> prefixesList = Arrays.asList(prefixesToSkip); consumedOptionKeys.addAll(allOptions.keySet().stream() .filter(key -> prefixesList.stream().anyMatch(key::startsWith)) .collect(Collectors.toSet())); validate(); }
Source:
protected Tuple parseStringToTuple(String line) { try { JSONObject jsonObj = (JSONObject) jsonParser.parse(line); if (jsonObj != null) { return tupleFactory.newTuple(walkJson(jsonObj)); } else { LOG.warn("Could not json-decode string: " + line); incrCounter(JsonLoaderCounters.LinesParseError, 1L); return null; } } catch (ParseException e) { LOG.warn("Could not json-decode string: " + line, e); incrCounter(JsonLoaderCounters.LinesParseError, 1L); if (isInvalidRecordEnabled) { retMap.put("error_line", line); retMap.put("error_string", "LinesParseError"); return tupleFactory.newTuple(retMap); } else { return null; } } catch (NumberFormatException e) { LOG.warn("Very big number exceeds the scale of long: " + line, e); incrCounter(JsonLoaderCounters.LinesParseErrorBadNumber, 1L); if (isInvalidRecordEnabled) { retMap.put("error_line", line); retMap.put("error_string", "LinesParseError"); return tupleFactory.newTuple(retMap); } else { return null; } } catch (ClassCastException e) { LOG.warn("Could not convert to Json Object: " + line, e); incrCounter(JsonLoaderCounters.LinesParseError, 1L); if (isInvalidRecordEnabled) { retMap.put("error_line", line); retMap.put("error_string", "LinesParseError"); return tupleFactory.newTuple(retMap); } else { return null; } } }

Target:
protected Tuple parseStringToTuple(String line) { try { JSONObject jsonObj = (JSONObject) jsonParser.parse(line); if (jsonObj != null) { return tupleFactory.newTuple(walkJson(jsonObj)); } else { LOG.warn("Could not json-decode string: " + line); incrCounter(JsonLoaderCounters.LinesParseError, 1L); return null; } } catch (ParseException e) { LOG.warn("Could not json-decode string: " + line, e); incrCounter(JsonLoaderCounters.LinesParseError, 1L); return emitErrorTuple(line,"LinesParseError"); } catch (NumberFormatException e) { LOG.warn("Very big number exceeds the scale of long: " + line, e); incrCounter(JsonLoaderCounters.LinesParseErrorBadNumber, 1L); return emitErrorTuple(line,"LinesParseError"); } catch (ClassCastException e) { LOG.warn("Could not convert to Json Object: " + line, e); incrCounter(JsonLoaderCounters.LinesParseError, 1L); return emitErrorTuple(line,"LinesParseError"); } }
Source:
public void incrementWriteOps() { statistics.incrementWriteOps(1); }

Target:
private void incrementWriteOps() { if (statistics != null) { statistics.incrementWriteOps(1); } }
Source:
final public Ref exactRef(String name) throws IOException { return getRefDatabase().exactRef(name); }

Target:
public final Ref exactRef(String name) throws IOException { return getRefDatabase().exactRef(name); }
Source:
public void generateReportTimesPanelContentForSuiteWithoutStartedTests() { XmlSuite xmlSuite = new XmlSuite(); xmlSuite.setName("GITHUB_1931"); XmlTest xmlTest = new XmlTest(xmlSuite); List<XmlClass> xmlClasses = new ArrayList<>(); xmlClasses.add(new XmlClass(Object.class)); xmlTest.setXmlClasses(xmlClasses); ISuite iSuite = new FakeSuite(xmlTest); List<ISuite> suites = new ArrayList<>(); Model model = new Model(suites); XMLStringBuffer buffer = new XMLStringBuffer(); TimesPanel panel = new TimesPanel(model); panel.getContent(iSuite, buffer); assertThat(panel.getContent(iSuite, buffer), containsString("Total running time: 0 ms")); }

Target:
public void generateReportTimesPanelContentForSuiteWithoutStartedTests() { XmlTest xmlTest = createXmlTest("GITHUB_1931", "NPE", Object.class); ISuite iSuite = new FakeSuite(xmlTest); List<ISuite> suites = new ArrayList<>(); suites.add(iSuite); Model model = new Model(suites); TimesPanel panel = new TimesPanel(model); XMLStringBuffer buffer = new XMLStringBuffer(); panel.getContent(iSuite, buffer); assertTrue("TimesPanel contains total running time", panel.getContent(iSuite, buffer).contains("Total running time: 0 ms")); }
Source:
static ExitMode valueOf(int ordinal) { return ExitMode.values()[ordinal]; }

Target:
static ExitMode valueOf(int ordinal) { return CACHED_VALUES[ordinal]; }
Source:
public void perform(GraphRewrite event, EvaluationContext context, WindupVertexFrame payload) { ProjectModel project; if (payload instanceof ProjectModel) { project = (ProjectModel) payload; } else if (payload instanceof FileModel) { project = ((FileModel) payload).getProjectModel(); } else if (payload instanceof FileLocationModel) { project = ((FileLocationModel)payload).getFile().getProjectModel(); } else { return; } TechnologyUsageStatisticsService service = new TechnologyUsageStatisticsService(event.getGraphContext()); TechnologyUsageStatisticsModel model = service.get(project, this.technologyName); model.setOccurrenceCount(model.getOccurrenceCount() + this.count); TagSetModel tagModel = model.getTagModel(); if (tagModel == null) { tagModel = new TagSetService(event.getGraphContext()).getOrCreate(event, this.tags); model.setTagModel(tagModel); } if (!tagModel.getTags().equals(this.tags)) { Set<String> newSet = new HashSet<>(tagModel.getTags()); newSet.addAll(this.tags); tagModel = new TagSetService(event.getGraphContext()).getOrCreate(event, this.tags); model.setTagModel(tagModel); } }

Target:
public void perform(GraphRewrite event, EvaluationContext context, WindupVertexFrame payload) { ProjectModel project; if (payload instanceof ProjectModel) { project = (ProjectModel) payload; } else if (payload instanceof FileModel) { project = ((FileModel) payload).getProjectModel(); } else if (payload instanceof FileLocationModel) { project = ((FileLocationModel)payload).getFile().getProjectModel(); } else { return; } TechnologyUsageStatisticsService service = new TechnologyUsageStatisticsService(event.getGraphContext()); TechnologyUsageStatisticsModel model = service.getOrCreate(project, this.technologyName); model.setOccurrenceCount(model.getOccurrenceCount() + this.count); TagSetModel tagModel = model.getTagModel(); if (tagModel == null) { tagModel = new TagSetService(event.getGraphContext()).getOrCreate(event, this.tags); model.setTagModel(tagModel); } if (!tagModel.getTags().equals(this.tags)) { Set<String> newSet = new HashSet<>(tagModel.getTags()); newSet.addAll(this.tags); tagModel = new TagSetService(event.getGraphContext()).getOrCreate(event, this.tags); model.setTagModel(tagModel); } }
Source:
public void deleteExperimentsByIds(final List<Integer> experimentIdList) throws MiddlewareQueryException { final String experimentIds = StringUtils.join(experimentIdList, ","); try { this.getSession().flush(); final SQLQuery statement = this.getSession().createSQLQuery("delete e, ep, es, pheno, eprop " + "from nd_experiment e " + "left join nd_experiment_stock es on e.nd_experiment_id = es.nd_experiment_id " + "left join phenotype pheno on pheno.nd_experiment_id = e.nd_experiment_id " + "left join nd_experimentprop eprop on eprop.nd_experiment_id = e.nd_experiment_id " + "where e.nd_experiment_id in (" + experimentIds + ") "); statement.executeUpdate(); } catch (final HibernateException e) { this.logAndThrowException("Error in deleteExperimentsByLocation=" + experimentIds + " in DataSetDao: " + e.getMessage(), e); } }

Target:
public void deleteExperimentsByIds(final List<Integer> experimentIdList) throws MiddlewareQueryException { final String experimentIds = StringUtils.join(experimentIdList, ","); try { this.getSession().flush(); final SQLQuery statement = this.getSession().createSQLQuery("delete e, es, pheno, eprop " + "from nd_experiment e " + "left join nd_experiment_stock es on e.nd_experiment_id = es.nd_experiment_id " + "left join phenotype pheno on pheno.nd_experiment_id = e.nd_experiment_id " + "left join nd_experimentprop eprop on eprop.nd_experiment_id = e.nd_experiment_id " + "where e.nd_experiment_id in (" + experimentIds + ") "); statement.executeUpdate(); } catch (final HibernateException e) { this.logAndThrowException("Error in deleteExperimentsByLocation=" + experimentIds + " in DataSetDao: " + e.getMessage(), e); } }
Source:
public void turtleWriterTest() throws IOException { InputStream rdfInput = TurtleRecordWriter.class.getClassLoader().getResourceAsStream(RDF_INPUT_TEST); Model modelResult = ModelFactory.createDefaultModel().read(rdfInput, "", "RDF/XML"); OutputStream outputStream = new ByteArrayOutputStream(); TurtleRecordWriter writer= new TurtleRecordWriter(outputStream); writer.write(modelResult); Assert.assertNotNull(outputStream); outputStream.close(); }

Target:
public void turtleWriterTest() throws IOException { InputStream rdfInput = TurtleRecordWriter.class.getClassLoader().getResourceAsStream(RDF_INPUT_TEST); Model modelResult = ModelFactory.createDefaultModel().read(rdfInput, "", "RDF/XML"); OutputStream outputStream = new ByteArrayOutputStream(); TurtleRecordWriter writer= new TurtleRecordWriter(outputStream); writer.write(modelResult); Assert.assertNotNull(outputStream); outputStream.close(); rdfInput.close(); }
Source:
public static Transformer<ByteBuf, ByteBuf> all() { return INSTANCE; }

Target:
public static CollectBytes all() { return upTo(Integer.MAX_VALUE); }
Source:
private void setInitialState(PlexBindingConfig config) { if (connector != null) { PlexSession session = connector.getSessionByMachineId(config.getMachineIdentifier()); if (session == null) session = new PlexSession(); updateConfigFromSession(config, session); } }

Target:
private void setInitialState(PlexBindingConfig config) { if (connector != null) { PlexSession session = connector.getSessionByMachineId(config.getMachineIdentifier()); if (session == null) { session = new PlexSession(); } updateConfigFromSession(config, session); } }
Source:
public void run(ITextSelection selection) { IEditorInput input= fEditor.getEditorInput(); IDocumentProvider docProvider= fEditor.getDocumentProvider(); if (docProvider == null || input == null) return; IDocument document= docProvider.getDocument(input); if (document == null) return; IDocumentExtension3 docExtension= null; if (document instanceof IDocumentExtension3) docExtension= (IDocumentExtension3) document; else return; String indentStr= IndentAction.EMPTY_STR; IJavaProject javaProject= getProject(); if (javaProject == null) { return; } try { indentStr= IndentAction.getIndentationAsPerTextBlockSettings(document, selection.getOffset(), javaProject); } catch (BadLocationException e) { return; } try { int selectionOffset= selection.getOffset(); boolean setCaratPosition= selection.getLength() > 0 ? false : true; ITypedRegion partition= docExtension.getPartition(IJavaPartitions.JAVA_PARTITIONING, selectionOffset, false); if (!canAddTextBlock(partition, javaProject, selection)) { return; } DocumentCommand command= getDocumentCommand(document, javaProject, selection, indentStr); addTextBlock(document, command, setCaratPosition); } catch (BadLocationException e) { e.printStackTrace(); } catch (BadPartitioningException e) { } }

Target:
public void run(ITextSelection selection) { IEditorInput input= fEditor.getEditorInput(); IDocumentProvider docProvider= fEditor.getDocumentProvider(); if (docProvider == null || input == null) return; IDocument document= docProvider.getDocument(input); if (document == null) return; IDocumentExtension3 docExtension= null; if (document instanceof IDocumentExtension3) docExtension= (IDocumentExtension3) document; else return; String indentStr= IndentAction.EMPTY_STR; IJavaProject javaProject= getProject(); if (javaProject == null) { return; } try { indentStr= IndentAction.getIndentationAsPerTextBlockSettings(document, selection.getOffset(), javaProject); } catch (BadLocationException e) { return; } try { int selectionOffset= selection.getOffset(); boolean setCaratPosition= selection.getLength() > 0 ? false : true; ITypedRegion partition= docExtension.getPartition(IJavaPartitions.JAVA_PARTITIONING, selectionOffset, false); if (!canAddTextBlock(partition, javaProject, selection)) { return; } DocumentCommand command= getDocumentCommand(document, javaProject, selection, indentStr); addTextBlock(document, command, setCaratPosition); } catch (BadLocationException e) { } catch (BadPartitioningException e) { } }
Source:
private void prepareObservations() throws ParseException { Observation tempObservation = new Observation(); tempObservation.setObsDatetime(format.parse(date)); tempObservation.setConcept(concept); tempObservation.setValue(new Observation.ObservationValue("True")); tempObservation.setPerson(patient.getPerson()); String observationUuid = obsAdapter.createObservation(DEFAULT_CONFIG_NAME, tempObservation).getUuid(); observation = obsAdapter.getObservationByUuid(DEFAULT_CONFIG_NAME, observationUuid); }

Target:
private void prepareObservations() throws ParseException { Observation tempObservation = new Observation(); tempObservation.setObsDatetime(format.parse(date)); tempObservation.setConcept(concept); tempObservation.setValue(new Observation.ObservationValue("true")); tempObservation.setPerson(patient.getPerson()); String observationUuid = obsAdapter.createObservation(DEFAULT_CONFIG_NAME, tempObservation).getUuid(); observation = obsAdapter.getObservationByUuid(DEFAULT_CONFIG_NAME, observationUuid); }
Source:
protected void onCreate(Bundle savedInstanceState) { Timber.d("onCreate()"); super.onCreate(savedInstanceState); setContentView(R.layout.card_template_editor_activity); if (savedInstanceState == null) { mModelId = getIntent().getLongExtra("modelId", -1L); mEditedModel = null; mEditedModelFileName = null; mTemplateChanges = null; if (mModelId == -1) { Timber.e("CardTemplateEditor :: no model ID was provided"); finishWithoutAnimation(); return; } mNoteId = getIntent().getLongExtra("noteId", -1L); mOrdId = getIntent().getIntExtra("ordId", -1); } else { mModelId = savedInstanceState.getLong("modelId"); mNoteId = savedInstanceState.getLong("noteId"); mOrdId = savedInstanceState.getInt("ordId"); mEditedModelFileName = savedInstanceState.getString(INTENT_MODEL_FILENAME); if (mEditedModelFileName != null) { Timber.d("onCreate() loading saved model file %s", mEditedModelFileName); mEditedModel = getTempModel(mEditedModelFileName); } mTemplateChanges = (ArrayList<Object[]>)savedInstanceState.getSerializable("mTemplateChanges"); } Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); if (toolbar != null) { setSupportActionBar(toolbar); } startLoadingCollection(); }

Target:
protected void onCreate(Bundle savedInstanceState) { Timber.d("onCreate()"); super.onCreate(savedInstanceState); setContentView(R.layout.card_template_editor_activity); if (savedInstanceState == null) { mModelId = getIntent().getLongExtra("modelId", -1L); if (mModelId == -1) { Timber.e("CardTemplateEditor :: no model ID was provided"); finishWithoutAnimation(); return; } mNoteId = getIntent().getLongExtra("noteId", -1L); mStartingOrdId = getIntent().getIntExtra("ordId", -1); } else { mModelId = savedInstanceState.getLong("modelId"); mNoteId = savedInstanceState.getLong("noteId"); mStartingOrdId = savedInstanceState.getInt("ordId"); mTempModel = TemporaryModel.fromBundle(savedInstanceState); } enableToolbar(); startLoadingCollection(); }
Source:
public void start(ComponentContext context) { super.start(context); plugins.clear(); List<PluginDescriptor> descriptors = getDescriptors(XP_PLUGINS); for (PluginDescriptor descriptor : descriptors) { try { Class<?> clazz = Class.forName(descriptor.getKlass()); Constructor<?> constructor = clazz.getConstructor(PluginDescriptor.class); Plugin<?> plugin = (Plugin<?>) constructor.newInstance(descriptor); plugins.put(descriptor.getId(), plugin); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) { log.error(e, e); } } }

Target:
public void start(ComponentContext context) { super.start(context); plugins.clear(); List<PluginDescriptor> descriptors = getDescriptors(XP_PLUGINS); for (PluginDescriptor descriptor : descriptors) { try { Class<?> clazz = Class.forName(descriptor.getKlass()); Constructor<?> constructor = clazz.getConstructor(PluginDescriptor.class); Plugin<?> plugin = (Plugin<?>) constructor.newInstance(descriptor); plugins.put(descriptor.getId(), plugin); } catch (ReflectiveOperationException e) { String msg = String.format( "Failed to register plugin with id '%s' on '%s': error initializing class '%s' (%s).", descriptor.getId(), name, descriptor.getKlass(), e.toString()); log.error(msg, e); Framework.getRuntime().getMessageHandler().addError(msg); } } }
Source:
private static Map<String, RemoteServiceConfiguration> createRemoteServiceConfigurations( ServerListConfig serverListConfig, UserAgent versionedAgent, AuxiliaryRemotingParameters parameters) { return KeyedStream.of(serverListConfig.servers()) .map(server -> ImmutableServerListConfig.builder() .from(serverListConfig) .servers(ImmutableList.of(server)) .build()) .flatMapEntries((uri, singleServerConfig) -> { RemoteServiceConfiguration nonRetrying = ImmutableRemoteServiceConfiguration.builder() .remotingParameters(ImmutableAuxiliaryRemotingParameters.builder() .from(parameters) .userAgent(versionedAgent) .shouldRetry(false) .build()) .serverList(singleServerConfig) .build(); RemoteServiceConfiguration retrying = ImmutableRemoteServiceConfiguration.builder() .remotingParameters(ImmutableAuxiliaryRemotingParameters.builder() .from(parameters) .userAgent(versionedAgent) .shouldRetry(true) .build()) .serverList(singleServerConfig) .build(); return Stream.of( Maps.immutableEntry(getServiceNameForTimeLock(uri, false), nonRetrying), Maps.immutableEntry(getServiceNameForTimeLock(uri, true), retrying)); }) .collectToMap(); }

Target:
private static Map<String, RemoteServiceConfiguration> createRemoteServiceConfigurations( ServerListConfig serverListConfig, UserAgent versionedAgent, AuxiliaryRemotingParameters parameters) { return KeyedStream.of(serverListConfig.servers()) .map(server -> ImmutableServerListConfig.builder() .from(serverListConfig) .servers(ImmutableList.of(server)) .build()) .flatMapEntries((uri, singleServerConfig) -> Stream.of(false, true) .map(retry -> createSingleServiceConfigurationMapping( uri, singleServerConfig, parameters, versionedAgent, retry))) .collectToMap(); }
Source:
public JvmMonitor getJvmMonitor( DataSourceTaskIdHolder dataSourceTaskIdHolder ) { return new JvmMonitor(MonitorsConfig.mapOfDimensionAndTaskID( dataSourceTaskIdHolder.getDataSource(), dataSourceTaskIdHolder.getTaskId() )); }

Target:
public JvmMonitor getJvmMonitor( DataSourceTaskIdHolder dataSourceTaskIdHolder ) { return new JvmMonitor(MonitorsConfig.mapOfDatasourceAndTaskID( dataSourceTaskIdHolder.getDataSource(), dataSourceTaskIdHolder.getTaskId() )); }
Source:
private void sendFailureResponse(final MessageMetadata metadata, final ProtocolInfo protocolInfo, final OsgpException exception) { final DeviceMessageMetadata deviceMessageMetadata = new DeviceMessageMetadata( metadata.getDeviceIdentification(), metadata.getOrganisationIdentification(), metadata.getCorrelationUid(), metadata.getMessageType(), metadata.getMessagePriority(), metadata.getScheduleTime()); final ProtocolResponseMessage responseMessage = new ProtocolResponseMessage.Builder() .deviceMessageMetadata(deviceMessageMetadata).domain(metadata.getDomain()) .domainVersion(metadata.getDomainVersion()).result(ResponseMessageResultType.NOT_OK) .osgpException(exception).dataObject(null).retryCount(metadata.getRetryCount()) .scheduled(metadata.isScheduled()).build(); this.protocolResponseMessageSender.send(responseMessage, DeviceFunction.GET_FIRMWARE_FILE.name(), protocolInfo, metadata); }

Target:
private void sendFailureResponse(final MessageMetadata metadata, final ProtocolInfo protocolInfo, final OsgpException exception) { final ProtocolResponseMessage responseMessage = new ProtocolResponseMessage.Builder() .deviceMessageMetadata(new DeviceMessageMetadata(metadata)).domain(metadata.getDomain()) .domainVersion(metadata.getDomainVersion()).result(ResponseMessageResultType.NOT_OK) .osgpException(exception).dataObject(null).retryCount(metadata.getRetryCount()) .scheduled(metadata.isScheduled()).build(); this.protocolResponseMessageSender.send(responseMessage, DeviceFunction.GET_FIRMWARE_FILE.name(), protocolInfo, metadata); }
Source:
BlobAsyncClient(AzureBlobStorageBuilder azureBlobStorageBuilder, String snapshot) { this.blobAsyncRawClient = new BlobAsyncRawClient(azureBlobStorageBuilder.build()); this.snapshot = snapshot; }

Target:
BlobAsyncClient(AzureBlobStorageBuilder azureBlobStorageBuilder, String snapshot) { this.blobAsyncRawClient = new BlobAsyncRawClient(azureBlobStorageBuilder.build(), snapshot); }
Source:
private void addRow(LineTcpMeasurementEvent event) { if (error) { return; } long timestamp = event.getTimestamp(); Row row = writer.newRow(timestamp); try { for (int i = 0; i < nMeasurementValues; i++) { int columnType = colTypes.getQuick(i); int columnIndex = colIndexMappings.getQuick(i); CairoLineProtoParserSupport.writers.getQuick(columnType).write(row, columnIndex, event.getValue(i)); } row.append(); } catch (BadCastException ignore) { row.cancel(); } writer.commit(); }

Target:
private void addRow(LineTcpMeasurementEvent event) { if (error) { return; } Row row = null; try { long timestamp = event.getTimestamp(); row = writer.newRow(timestamp); for (int i = 0; i < nMeasurementValues; i++) { int columnType = colTypes.getQuick(i); int columnIndex = colIndexMappings.getQuick(i); CairoLineProtoParserSupport.writers.getQuick(columnType).write(row, columnIndex, event.getValue(i)); } row.append(); } catch (NumericException | CairoException | BadCastException ignore) { if (null != row) { row.cancel(); } return; } nUncommitted++; if (nUncommitted > maxUncommittedRows) { commit(); } }
Source:
private List<ProgramState> copyConstraintFromTo(SymbolicValue from, SymbolicValue to, ProgramState programState, BooleanConstraint booleanConstraint) { List<ProgramState> states = new ArrayList<>(); states.add(programState); PMap<Class<? extends Constraint>, Constraint> leftConstraints = programState.getConstraints(from); if (leftConstraints != null) { leftConstraints.forEach((d, c) -> { List<ProgramState> newStates = new ArrayList<>(); for (ProgramState state : states) { if(ObjectConstraint.class.equals(d)) { if(((ObjectConstraint) c).isNull()) { newStates.addAll(to.setConstraint(state, shouldNotInverse().equals(booleanConstraint) ? c : c.inverse())); } else if(shouldNotInverse().equals(booleanConstraint)) { newStates.addAll(to.setConstraint(state, c)); } else { newStates.add(state); } continue; } else if(BooleanConstraint.class.equals(d)) { newStates.addAll(to.setConstraint(state, shouldNotInverse().equals(booleanConstraint) ? c : c.inverse())); continue; } Constraint constraint = shouldNotInverse().equals(booleanConstraint) ? c : c.inverse(); if (constraint == null) { PMap<Class<? extends Constraint>, Constraint> constraints = state.getConstraints(to); if (constraints != null) { newStates.add(state.addConstraints(to, constraints.remove(c.getClass()))); } else { newStates.add(state); } } else { newStates.addAll(to.setConstraint(state, constraint)); } } states.clear(); states.addAll(newStates); }); } return states; }

Target:
private List<ProgramState> copyConstraintFromTo(SymbolicValue from, SymbolicValue to, ProgramState programState, BooleanConstraint booleanConstraint) { List<ProgramState> states = new ArrayList<>(); states.add(programState); PMap<Class<? extends Constraint>, Constraint> leftConstraints = programState.getConstraints(from); if (leftConstraints != null) { leftConstraints.forEach((d, c) -> { List<ProgramState> newStates = new ArrayList<>(); Constraint constraint = shouldNotInverse().equals(booleanConstraint) ? c : c.inverse(); states.forEach(state -> { if (constraint == null) { PMap<Class<? extends Constraint>, Constraint> constraints = state.getConstraints(to); if (constraints != null) { newStates.add(state.removeConstraintsOnDomain(to, c.getClass())); } else { newStates.add(state); } } else { if (ObjectConstraint.NULL == constraint && c != constraint) { newStates.add(state); } else { newStates.addAll(to.setConstraint(state, constraint)); } } }); states.clear(); states.addAll(newStates); }); } return states; }
Source:
public static void main(String[] args) { setExceptionHandler(() -> System.exit(1)); Integer containerId = Integer.valueOf(System.getenv(ShellCommandConfig.ENV_CONTAINER_ID())); log.info(String.format("Got container ID: %d", containerId)); String coordinatorUrl = System.getenv(ShellCommandConfig.ENV_COORDINATOR_URL()); log.info(String.format("Got coordinator URL: %s", coordinatorUrl)); int delay = new Random().nextInt(SamzaContainer.DEFAULT_READ_JOBMODEL_DELAY_MS()) + 1; JobModel jobModel = SamzaContainer.readJobModel(coordinatorUrl, delay); Config config = jobModel.getConfig(); JobConfig jobConfig = new JobConfig(config); if (jobConfig.getName().isEmpty()) { throw new SamzaException("can not find the job name"); } String jobName = jobConfig.getName().get(); String jobId = jobConfig.getJobId().getOrElse(ScalaToJavaUtils.defaultValue("1")); MDC.put("containerName", "samza-container-" + containerId); MDC.put("jobName", jobName); MDC.put("jobId", jobId); new LocalContainerRunner(jobModel, containerId).run(null); }

Target:
public static void main(String[] args) throws Exception { setExceptionHandler(() -> { log.info("Exiting process now."); System.exit(1); }); Integer containerId = Integer.valueOf(System.getenv(ShellCommandConfig.ENV_CONTAINER_ID())); log.info(String.format("Got container ID: %d", containerId)); String coordinatorUrl = System.getenv(ShellCommandConfig.ENV_COORDINATOR_URL()); log.info(String.format("Got coordinator URL: %s", coordinatorUrl)); int delay = new Random().nextInt(SamzaContainer.DEFAULT_READ_JOBMODEL_DELAY_MS()) + 1; JobModel jobModel = SamzaContainer.readJobModel(coordinatorUrl, delay); Config config = jobModel.getConfig(); JobConfig jobConfig = new JobConfig(config); if (jobConfig.getName().isEmpty()) { throw new SamzaException("can not find the job name"); } String jobName = jobConfig.getName().get(); String jobId = jobConfig.getJobId().getOrElse(ScalaToJavaUtils.defaultValue("1")); MDC.put("containerName", "samza-container-" + containerId); MDC.put("jobName", jobName); MDC.put("jobId", jobId); StreamApplication streamApp = TaskFactoryUtil.createStreamApplication(config); new LocalContainerRunner(jobModel, containerId).run(streamApp); }