auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void beforeClass() throws Exception { super.beforeClass(); System.out.println("START " + CLASS_NAME + " at " + new Date(System.currentTimeMillis())); _gSetupTool.addCluster(CLUSTER_NAME, true); _gSetupTool.addResourceToCluster(CLUSTER_NAME, TEST_DB, _PARTITIONS, STATE_MODEL); for (int i = 0; i < NODE_NR; i++) { String storageNodeName = PARTICIPANT_PREFIX + "_" + (START_PORT + i); _gSetupTool.addInstanceToCluster(CLUSTER_NAME, storageNodeName); } _gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, TEST_DB, _replica); for (int i = 0; i < NODE_NR; i++) { String instanceName = PARTICIPANT_PREFIX + "_" + (START_PORT + i); _participants[i] = new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, instanceName); _participants[i].syncStart(); } String controllerName = CONTROLLER_PREFIX + "_0"; _controller = new ClusterControllerManager(ZK_ADDR, CLUSTER_NAME, controllerName); _controller.syncStart(); _clusterVerifier = new BestPossibleExternalViewVerifier.Builder(CLUSTER_NAME).setZkClient(_gZkClient) .setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME) .build(); Assert.assertTrue(_clusterVerifier.verifyByPolling()); Assert.assertTrue(_clusterVerifier.verifyByPolling()); _manager = HelixManagerFactory .getZKHelixManager(CLUSTER_NAME, "Admin", InstanceType.ADMINISTRATOR, ZK_ADDR); _manager.connect(); }

Target:
public void beforeClass() throws Exception { super.beforeClass(); System.out.println("START " + CLASS_NAME + " at " + new Date(System.currentTimeMillis())); _gSetupTool.addCluster(CLUSTER_NAME, true); _gSetupTool.addResourceToCluster(CLUSTER_NAME, TEST_DB, _PARTITIONS, STATE_MODEL); for (int i = 0; i < NODE_NR; i++) { String storageNodeName = PARTICIPANT_PREFIX + "_" + (START_PORT + i); _gSetupTool.addInstanceToCluster(CLUSTER_NAME, storageNodeName); } _gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, TEST_DB, _replica); for (int i = 0; i < NODE_NR; i++) { String instanceName = PARTICIPANT_PREFIX + "_" + (START_PORT + i); _participants[i] = new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, instanceName); _participants[i].syncStart(); } String controllerName = CONTROLLER_PREFIX + "_0"; _controller = new ClusterControllerManager(ZK_ADDR, CLUSTER_NAME, controllerName); _controller.syncStart(); _clusterVerifier = new BestPossibleExternalViewVerifier.Builder(CLUSTER_NAME).setZkClient(_gZkClient) .setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME) .build(); Assert.assertTrue(_clusterVerifier.verifyByPolling()); _manager = HelixManagerFactory .getZKHelixManager(CLUSTER_NAME, "Admin", InstanceType.ADMINISTRATOR, ZK_ADDR); _manager.connect(); }
Source:
public FacilityCreated(Facility facility) { this.facility = facility; this.message = formatMessage("Facility created: %s",facility); }

Target:
public FacilityCreated(Facility facility) { this.facility = facility; this.message = formatMessage("Facility created %s.",facility); }
Source:
private void generateIndexes() { mongoOperations.getCollection(collection).createIndex(new BasicDBObject( DBObjectToVariantConverter.CHROMOSOME_FIELD, 1) .append(DBObjectToVariantConverter.START_FIELD, 1) .append(DBObjectToVariantConverter.END_FIELD, 1) .append("background", true)); mongoOperations.getCollection(collection).createIndex(new BasicDBObject( DBObjectToVariantConverter.IDS_FIELD, 1).append("background", true)); String filesStudyIdField = String.format("%s.%s", DBObjectToVariantConverter.FILES_FIELD, DBObjectToVariantSourceEntryConverter.STUDYID_FIELD); String filesFileIdField = String.format("%s.%s", DBObjectToVariantConverter.FILES_FIELD, DBObjectToVariantSourceEntryConverter.FILEID_FIELD); mongoOperations.getCollection(collection).createIndex( new BasicDBObject(filesStudyIdField, 1).append(filesFileIdField, 1).append("background", true)); mongoOperations.getCollection(collection).createIndex(new BasicDBObject( "annot.xrefs.id", 1).append("background", true)); mongoOperations.getCollection(collection).createIndex(new BasicDBObject("annot", 1).append("background", true)); }

Target:
private void generateIndexes() { mongoOperations.getCollection(collection).createIndex(new BasicDBObject( VariantToDBObjectConverter.CHROMOSOME_FIELD, 1).append(VariantToDBObjectConverter.START_FIELD, 1) .append(VariantToDBObjectConverter.END_FIELD, 1) .append(BACKGROUND_INDEX, true)); mongoOperations.getCollection(collection).createIndex(new BasicDBObject( VariantToDBObjectConverter.IDS_FIELD, 1).append(BACKGROUND_INDEX, true)); String filesStudyIdField = String.format("%s.%s", VariantToDBObjectConverter.FILES_FIELD, VariantSourceEntryToDBObjectConverter.STUDYID_FIELD); String filesFileIdField = String.format("%s.%s", VariantToDBObjectConverter.FILES_FIELD, VariantSourceEntryToDBObjectConverter.FILEID_FIELD); mongoOperations.getCollection(collection).createIndex( new BasicDBObject(filesStudyIdField, 1).append(filesFileIdField, 1).append(BACKGROUND_INDEX, true)); mongoOperations.getCollection(collection) .createIndex(new BasicDBObject(ANNOTATION_XREF_ID_FIELD, 1).append(BACKGROUND_INDEX, true)); mongoOperations.getCollection(collection) .createIndex(new BasicDBObject(ANNOTATION_FIELD, 1).append(BACKGROUND_INDEX, true)); }
Source:
private void updateTemplateEngine(CompletionContext context) { ICompilationUnit cu = (ICompilationUnit) context.getEnclosingElement().getAncestor(IJavaElement.COMPILATION_UNIT); ASTParser parser = createParser(cu); IBinding res = parser.createBindings(new IJavaElement { context.getEnclosingElement() }, null); if (res.length > 0 && res[0] != null) { parser = createParser(cu); CompilationUnit cuRoot = (CompilationUnit) parser.createAST(null); ASTNode completionNode = cuRoot.findDeclaringNode(res[0].getKey()); ASTNode bestNode = new ASTNode {completionNode}; int invOffset = context.getOffset(); completionNode.accept(new ASTVisitor() { @Override public boolean visit(ExpressionStatement node) { int start = node.getStartPosition(); if (invOffset > start && start > bestNode[0].getStartPosition()) { bestNode[0] = node; } return true; } }); completionNode = bestNode[0]; ASTNode completionNodeParent = completionNode.getParent(); postfixCompletionTemplateEngine.setASTNodes(completionNode, completionNodeParent); } }

Target:
private void updateTemplateEngine(CompletionContext context) { IJavaElement enclosingElement= context.getEnclosingElement(); if (enclosingElement == null) { postfixCompletionTemplateEngine.setASTNodes(null, null); return; } ICompilationUnit cu = (ICompilationUnit) enclosingElement.getAncestor(IJavaElement.COMPILATION_UNIT); ASTParser parser = createParser(cu); IBinding res = parser.createBindings(new IJavaElement { enclosingElement }, null); if (res.length > 0 && res[0] != null) { parser = createParser(cu); CompilationUnit cuRoot = (CompilationUnit) parser.createAST(null); ASTNode completionNode = cuRoot.findDeclaringNode(res[0].getKey()); ASTNode bestNode = new ASTNode {completionNode}; int invOffset = context.getOffset() - context.getToken().length - 1; completionNode.accept(new ASTVisitor() { @Override public boolean visit(ExpressionStatement node) { int start = node.getStartPosition(); if (invOffset > start && start > bestNode[0].getStartPosition()) { bestNode[0] = node; } return true; } @Override public boolean visit(SimpleName node) { int start = node.getStartPosition(); if (invOffset > start && start > bestNode[0].getStartPosition()) { bestNode[0] = node; } return true; } @Override public boolean visit(QualifiedName node) { int start = node.getStartPosition(); if (invOffset > start && start > bestNode[0].getStartPosition()) { bestNode[0] = node; } return true; } }); completionNode = bestNode[0]; ASTNode completionNodeParent = completionNode.getParent(); postfixCompletionTemplateEngine.setASTNodes(completionNode, completionNodeParent); } }
Source:
public VolumeClassification getVolumeClassification() { if (volumeClassification == null) { if (active) { return VolumeClassification.Volume; } return VolumeClassification.Snapshot; } return volumeClassification; }

Target:
public VolumeClassification getVolumeClassification() { if (volumeClassification == null) { return (active ? VolumeClassification.Volume : VolumeClassification.Snapshot); } return volumeClassification; }
Source:
public static final String formatPercentage(double value) { NumberFormat percentFormat = NumberFormat.getPercentInstance(); percentFormat.setMaximumFractionDigits(1); String result = percentFormat.format(value); return result; }

Target:
public static final String formatPercentage(double value) { NumberFormat percentFormat = NumberFormat.getPercentInstance(); percentFormat.setMaximumFractionDigits(1); return percentFormat.format(value); }
Source:
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (!super.equals(o)) return false; GenericGraph that = (GenericGraph) o; return Objects.equals(jungGraph, that.jungGraph) && Objects.equals(vertexToIdMap, that.vertexToIdMap) && Objects.equals(edgeToIdMap, that.edgeToIdMap) && Objects.equals(focusStrategy, that.focusStrategy) && Objects.equals(graphInfo, that.graphInfo); }

Target:
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (!super.equals(o)) return false; GenericGraph that = (GenericGraph) o; return Objects.equals(vertexToIdMap, that.vertexToIdMap) && Objects.equals(edgeToIdMap, that.edgeToIdMap) && Objects.equals(focusStrategy, that.focusStrategy); }
Source:
public ListenableFuture<?> isBlocked() { switch (state) { case CONSUMING_INPUT: return NOT_BLOCKED; case SPILLING_INPUT: return spillInProgress; case LOOKUP_SOURCE_BUILT: return lookupSourceNotNeeded.get(); case LOOKUP_SOURCE_SPILLED: return spilledLookupSourceHandle.getUnspillingOrDisposeRequested(); case LOOKUP_SOURCE_UNSPILLING: return unspillInProgress.get(); case LOOKUP_SOURCE_UNSPILLED_AND_BUILT: return spilledLookupSourceHandle.getDisposeRequested(); case DISPOSED: return lookupSourceFactoryDestroyed; } throw new IllegalStateException("Unhandled state: " + state); }

Target:
public ListenableFuture<?> isBlocked() { switch (state) { case CONSUMING_INPUT: return NOT_BLOCKED; case SPILLING_INPUT: return spillInProgress; case LOOKUP_SOURCE_BUILT: return lookupSourceNotNeeded.orElseThrow(() -> new IllegalStateException("Lookup source built, but disposal future not set")); case INPUT_SPILLED: return spilledLookupSourceHandle.getUnspillingOrDisposeRequested(); case INPUT_UNSPILLING: return unspillInProgress.orElseThrow(() -> new IllegalStateException("Unspilling in progress, but unspilling future not set")); case INPUT_UNSPILLED_AND_BUILT: return spilledLookupSourceHandle.getDisposeRequested(); case DISPOSED: return lookupSourceFactoryDestroyed; } throw new IllegalStateException("Unhandled state: " + state); }
Source:
public void signupViaFacebook(String code, String state) { if (code == null) { includeAsList("messages", i18n("error", "error.signup.facebook.unknown")); redirectTo(SignupController.class).signupForm(); return; } try { String rawToken = facebook.buildToken(code); SignupInfo signupInfo = facebook.getSignupInfo(); User existantFacebookUser = users.findByEmailAndMethod(signupInfo.getEmail(), MethodType.FACEBOOK); if (existantFacebookUser != null) { access.login(existantFacebookUser); redirectToRightUrl(state); return; } User existantGoogleUser = users.findByEmailAndMethod(signupInfo.getEmail(), MethodType.GOOGLE); if (existantGoogleUser != null) { mergeLoginMethod.mergeLoginMethods(rawToken, existantGoogleUser, MethodType.FACEBOOK); logMessages(existantGoogleUser); redirectToRightUrl(state); return; } User existantBrutalUser = users.findByEmailAndMethod(signupInfo.getEmail(), MethodType.BRUTAL); if (existantBrutalUser != null) { mergeLoginMethod.mergeLoginMethods(rawToken, existantBrutalUser, MethodType.FACEBOOK); logMessages(existantBrutalUser); redirectToRightUrl(state); return; } createNewUser(rawToken, signupInfo); redirectToRightUrl(state); } catch (IllegalArgumentException e) { LOG.error("unable to signup user with facebook", e); includeAsList("messages", i18n("error", "error.signup.facebook.unknown")); redirectTo(SignupController.class).signupForm(); return; } }

Target:
public void signupViaFacebook(String code, String state) { if (code == null) { includeAsList("messages", i18n("error", "error.signup.facebook.unknown")); redirectTo(SignupController.class).signupForm(); return; } Token token = service.getAccessToken(null, new Verifier(code)); SocialAPI facebookAPI = new FacebookAPI(service, token); loginManager.merge(MethodType.FACEBOOK, facebookAPI); redirectToRightUrl(state); }
Source:
public Map<String, Object> toMap() { Base64.Encoder encoder = Base64.getUrlEncoder(); HashMap<String, Object> map = new HashMap(); map.put("credentialId", encoder.encodeToString(id)); map.put("isResidentCredential", isResidentCredential); map.put("rpId", rpId); map.put("privateKey", encoder.encodeToString(privateKey.getEncoded())); if (userHandle != null) map.put("userHandle", encoder.encodeToString(userHandle)); map.put("signCount", signCount); return map; }

Target:
public Map<String, Object> toMap() { Base64.Encoder encoder = Base64.getUrlEncoder(); Map<String, Object> map = new HashMap<String, Object>(); map.put("credentialId", encoder.encodeToString(id)); map.put("isResidentCredential", isResidentCredential); map.put("rpId", rpId); map.put("privateKey", encoder.encodeToString(privateKey.getEncoded())); map.put("signCount", signCount); if (userHandle != null) { map.put("userHandle", encoder.encodeToString(userHandle)); } return Collections.unmodifiableMap(map); }
Source:
public RequestListener(int port, LionConfChange lionConfChange, HttpClientSingle cmdbHttpClient) throws IOException { this.serversocket = new ServerSocket(port); this.params = new SyncBasicHttpParams(); this.params .setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 120000) .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024) .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false) .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true) .setParameter(CoreProtocolPNames.ORIGIN_SERVER, "HttpComponents/1.1"); HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpResponseInterceptor[] { new ResponseDate(), new ResponseServer(), new ResponseContent(), new ResponseConnControl() }); HttpRequestHandlerRegistry reqistry = new HttpRequestHandlerRegistry(); reqistry.register("/search*", new HttpSearchHandler()); reqistry.register("/scaleout*", new HttpScalaoutHandler(lionConfChange, cmdbHttpClient)); reqistry.register("*", new HttpFallbackHandler()); this.httpService = new HttpService( httpproc, new DefaultConnectionReuseStrategy(), new DefaultHttpResponseFactory(), reqistry, this.params); }

Target:
public RequestListener(int port, LionConfChange lionConfChange, HttpClientSingle cmdbHttpClient) throws IOException { this.serversocket = new ServerSocket(port); this.params = new SyncBasicHttpParams(); this.params .setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 120000) .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024) .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false) .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true) .setParameter(CoreProtocolPNames.ORIGIN_SERVER, "HttpComponents/1.1"); HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpResponseInterceptor[] { new ResponseDate(), new ResponseServer(), new ResponseContent(), new ResponseConnControl() }); HttpRequestHandlerRegistry reqistry = new HttpRequestHandlerRegistry(); reqistry.register("/scaleout*", new HttpScalaoutHandler(lionConfChange, cmdbHttpClient)); reqistry.register("*", new HttpFallbackHandler()); this.httpService = new HttpService( httpproc, new DefaultConnectionReuseStrategy(), new DefaultHttpResponseFactory(), reqistry, this.params); }
Source:
public void test() { TestNG tng = create(ParameterInjectAndOptionSample.class); tng.run(); }

Target:
public void test() { TestNG tng = create(ParameterInjectAndOptionSample.class); TestListenerAdapter tla = new TestListenerAdapter(); tng.addListener((ITestNGListener) tla); tng.run(); Assert.assertEquals(tla.getPassedTests().size(), 1); }
Source:
public void close() { if (isClosed.compareAndSet(false, true)) { ShutdownRunner shutdownRunner = new ShutdownRunner(); shutdownRunner.runShutdownCallbackSafely(super::close); shutdownRunner.runShutdownCallbackSafely(cleaner::close); shutdownRunner.runShutdownCallbackSafely(keyValueService::close); shutdownRunner.runShutdownCallbackSafely(() -> shutdownExecutor(deleteExecutor)); shutdownRunner.runShutdownCallbackSafely(() -> shutdownExecutor(getRangesExecutor)); shutdownRunner.runShutdownCallbackSafely(this::closeLockServiceIfPossible); for (Runnable callback : Lists.reverse(closingCallbacks)) { shutdownRunner.runShutdownCallbackSafely(callback); } shutdownRunner.runShutdownCallbackSafely(metricsManager::deregisterMetrics); if (shutdownRunner.isFailed()) { throw new SafeRuntimeException("Close failed."); } } }

Target:
public void close() { if (!isClosed.compareAndSet(false, true)) { return; } try (ShutdownRunner shutdownRunner = new ShutdownRunner()) { shutdownRunner.shutdownSafely(super::close); shutdownRunner.shutdownSafely(cleaner::close); shutdownRunner.shutdownSafely(keyValueService::close); shutdownRunner.shutdownSafely(() -> shutdownExecutor(deleteExecutor)); shutdownRunner.shutdownSafely(() -> shutdownExecutor(getRangesExecutor)); shutdownRunner.shutdownSafely(this::closeLockServiceIfPossible); for (Runnable callback : Lists.reverse(closingCallbacks)) { shutdownRunner.shutdownSafely(callback); } shutdownRunner.shutdownSafely(metricsManager::deregisterMetrics); } }
Source:
public SessionCacheCleaner( SchemaFactory<ReviewDb> reviewDbFactory, @Named(WebSession.CACHE_NAME) final Cache<ActiveSession.Key, ActiveSession> cache) throws OrmException { this.activeSessionAccess = reviewDbFactory.open().activeSessions(); this.cache = cache; }

Target:
public SessionCacheCleaner( SchemaFactory<ReviewDb> reviewDbFactory, @Named(WebSession.CACHE_NAME) final Cache<ActiveSession.Key, ActiveSession> cache) { this.reviewDbFactory = reviewDbFactory; this.cache = cache; }
Source:
public PythonProgramOptions(CommandLine line) throws CliArgsException { super(line); isPython = isPython(line); pythonConfiguration = PythonDependencyUtils.parsePythonDependencyConfiguration(line); if (entryPointClass == null) { entryPointClass = "org.apache.flink.client.python.PythonDriver"; } }

Target:
public PythonProgramOptions(CommandLine line) throws CliArgsException { super(line); isPythonEntryPoint = isPythonEntryPoint(line); pythonConfiguration = PythonDependencyUtils.parsePythonDependencyConfiguration(line); if (entryPointClass == null) { entryPointClass = "org.apache.flink.client.python.PythonDriver"; } }
Source:
public void run() throws Exception { List<ReportParam> partialReport1 = Lists.newArrayList( new ReportParam("param1.paramA.I", "3"), new ReportParam("param1.paramA.III", "6"), new ReportParam("param1.paramB", "4")); List<ReportParam> partialReport2 = Lists.newArrayList( new ReportParam("param2", "12"), new ReportParam("param1.paramA.II", "2")); AvroTestUtils.createLocalAvroDataStore(partialReport1, inputPartialReportsBasePath + "/report1"); AvroTestUtils.createLocalAvroDataStore(partialReport2, inputPartialReportsBasePath + "/report2"); PortBindings portBindings = new PortBindings( ImmutableMap.of("partial_reports", new Path(inputPartialReportsBasePath)), ImmutableMap.of("report", new Path(outputReportPath))); Configuration conf = new Configuration(false); reportMerger.run(portBindings, conf, Collections.emptyMap()); JsonObject actualReportJson = readJson(outputReportPath); String expectedReportJsonString = "{" + " param1: {" + " paramA: {" + " I: 3," + " II: 2," + " III: 6" + " }," + " paramB: 4" + " }," + " param2: 12" + "}"; JsonObject expectedJsonReport = jsonParser.parse(expectedReportJsonString).getAsJsonObject(); assertEquals(expectedJsonReport, actualReportJson); }

Target:
public void run() throws Exception { List<ReportParam> partialReport1 = Lists.newArrayList( new ReportParam("param1.paramA.I", "3"), new ReportParam("param1.paramA.III", "6"), new ReportParam("param1.paramB", "4")); List<ReportParam> partialReport2 = Lists.newArrayList( new ReportParam("param2", "12"), new ReportParam("param1.paramA.II", "2")); AvroTestUtils.createLocalAvroDataStore(partialReport1, inputPartialReportsBasePath + "/report1"); AvroTestUtils.createLocalAvroDataStore(partialReport2, inputPartialReportsBasePath + "/report2"); PortBindings portBindings = new PortBindings( ImmutableMap.of("partial_reports", new Path(inputPartialReportsBasePath)), ImmutableMap.of("report", new Path(outputReportPath))); Configuration conf = new Configuration(false); reportMerger.run(portBindings, conf, Collections.emptyMap()); JsonObject actualReportJson = readJson(outputReportPath); JsonObject expectedJsonReport = readJsonFromClasspath("/eu/dnetlib/iis/common/report/report_merged.json"); assertEquals(expectedJsonReport, actualReportJson); }
Source:
public synchronized void startBackgroundScanning() { if (backgroundScanningJob == null) { backgroundScanningJob = scheduler.scheduleWithFixedDelay(() -> { singleScanInternal(false); }, 0, pauseBetweenScans.getSeconds(), TimeUnit.SECONDS); logger.debug("Scheduled usb-serial background discovery every seconds", pauseBetweenScans.getSeconds()); } }

Target:
public synchronized void startBackgroundScanning() { if (backgroundScanningJob == null) { backgroundScanningJob = scheduler.scheduleWithFixedDelay(() -> { singleScanInternal(false); }, 0, pauseBetweenScans.getSeconds(), TimeUnit.SECONDS); logger.debug("Scheduled USB-Serial background discovery every seconds", pauseBetweenScans.getSeconds()); } }
Source:
public void addTable(TableSpec tableSpec) { if (tables.containsKey(tableSpec.getId())) { throw new SamzaException("Table " + tableSpec.getId() + " already exists"); } TableCtx ctx = new TableCtx(); TableProviderFactory tableProviderFactory = Util.getObj(tableSpec.getTableProviderFactory()); ctx.tableProvider = tableProviderFactory.getTableProvider(tableSpec); ctx.tableSpec = tableSpec; tables.put(tableSpec.getId(), ctx); }

Target:
private void addTable(TableSpec tableSpec) { if (tables.containsKey(tableSpec.getId())) { throw new SamzaException("Table " + tableSpec.getId() + " already exists"); } TableCtx ctx = new TableCtx(); TableProviderFactory tableProviderFactory = Util.getObj(tableSpec.getTableProviderFactoryClassName()); ctx.tableProvider = tableProviderFactory.getTableProvider(tableSpec); ctx.tableSpec = tableSpec; tables.put(tableSpec.getId(), ctx); }
Source:
public static Schema appendFields(Schema schema, Schema.Field... fields) { Schema newSchema = schema; if (schema.getType() == Type.RECORD) { newSchema = Schema.createRecord(schema.getName(), schema.getDoc(), schema.getNamespace(), schema.isError()); List<Schema.Field> copyFieldList = new ArrayList<>(); for (Schema.Field se : schema.getFields()) { copyFieldList.add(new Schema.Field(se.name(), se.schema(), se.doc(), se.defaultVal())); } for (Schema.Field field : fields) { copyFieldList.add(field); } newSchema.setFields(copyFieldList); Map<String, Object> props = schema.getObjectProps(); for (String propKey : props.keySet()) { newSchema.addProp(propKey, props.get(propKey)); } } else { throw new RuntimeException("Not support this type " + newSchema.getType() + " now, need to implement"); } return newSchema; }

Target:
public static Schema appendFields(Schema schema, Schema.Field... fields) { Schema newSchema = schema; if (schema.getType() == Type.RECORD) { newSchema = Schema.createRecord(schema.getName(), schema.getDoc(), schema.getNamespace(), schema.isError()); List<Schema.Field> copyFieldList = new ArrayList<>(); for (Schema.Field se : schema.getFields()) { copyFieldList.add(new Schema.Field(se.name(), se.schema(), se.doc(), se.defaultVal())); } for (Schema.Field field : fields) { copyFieldList.add(field); } newSchema.setFields(copyFieldList); Map<String, Object> props = schema.getObjectProps(); for (String propKey : props.keySet()) { newSchema.addProp(propKey, props.get(propKey)); } } else { TalendRuntimeException.build(CommonErrorCodes.UNEXPECTED_EXCEPTION) .setAndThrow("Not support this type " + schema.getType() + ", only support record type"); } return newSchema; }
Source:
public void testConversionAggregated() throws Exception { final String inputFilePath = "/aggregated.vcf.gz"; String inputFile = AggregatedVcfReaderTest.class.getResource(inputFilePath).getFile(); File tempFile = JobTestUtils.createTempFile(); JobTestUtils.uncompress(inputFile, tempFile); String fileId = "5"; String studyId = "7"; String studyName = "study name"; VcfHeaderReader headerReader = new VcfHeaderReader(new File(inputFile), fileId, studyId, studyName, VariantStudy.StudyType.COLLECTION, VariantSource.Aggregation.NONE); VariantSource source = headerReader.read(); char CHARACTER_TO_REPLACE_DOTS = (char) 163; Map<String, Object> meta = source.getMetadata(); BasicDBObject metadataMongo = new BasicDBObject(); for (Map.Entry<String, Object> metaEntry : meta.entrySet()) { ObjectMapper mapper = new ObjectMapper(); ObjectWriter writer = mapper.writer(); String key = metaEntry.getKey().replace('.', CHARACTER_TO_REPLACE_DOTS); Object value = metaEntry.getValue(); String jsonString = writer.writeValueAsString(value); metadataMongo.append(key, JSON.parse(jsonString)); } checkFieldsInsideList(metadataMongo, "INFO", Arrays.asList("id", "description", "number", "type")); checkStringInsideList(metadataMongo, "contig"); }

Target:
public void testConversionAggregated() throws Exception { File input = TestFileUtils.getResource(INPUT_AGGREGATED_FILE_PATH); File tempFile = JobTestUtils.createTempFile(); JobTestUtils.uncompress(input.getAbsolutePath(), tempFile); VcfHeaderReader headerReader = new VcfHeaderReader(input, FILE_ID, STUDY_ID, STUDY_NAME, VariantStudy.StudyType.COLLECTION, VariantSource.Aggregation.NONE); VariantSource source = headerReader.read(); char CHARACTER_TO_REPLACE_DOTS = (char) 163; Map<String, Object> meta = source.getMetadata(); BasicDBObject metadataMongo = new BasicDBObject(); for (Map.Entry<String, Object> metaEntry : meta.entrySet()) { ObjectMapper mapper = new ObjectMapper(); ObjectWriter writer = mapper.writer(); String key = metaEntry.getKey().replace('.', CHARACTER_TO_REPLACE_DOTS); Object value = metaEntry.getValue(); String jsonString = writer.writeValueAsString(value); metadataMongo.append(key, JSON.parse(jsonString)); } checkFieldsInsideList(metadataMongo, "INFO", Arrays.asList("id", "description", "number", "type")); checkStringInsideList(metadataMongo, "contig"); }
Source:
private Set<String> getCatalogItemIds(Iterable<CatalogItem<Object, Object>> catalogItems) { return FluentIterable.from(catalogItems) .transform(new Function<CatalogItem<Object, Object>, String>() { @Override public String apply(CatalogItem<Object, Object> input) { return input.getId(); } }) .copyInto(Sets.<String>newHashSet()); }

Target:
private Set<String> getCatalogItemIds(Iterable<CatalogItem<Object, Object>> catalogItems) { return FluentIterable.from(catalogItems) .transform(EntityFunctions.id()) .copyInto(Sets.<String>newHashSet()); }
Source:
public void process(Session session, DashBoard dash, byte pin, PinType type, String triggerValue) { Eventor eventor = dash.getWidgetByType(Eventor.class); if (eventor == null || eventor.rules == null) { return; } double valueParsed; try { valueParsed = Double.parseDouble(triggerValue); } catch (NumberFormatException nfe) { return; } for (Rule rule : eventor.rules) { if (rule.isReady(pin, type)) { if (rule.isValid(valueParsed)) { if (!rule.isProcessed) { for (BaseAction action : rule.actions) { if (action instanceof SetPinAction) { execute(session, dash.isActive, dash.id, (SetPinAction) action); } else if (action instanceof NotificationAction) { execute(dash, triggerValue, (NotificationAction) action); } } rule.isProcessed = true; } } else { rule.isProcessed = false; } } } globalStats.mark(EVENTOR); }

Target:
public void process(Session session, DashBoard dash, byte pin, PinType type, String triggerValue) { Eventor eventor = dash.getWidgetByType(Eventor.class); if (eventor == null || eventor.rules == null) { return; } double valueParsed; try { valueParsed = Double.parseDouble(triggerValue); } catch (NumberFormatException nfe) { return; } for (Rule rule : eventor.rules) { if (rule.isReady(pin, type)) { if (rule.isValid(valueParsed)) { if (!rule.isProcessed) { for (BaseAction action : rule.actions) { if (action instanceof SetPinAction) { execute(session, dash.isActive, dash.id, (SetPinAction) action); } else if (action instanceof NotificationAction) { execute(dash, triggerValue, (NotificationAction) action); } } rule.isProcessed = true; } } else { rule.isProcessed = false; } } } }
Source:
public Activity(String label, ActivityType activityType, String ref) { this.label = label; this.activityType = activityType; this.ref = ref; this.survey = null; }

Target:
public Activity(String label, ActivityType activityType, String ref) { this(label, activityType, ref, null); }
Source:
protected GoogleApiClient createGoogleApiClient() { return GoogleApiClientFactory.createWithoutSignIn(getApplicationContext()); }

Target:
protected GoogleApiClient createGoogleApiClient() { return GoogleApiClientFactory.createWithoutSignIn(this); }
Source:
public void onAllRequiredCapabilitiesAvailable() { DataHolder.getInstance().getBundleContext().registerService(WebSocketServerSC.class, this, null); log.info("All required capabilities are available"); }

Target:
public void onAllRequiredCapabilitiesAvailable() { DataHolder.getInstance().getBundleContext().registerService(WebSocketServerSC.class, this, null); log.info("All required capabilities are available of WebSocket service component is available."); }
Source:
public void testCompactHasCorrectTimeStamp() { Chain chain = getChainFromOperations( new PutOperation<>(1L, "Albin1", 0), new PutOperation<>(1L, "Albin2", 1), new RemoveOperation<>(1L, 2), new PutOperation<>(1L, "Albin3", 3)); ChainResolver<Long, String> resolver = createChainResolver(ExpiryPolicyBuilder.noExpiration()); Chain compactedChain = resolver.compactChain(chain, 3); assertThat(compactedChain, contains(operation(new PutOperation<>(1L, "Albin3", 3)))); }

Target:
public void testCompactHasCorrectTimeStamp() { Chain chain = getChainFromOperations( new PutOperation<>(1L, "Albin", 0), new PutOperation<>(1L, "Albin", 1), new RemoveOperation<>(1L, 2), new PutOperation<>(1L, "Albin", 3)); ChainResolver<Long, String> resolver = createChainResolver(ExpiryPolicyBuilder.noExpiration()); Chain compactedChain = resolver.compactChain(chain, 3); assertThat(compactedChain, contains(operation(new PutOperation<>(1L, "Albin", 3)))); }
Source:
public Object get(int index) { if (index < 0) { throw new IndexOutOfBoundsException("Index: " + index + " should not be negative"); } int i = 0; for (Iterator it = iterator(); ; i++) { final Object next = it.next(); if (i == index) { return next; } else if (!it.hasNext()) { throw new IndexOutOfBoundsException("Index: " + index + " is too big for range: " + this); } } }

Target:
public Comparable get(int index) { if (index < 0) { throw new IndexOutOfBoundsException("Index: " + index + " should not be negative"); } int i = 0; for (Iterator<Comparable> iter = new LazySteppingIterator(this, 1); ; i++) { final Comparable next = iter.next(); if (i == index) { return next; } else if (!iter.hasNext()) { throw new IndexOutOfBoundsException("Index: " + index + " is too big for range: " + this); } } }
Source:
public void testToString() { DateFormat df = new SimpleDateFormat("HH:mm:ss.SSS"); df.setTimeZone(TimeZone.getTimeZone("UTC")); int timeOffset = TimeZone.getDefault().getOffset(0); Date d0 = new Date(0 + timeOffset); Date d1 = new Date(12345000L + timeOffset); Date d2 = new Date(85166000L + timeOffset); assertEquals("toString", df.format(d0) + " 000 000", ts0.toString()); assertEquals("toString", df.format(d1) + " 000 000", ts1.toString()); assertEquals("toString", df.format(d2) + " 000 000", ts2.toString()); }

Target:
public void testToString() { DateFormat df = new SimpleDateFormat("HH:mm:ss.SSS"); Date d0 = new Date(0); Date d1 = new Date(12345000L); Date d2 = new Date(85166000L); assertEquals("toString", df.format(d0) + " 000 000", ts0.toString()); assertEquals("toString", df.format(d1) + " 000 000", ts1.toString()); assertEquals("toString", df.format(d2) + " 000 000", ts2.toString()); }
Source:
protected void initializeCommand(UpdateVmDiskParameters params, List<VM> vms) { mockCtorRelatedDaoCalls(vms); command = spy(new UpdateVmDiskCommand<UpdateVmDiskParameters>(params) { @SuppressWarnings("synthetic-access") @Override protected DiskDao getDiskDao() { return diskDao; } @Override public VmDAO getVmDAO() { return vmDAO; } }); doReturn(true).when(command).acquireLockInternal(); doReturn(snapshotDao).when(command).getSnapshotDao(); doReturn(diskImageDao).when(command).getDiskImageDao(); doReturn(storagePoolDao).when(command).getStoragePoolDAO(); doReturn(storageDomainDao).when(command).getStorageDomainDAO(); doReturn(vmStaticDAO).when(command).getVmStaticDAO(); doReturn(baseDiskDao).when(command).getBaseDiskDao(); doReturn(imageDao).when(command).getImageDao(); doReturn(vmDeviceDAO).when(command).getVmDeviceDao(); doReturn(vmDAO).when(command).getVmDAO(); doReturn(diskDao).when(command).getDiskDao(); doNothing().when(command).reloadDisks(); doNothing().when(command).updateBootOrder(); doNothing().when(vmStaticDAO).incrementDbGeneration(any(Guid.class)); ejbRule.mockResource(ContainerManagedResourceType.TRANSACTION_MANAGER, new DummyTransactionManager()); SnapshotsValidator snapshotsValidator = mock(SnapshotsValidator.class); doReturn(snapshotsValidator).when(command).getSnapshotsValidator(); doReturn(ValidationResult.VALID).when(snapshotsValidator).vmNotDuringSnapshot(any(Guid.class)); doReturn(ValidationResult.VALID).when(snapshotsValidator).vmNotInPreview(any(Guid.class)); mockVds(); mockVmsStoragePoolInfo(vms); mockToUpdateDiskVm(vms); }

Target:
protected void initializeCommand(UpdateVmDiskParameters params, List<VM> vms) { mockCtorRelatedDaoCalls(vms); command = spy(new UpdateVmDiskCommand<UpdateVmDiskParameters>(params) { @SuppressWarnings("synthetic-access") @Override protected DiskDao getDiskDao() { return diskDao; } @Override public VmDAO getVmDAO() { return vmDAO; } }); doReturn(true).when(command).acquireLockInternal(); doReturn(snapshotDao).when(command).getSnapshotDao(); doReturn(diskImageDao).when(command).getDiskImageDao(); doReturn(storagePoolDao).when(command).getStoragePoolDAO(); doReturn(storageDomainStaticDao).when(command).getStorageDomainStaticDAO(); doReturn(vmStaticDAO).when(command).getVmStaticDAO(); doReturn(baseDiskDao).when(command).getBaseDiskDao(); doReturn(imageDao).when(command).getImageDao(); doReturn(vmDeviceDAO).when(command).getVmDeviceDao(); doReturn(vmDAO).when(command).getVmDAO(); doReturn(diskDao).when(command).getDiskDao(); doNothing().when(command).reloadDisks(); doNothing().when(command).updateBootOrder(); doNothing().when(vmStaticDAO).incrementDbGeneration(any(Guid.class)); ejbRule.mockResource(ContainerManagedResourceType.TRANSACTION_MANAGER, new DummyTransactionManager()); SnapshotsValidator snapshotsValidator = mock(SnapshotsValidator.class); doReturn(snapshotsValidator).when(command).getSnapshotsValidator(); doReturn(ValidationResult.VALID).when(snapshotsValidator).vmNotDuringSnapshot(any(Guid.class)); doReturn(ValidationResult.VALID).when(snapshotsValidator).vmNotInPreview(any(Guid.class)); mockVds(); mockVmsStoragePoolInfo(vms); mockToUpdateDiskVm(vms); }
Source:
public void stop() { if (this.abortStarted == 0) { this.abortStarted = System.currentTimeMillis(); } if (this.consumer != null && this.consumer.getChannel() != null && this.consumerTags.size() > 0 && !this.cancelled.get()) { try { RabbitUtils.closeMessageConsumer(this.consumer.getChannel(), this.consumerTags.keySet(), this.transactional); } catch (Exception e) { if (logger.isDebugEnabled()) { logger.debug("Error closing consumer " + this, e); } } } if (logger.isDebugEnabled()) { logger.debug("Closing Rabbit Channel: " + this.channel); } RabbitUtils.setPhysicalCloseRequired(true); ConnectionFactoryUtils.releaseResources(this.resourceHolder); if (!(this.channel instanceof ChannelProxy)) { RabbitUtils.isPhysicalCloseRequired(); } this.deliveryTags.clear(); this.consumer = null; this.queue.clear(); }

Target:
public void stop() { if (this.abortStarted == 0) { this.abortStarted = System.currentTimeMillis(); } if (this.consumer != null && this.consumer.getChannel() != null && this.consumerTags.size() > 0 && !this.cancelled.get()) { try { RabbitUtils.closeMessageConsumer(this.consumer.getChannel(), this.consumerTags.keySet(), this.transactional); } catch (Exception e) { if (logger.isDebugEnabled()) { logger.debug("Error closing consumer " + this, e); } } } if (logger.isDebugEnabled()) { logger.debug("Closing Rabbit Channel: " + this.channel); } RabbitUtils.setPhysicalCloseRequired(this.channel, true); ConnectionFactoryUtils.releaseResources(this.resourceHolder); this.deliveryTags.clear(); this.consumer = null; this.queue.clear(); }
Source:
public List<Index> call(SQLDatabase db) throws Exception { String sqlIndexNames = String.format("SELECT DISTINCT index_name FROM %s", QueryImpl .INDEX_METADATA_TABLE_NAME); Cursor cursorIndexNames = null; ArrayList<Index> indexes = new ArrayList<Index>(); try { cursorIndexNames = db.rawQuery(sqlIndexNames, new String[]{}); while (cursorIndexNames.moveToNext()) { String indexName = cursorIndexNames.getString(0); String sqlIndexes = String.format("SELECT index_type, field_name, index_settings " + "FROM %s " + "WHERE index_name = ?", QueryImpl.INDEX_METADATA_TABLE_NAME); Cursor cursorIndexes = null; try { cursorIndexes = db.rawQuery(sqlIndexes, new String[]{indexName}); IndexType indexType = null; String settings = null; ArrayList<FieldSort> fieldNames = new ArrayList<FieldSort>(); boolean first = true; while (cursorIndexes.moveToNext()) { if (first) { indexType = IndexType.valueOf(cursorIndexes.getString(0).toUpperCase (Locale.ENGLISH)); settings = cursorIndexes.getString(2); first = false; } fieldNames.add(new FieldSort(cursorIndexes.getString(1))); } Tokenizer tokenizer = TokenizerHelper.jsonToTokenizer(settings); if (tokenizer != null) { indexes.add(new Index(fieldNames, indexName, indexType, tokenizer)); } else { indexes.add(new Index(fieldNames, indexName, indexType)); } } finally { DatabaseUtils.closeCursorQuietly(cursorIndexes); } } } finally { DatabaseUtils.closeCursorQuietly(cursorIndexNames); } return indexes; }

Target:
public List<Index> call(SQLDatabase db) throws Exception { String sqlIndexNames = String.format("SELECT DISTINCT index_name FROM %s", QueryImpl .INDEX_METADATA_TABLE_NAME); Cursor cursorIndexNames = null; ArrayList<Index> indexes = new ArrayList<Index>(); try { cursorIndexNames = db.rawQuery(sqlIndexNames, new String[]{}); while (cursorIndexNames.moveToNext()) { String indexName = cursorIndexNames.getString(0); String sqlIndexes = String.format("SELECT index_type, field_name, index_settings " + "FROM %s WHERE index_name = ?", QueryImpl.INDEX_METADATA_TABLE_NAME); Cursor cursorIndexes = null; try { cursorIndexes = db.rawQuery(sqlIndexes, new String[]{indexName}); IndexType indexType = null; String settings = null; ArrayList<FieldSort> fieldNames = new ArrayList<FieldSort>(); boolean first = true; while (cursorIndexes.moveToNext()) { if (first) { indexType = IndexType.valueOf(cursorIndexes.getString(0).toUpperCase (Locale.ENGLISH)); settings = cursorIndexes.getString(2); first = false; } fieldNames.add(new FieldSort(cursorIndexes.getString(1))); } Tokenizer tokenizer = TokenizerHelper.jsonToTokenizer(settings); if (tokenizer != null) { indexes.add(new Index(fieldNames, indexName, indexType, tokenizer)); } else { indexes.add(new Index(fieldNames, indexName, indexType)); } } finally { DatabaseUtils.closeCursorQuietly(cursorIndexes); } } } finally { DatabaseUtils.closeCursorQuietly(cursorIndexNames); } return indexes; }
Source:
public boolean postData(JSONArray data, String sessionID) throws IOException, JSONException { if(sessionID == null || sessionID.isEmpty() || data == null || data.length() == 0) throw new IOException("invalid input of data or sessionID"); JSONObject postData = new JSONObject(); postData.put("sensors",data); String url = makeUrlFor(URLE_UPLOAD_MULTIPLE_SENSORS,null); Map<String, String> response = request(url, postData, sessionID,"POST"); int code = checkResponseCode(response.get(RESPONSE_CODE), "postData"); if(code != -2) throw new IOException("Incorrect response of postData from CommonSense: " + response.get(RESPONSE_CODE)); return (code == -2); }

Target:
public boolean postData(JSONArray data, String sessionID) throws RuntimeException, IOException { if(sessionID == null || sessionID.isEmpty() || data == null || data.length() == 0) throw new IllegalArgumentException("invalid input of data or sessionID"); JSONObject postData = new JSONObject(); try { postData.put("sensors", data); }catch(JSONException js){ throw new RuntimeException("postData failed to create the content for the request"); } String url = makeUrlFor(URLE_UPLOAD_MULTIPLE_SENSORS,null); Map<String, String> response = request(url, postData, sessionID,"POST"); int code = checkResponseCode(response.get(RESPONSE_CODE), "postData"); return (code == 1); }
Source:
private void updateBrokers() { if (StringUtils.isEmpty(kafkaSettings.getBootstrapServers()) && kafkaProperties != null) { final List<Broker> brokers = fetchBrokers(); if (!brokers.isEmpty()) { kafkaProperties.setProperty(CommonClientConfigs.BOOTSTRAP_SERVERS_CONFIG, buildBootstrapServers(brokers)); } } }

Target:
private void updateBrokers() { final List<Broker> brokers = fetchBrokers(); if (!brokers.isEmpty()) { kafkaProperties.setProperty(CommonClientConfigs.BOOTSTRAP_SERVERS_CONFIG, buildBootstrapServers(brokers)); } }
Source:
public void testKJarNotAvailable() { boolean caughtException = false; ScoreKJarReleaseIdConfig config = new ScoreKJarReleaseIdConfig(); config.setGroupId(groupId); config.setArtifactId(artifactId); config.setVersion("1.0.1"); try { DroolsScoreDirectorFactory scoreDirectorFactory = config.build(); } catch (RuntimeException re) { caughtException = true; } assertEquals("Expected exception when trying to load a KJAR which doesn't exist.", true, caughtException); }

Target:
public void testKJarNotAvailable() { ScoreKJarReleaseIdConfig config = new ScoreKJarReleaseIdConfig(); config.setGroupId(groupId); config.setArtifactId(artifactId); config.setVersion("1.0.1"); DroolsScoreDirectorFactory scoreDirectorFactory = config.build(); }
Source:
private static <T> String getMismatchDescriptionString(T actual, Matcher<T> matcher) { Description mismatchDescription = new StringDescription(); matcher.describeMismatch(actual, mismatchDescription); String mismatchDescriptionString = mismatchDescription.toString(); mismatchDescriptionString = mismatchDescriptionString == null ? "" : mismatchDescriptionString.trim(); return mismatchDescriptionString.isEmpty() ? actual.toString() : mismatchDescriptionString; }

Target:
private static <T> String getMismatchDescriptionString(T actual, Matcher<T> matcher) { Description mismatchDescription = new StringDescription(); matcher.describeMismatch(actual, mismatchDescription); String mismatchDescriptionString = mismatchDescription.toString().trim(); return mismatchDescriptionString.isEmpty() ? actual.toString() : mismatchDescriptionString; }
Source:
public void run() throws OperationException { Map<String, Object> vars = isolate ? new HashMap<String, Object>(ctx.getVars()) : ctx.getVars(); Collection<?> list = null; if (ctx.get(listName) instanceof Object[]) { list = Arrays.asList((Object[]) ctx.get(listName)); } else if (ctx.get(listName) instanceof Collection<?>) { list = (Collection<?>) ctx.get(listName); } else { throw new UnsupportedOperationException(ctx.get(listName).getClass() + " is not a Collection"); } TransactionHelper.commitOrRollbackTransaction(); for (Object value : list) { TransactionHelper.startTransaction(); boolean completedAbruptly = true; try { OperationContext subctx = ctx.getSubContext(isolate, ctx.getInput()); subctx.push(itemName, value); try { service.run(subctx, chainId); } finally { subctx.pop(itemName); } completedAbruptly = false; } finally { if (completedAbruptly) { TransactionHelper.setTransactionRollbackOnly(); } TransactionHelper.commitOrRollbackTransaction(); } } TransactionHelper.startTransaction(); if (!isolate) { for (String varName : vars.keySet()) { if (!ctx.getVars().containsKey(varName)) { ctx.put(varName, vars.get(varName)); } else { Object value = vars.get(varName); if (session != null && value != null && value instanceof DocumentModel) { ctx.getVars().put(varName, session.getDocument(((DocumentModel) value).getRef())); } else { ctx.getVars().put(varName, value); } } } } }

Target:
public void run() throws OperationException { Map<String, Object> vars = isolate ? new HashMap<String, Object>(ctx.getVars()) : ctx.getVars(); Collection<?> list = null; if (ctx.get(listName) instanceof Object[]) { list = Arrays.asList((Object[]) ctx.get(listName)); } else if (ctx.get(listName) instanceof Collection<?>) { list = (Collection<?>) ctx.get(listName); } else { throw new UnsupportedOperationException(ctx.get(listName).getClass() + " is not a Collection"); } TransactionHelper.commitOrRollbackTransaction(); for (Object value : list) { try { TransactionHelper.runInNewTransaction(() -> { try (OperationContext subctx = ctx.getSubContext(isolate, ctx.getInput())) { subctx.push(itemName, value); try { service.run(subctx, chainId); } finally { subctx.pop(itemName); } } catch (OperationException e) { throw new NuxeoException(e); } }); } catch (NuxeoException e) { if (e.getCause() instanceof OperationException) { throw (OperationException) e.getCause(); } throw e; } } TransactionHelper.startTransaction(); if (!isolate) { for (String varName : vars.keySet()) { if (!ctx.getVars().containsKey(varName)) { ctx.put(varName, vars.get(varName)); } else { Object value = vars.get(varName); if (session != null && value != null && value instanceof DocumentModel) { ctx.getVars().put(varName, session.getDocument(((DocumentModel) value).getRef())); } else { ctx.getVars().put(varName, value); } } } } }
Source:
private boolean updateJMXPort(DebuggingContext debugContext, Set<IPort> ports) { IPort existing = ports.stream().filter(p->p.getName().equals("remotingjmx")).findFirst().orElse(null); PortSpecAdapter newPort = new PortSpecAdapter("remotingjmx", "TCP", 9999); if (existing == null) { ports.add(newPort); return true; } else { if (existing.equals(newPort)) { return false; } ports.remove(existing); ports.add(newPort); return true; } }

Target:
private boolean updateJMXPort(DebuggingContext debugContext, Set<IPort> ports) { IPort existing = ports.stream().filter(p->p.getName().equals("remotingjmx")).findFirst().orElse(null); PortSpecAdapter newPort = new PortSpecAdapter("remotingjmx", "TCP", NATIVE_MANAGMENT_PORT); if (existing == null) { ports.add(newPort); return true; } else { if (existing.equals(newPort)) { return false; } ports.remove(existing); ports.add(newPort); return true; } }