auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void testEventStyling() { SWTWorkbenchBot bot = new SWTWorkbenchBot(); resetTimeRange(bot); Rectangle bounds = fBounds; ImageHelper precollapse = ImageHelper.grabImage(bounds); SWTBotTimeGraph tg = new SWTBotTimeGraph(fViewBot.bot()); tg.getEntry("Plumber guy").collapse(); TimeGraphViewStub view = getView(); ImageHelper ref = ImageHelper.waitForNewImage(bounds, precollapse); view.setFilterRegex("row?"); UIThreadRunnable.syncExec(() -> view.restartZoomThread()); ImageHelper highlighted = ImageHelper.waitForNewImage(bounds, ref); view.setFilterRegex(null); UIThreadRunnable.syncExec(() -> view.restartZoomThread()); ImageHelper reset = ImageHelper.waitForNewImage(bounds, highlighted); ImageHelper diff = ref.diff(reset); assertTrue((double)diff.getHistogram().count(new RGB(0,0,0))/diff.getHistogram().size() > 0.99); ImageHelper delta = highlighted.diff(reset); tg.expandAll(); assertTrue("Some highlighting", delta.getHistogram().elementSet().size() > 1); }

Target:
public void testEventStyling() { SWTWorkbenchBot bot = new SWTWorkbenchBot(); resetTimeRange(bot); Rectangle bounds = fBounds; ImageHelper precollapse = ImageHelper.grabImage(bounds); SWTBotTimeGraph tg = new SWTBotTimeGraph(fViewBot.bot()); tg.getEntry("Plumber guy").collapse(); TimeGraphViewStub view = getView(); ImageHelper ref = ImageHelper.waitForNewImage(bounds, precollapse); view.setFilterRegex("row?"); UIThreadRunnable.syncExec(() -> view.restartZoomThread()); ImageHelper highlighted = ImageHelper.waitForNewImage(bounds, ref); view.setFilterRegex(null); UIThreadRunnable.syncExec(() -> view.restartZoomThread()); ImageHelper reset = ImageHelper.waitForNewImage(bounds, highlighted); assertEquals(ref.getHistogram(), reset.getHistogram()); ImageHelper delta = highlighted.diff(reset); tg.expandAll(); assertTrue("Some highlighting", delta.getHistogram().elementSet().size() > 1); }
Source:
public Boolean geteofCompliesPDFA() { return true; }

Target:
public Boolean geteofCompliesPDFA() { return ((COSDocument) baseObject).getEofComplyPDFA(); }
Source:
private void when_badCharacters_then_escaped(String badText) throws Exception { System.out.println("badText: " + badText); jmxPublisher.publishLong(newDescriptor() .withPrefix(badText) .withMetric("metric"), 1L); jmxPublisher.publishLong(newDescriptor() .withMetric(badText) .withTag("tag1", "a"), 2L); jmxPublisher.whenComplete(); helper.assertMBeans(asList( of(domainPrefix + ":type=Metrics,instance=inst1,prefix=" + JmxPublisher.escapeObjectNameValue(badText), singletonList(entry("metric", 1L))), of(domainPrefix + ":type=Metrics,instance=inst1,tag0=\"tag1=a\"", singletonList(entry(badText, 2L))) )); }

Target:
private void when_badCharacters_then_escaped(String badText) throws Exception { jmxPublisher.publishLong(newDescriptor() .withPrefix(badText) .withMetric("metric"), 1L); jmxPublisher.publishLong(newDescriptor() .withMetric(badText) .withTag("tag1", "a"), 2L); jmxPublisher.whenComplete(); helper.assertMBeans(asList( of(domainPrefix + ":type=Metrics,instance=inst1,prefix=" + JmxPublisher.escapeObjectNameValue(badText), singletonList(entry("metric", 1L))), of(domainPrefix + ":type=Metrics,instance=inst1,tag0=\"tag1=a\"", singletonList(entry(badText, 2L))) )); }
Source:
public APIQuerySubmissionResult submit(final MISTQuery queryToSubmit) throws IOException { final NettyTransceiver clientToDriver = new NettyTransceiver(new InetSocketAddress(serverAddr, serverPort)); final MistTaskProvider proxyToDriver = SpecificRequestor.getClient(MistTaskProvider.class, clientToDriver); final TaskList taskList = proxyToDriver.getTasks(new QueryInfo()); final java.util.List<IPAddress> tasks = taskList.getTasks(); final LogicalPlan logicalPlan = querySerializer.queryToLogicalPlan(queryToSubmit); final IPAddress task = tasks.get(0); final NettyTransceiver clientToTask = new NettyTransceiver( new InetSocketAddress(task.getHostAddress().toString(), task.getPort())); final ClientToTaskMessage proxyToTask = SpecificRequestor.getClient(ClientToTaskMessage.class, clientToTask); final QuerySubmissionResult querySubmissionResult = proxyToTask.sendQueries(logicalPlan); APIQuerySubmissionResult apiQuerySubmissionResult = new APIQuerySubmissionResultImpl(querySubmissionResult.getQueryId()); return apiQuerySubmissionResult; }

Target:
public APIQuerySubmissionResult submit(final MISTQuery queryToSubmit) throws IOException { final NettyTransceiver clientToDriver = new NettyTransceiver(new InetSocketAddress(serverAddr, serverPort)); final MistTaskProvider proxyToDriver = SpecificRequestor.getClient(MistTaskProvider.class, clientToDriver); final TaskList taskList = proxyToDriver.getTasks(new QueryInfo()); final List<IPAddress> tasks = taskList.getTasks(); final LogicalPlan logicalPlan = querySerializer.queryToLogicalPlan(queryToSubmit); final IPAddress task = tasks.get(0); final NettyTransceiver clientToTask = new NettyTransceiver( new InetSocketAddress(task.getHostAddress().toString(), task.getPort())); final ClientToTaskMessage proxyToTask = SpecificRequestor.getClient(ClientToTaskMessage.class, clientToTask); final QuerySubmissionResult querySubmissionResult = proxyToTask.sendQueries(logicalPlan); APIQuerySubmissionResult apiQuerySubmissionResult = new APIQuerySubmissionResultImpl(querySubmissionResult.getQueryId()); return apiQuerySubmissionResult; }
Source:
public E read(String line) { try { return builder.makeRecord(parser.parseLine(line), null); } catch (IOException e) { throw new DatasetIOException("Cannot parse line: " + line, e); } }

Target:
public E read(String line) { return read(line, null); }
Source:
public void testDetermineOutputType() { Assert.assertEquals(OutputType.VCF, VariantContextWriterBuilder.determineOutputTypeFromFile(this.vcf)); Assert.assertEquals(OutputType.BCF, VariantContextWriterBuilder.determineOutputTypeFromFile(this.bcf)); Assert.assertEquals(OutputType.VCF_STREAM, VariantContextWriterBuilder.determineOutputTypeFromFile(new File("/dev/stdout"))); try { final Path link = Files.createTempFile("foo.", ".tmp"); Files.deleteIfExists(link); Files.createSymbolicLink(link, this.vcf.toPath()); link.toFile().deleteOnExit(); Assert.assertEquals(OutputType.VCF, VariantContextWriterBuilder.determineOutputTypeFromFile(link.toFile())); link.toFile().delete(); } catch (final IOException ioe) { throw new RuntimeIOException(ioe); } }

Target:
public void testDetermineOutputType() { Assert.assertEquals(OutputType.VCF, VariantContextWriterBuilder.determineOutputTypeFromFile(this.vcf)); Assert.assertEquals(OutputType.BCF, VariantContextWriterBuilder.determineOutputTypeFromFile(this.bcf)); Assert.assertEquals(OutputType.VCF_STREAM, VariantContextWriterBuilder.determineOutputTypeFromFile(new File("/dev/stdout"))); for (final File f: this.blockCompressedVCFs) { Assert.assertEquals(OutputType.BLOCK_COMPRESSED_VCF, VariantContextWriterBuilder.determineOutputTypeFromFile(f)); } try { final Path link = Files.createTempFile("foo.", ".tmp"); Files.deleteIfExists(link); Files.createSymbolicLink(link, this.vcf.toPath()); link.toFile().deleteOnExit(); Assert.assertEquals(OutputType.VCF, VariantContextWriterBuilder.determineOutputTypeFromFile(link.toFile())); link.toFile().delete(); } catch (final IOException ioe) { throw new RuntimeIOException(ioe); } }
Source:
private void increment(String tag, Map<String, AtomicLong> toIncrement) { final AtomicLong counter = getOrCreateCounter(tag, toIncrement); counter.set(counter.incrementAndGet()); toIncrement.put(tag, counter); }

Target:
private void increment(String tag, Map<String, AtomicLong> toIncrement) { final AtomicLong counter = getOrCreateCounter(tag, toIncrement); counter.incrementAndGet(); }
Source:
public void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey) throws ScriptException { correctlySpends(txContainingThis, scriptSigIndex, scriptPubKey, new HashSet<VerifyFlag>(Arrays.asList(VerifyFlag.values()))); }

Target:
public void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey) throws ScriptException { correctlySpends(txContainingThis, scriptSigIndex, scriptPubKey, ALL_VERIFY_FLAGS); }
Source:
public final void setup() { customHandler = new CustomHandler(); wasCustomHandlerInvoked = false; throwable = new TestRejectedTaskException(); activeThreadCount = 2; corePoolSize = 4; largestPoolSize = 8; maximumPoolSize = 16; executorQueue = new SynchronousQueue<>(); final Lease lease = new LeaseBuilder().build(); leaseAssignments = Collections.singletonList(lease); when(executor.getQueue()).thenReturn(executorQueue); when(executor.getActiveCount()).thenReturn(activeThreadCount); when(executor.getCorePoolSize()).thenReturn(corePoolSize); when(executor.getLargestPoolSize()).thenReturn(largestPoolSize); when(executor.getMaximumPoolSize()).thenReturn(maximumPoolSize); when(leaseCoordinator.getAssignments()).thenReturn(leaseAssignments); }

Target:
public void setup() { wasCustomHandlerInvoked = false; executorQueue = new SynchronousQueue<>(); final Lease lease = new LeaseBuilder().build(); leaseAssignments = Collections.singletonList(lease); when(executor.getQueue()).thenReturn(executorQueue); when(executor.getActiveCount()).thenReturn(activeThreadCount); when(executor.getCorePoolSize()).thenReturn(corePoolSize); when(executor.getLargestPoolSize()).thenReturn(largestPoolSize); when(executor.getMaximumPoolSize()).thenReturn(maximumPoolSize); when(leaseCoordinator.getAssignments()).thenReturn(leaseAssignments); }
Source:
public IPropertyDescriptor[] getPropertyDescriptors() { List<IPropertyDescriptor> descriptors= new ArrayList<IPropertyDescriptor>(); descriptors.add(new ReadOnlyTextPropertyDescriptor(ID_TIMESTAMP, NAME_TIMESTAMP)); descriptors.add(new ReadOnlyTextPropertyDescriptor(ID_SOURCE, NAME_SOURCE)); descriptors.add(new ReadOnlyTextPropertyDescriptor(ID_TYPE, NAME_TYPE)); descriptors.add(new ReadOnlyTextPropertyDescriptor(ID_REFERENCE, NAME_REFERENCE)); descriptors.add(new ReadOnlyTextPropertyDescriptor(ID_CONTENT, NAME_CONTENT)); if ((fEvent instanceof ITmfSourceLookup) && (((ITmfSourceLookup)fEvent).getCallsite() != null)) { descriptors.add(new ReadOnlyTextPropertyDescriptor(ID_SOURCE_LOOKUP, NAME_SOURCE_LOOKUP)); } if (fEvent instanceof ITmfCustomAttributes) { ITmfCustomAttributes event = (ITmfCustomAttributes) fEvent; if (event.listCustomAttributes() != null && !event.listCustomAttributes().isEmpty()) { descriptors.add(new ReadOnlyTextPropertyDescriptor(ID_CUSTOM_ATTRIBUTE, NAME_CUSTOM_ATTRIBUTES)); } } return descriptors.toArray(new IPropertyDescriptor[0]); }

Target:
public IPropertyDescriptor[] getPropertyDescriptors() { List<IPropertyDescriptor> descriptors= new ArrayList<IPropertyDescriptor>(); descriptors.add(new ReadOnlyTextPropertyDescriptor(ID_TIMESTAMP, NAME_TIMESTAMP)); descriptors.add(new ReadOnlyTextPropertyDescriptor(ID_SOURCE, NAME_SOURCE)); descriptors.add(new ReadOnlyTextPropertyDescriptor(ID_TYPE, NAME_TYPE)); descriptors.add(new ReadOnlyTextPropertyDescriptor(ID_REFERENCE, NAME_REFERENCE)); descriptors.add(new ReadOnlyTextPropertyDescriptor(ID_CONTENT, NAME_CONTENT)); if ((fEvent instanceof ITmfSourceLookup) && (((ITmfSourceLookup)fEvent).getCallsite() != null)) { descriptors.add(new ReadOnlyTextPropertyDescriptor(ID_SOURCE_LOOKUP, NAME_SOURCE_LOOKUP)); } if ((fEvent instanceof ITmfModelLookup) && (((ITmfModelLookup) fEvent).getModelUri() != null)) { descriptors.add(new ReadOnlyTextPropertyDescriptor(ID_MODEL_URI, NAME_MODEL_URI)); } if (fEvent instanceof ITmfCustomAttributes) { ITmfCustomAttributes event = (ITmfCustomAttributes) fEvent; if (event.listCustomAttributes() != null && !event.listCustomAttributes().isEmpty()) { descriptors.add(new ReadOnlyTextPropertyDescriptor(ID_CUSTOM_ATTRIBUTE, NAME_CUSTOM_ATTRIBUTES)); } } return descriptors.toArray(new IPropertyDescriptor[0]); }
Source:
public ExtendedEmailPublisherContext(ExtendedEmailPublisher publisher, AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) { this.publisher = publisher; this.run = build; this.workspace = build.getWorkspace(); this.launcher = launcher; this.listener = listener; }

Target:
public ExtendedEmailPublisherContext(ExtendedEmailPublisher publisher, AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) { this(publisher, build, build.getWorkspace(), launcher, listener); }
Source:
public DirCache call() throws IOException { DirCache dc = DirCache.lock(repo); try { ObjectWriter ow = new ObjectWriter(repo); ObjectId id; DirCacheIterator c; DirCacheBuilder builder = dc.builder(); final TreeWalk tw = new TreeWalk(repo); tw.reset(); tw.addTree(new DirCacheBuildIterator(builder)); FileTreeIterator fileTreeIterator = new FileTreeIterator( repo.getWorkDir(), repo.getFS()); tw.addTree(fileTreeIterator); tw.setRecursive(true); tw.setFilter(PathFilterGroup.createFromStrings(filepatterns)); String lastAddedFile = null; while (tw.next()) { String path = tw.getPathString(); final File file = new File(repo.getWorkDir(), path); if (!(path.equals(lastAddedFile))) { if (file.exists()) { id = ow.writeBlob(file); DirCacheEntry entry = new DirCacheEntry(path); entry.setObjectId(id); entry.setFileMode(repo.getFS().canExecute(file) ? FileMode.EXECUTABLE_FILE : FileMode.REGULAR_FILE); entry.setLastModified(file.lastModified()); entry.setLength((int) file.length()); builder.add(entry); lastAddedFile = path; } else { c = tw.getTree(0, DirCacheIterator.class); builder.add(c.getDirCacheEntry()); } } } builder.commit(); } finally { dc.unlock(); } return dc; }

Target:
public DirCache call() throws NoFilepatternException { if (filepatterns.isEmpty()) throw new NoFilepatternException(JGitText.get().atLeastOnePatternIsRequired); checkCallable(); DirCache dc = null; try { dc = DirCache.lock(repo); ObjectWriter ow = new ObjectWriter(repo); DirCacheIterator c; DirCacheBuilder builder = dc.builder(); final TreeWalk tw = new TreeWalk(repo); tw.reset(); tw.addTree(new DirCacheBuildIterator(builder)); FileTreeIterator fileTreeIterator = new FileTreeIterator( repo.getWorkDir(), repo.getFS()); tw.addTree(fileTreeIterator); tw.setRecursive(true); tw.setFilter(PathFilterGroup.createFromStrings(filepatterns)); String lastAddedFile = null; while (tw.next()) { String path = tw.getPathString(); final File file = new File(repo.getWorkDir(), path); if (!(path.equals(lastAddedFile))) { FileTreeIterator f = tw.getTree(1, FileTreeIterator.class); if (f != null) { DirCacheEntry entry = new DirCacheEntry(path); entry.setLength((int)f.getEntryLength()); entry.setLastModified(f.getEntryLastModified()); entry.setFileMode(f.getEntryFileMode()); entry.setObjectId(ow.writeBlob(file)); builder.add(entry); lastAddedFile = path; } else { c = tw.getTree(0, DirCacheIterator.class); builder.add(c.getDirCacheEntry()); } } } builder.commit(); setCallable(false); } catch (IOException e) { throw new JGitInternalException( JGitText.get().exceptionCaughtDuringExecutionOfAddCommand, e); } finally { if (dc != null) dc.unlock(); } return dc; }
Source:
public void combine_WithPlugins_annotations() throws Exception { List<WithPlugins> annotations = Arrays.asList( FakeTestClass.class.getAnnotation(WithPlugins.class), FakeTestClass.class.getMethod("test").getAnnotation(WithPlugins.class) ); List<PluginSpec> actual = WithPlugins.RuleImpl.combinePlugins(annotations); List<PluginSpec> expected = Arrays.asList( new PluginSpec("keep"), new PluginSpec("keepv@1"), new PluginSpec("specify@42"), new PluginSpec("keepspecific@42"), new PluginSpec("override@2"), new PluginSpec("donotoverride@2"), new PluginSpec("inherrit"), new PluginSpec("add") ); assertThat(actual, equalTo(expected)); }

Target:
public void combine_WithPlugins_annotations() throws Exception { List<WithPlugins> annotations = Arrays.asList( FakeTestClass.class.getAnnotation(WithPlugins.class), FakeTestClass.class.getMethod("test").getAnnotation(WithPlugins.class) ); List<PluginSpec> actual = WithPlugins.RuleImpl.combinePlugins(annotations); List<PluginSpec> expected = Arrays.asList( new PluginSpec("keep"), new PluginSpec("keepv@1"), new PluginSpec("specify@42"), new PluginSpec("keepspecific@42"), new PluginSpec("override@2"), new PluginSpec("donotoverride@2"), new PluginSpec("inherit"), new PluginSpec("add") ); assertThat(actual, equalTo(expected)); }
Source:
private ValidationResult validate(String line) { getLog().info("Testing import: " + line); ValidationResult validationResult = new ValidationResult(line, IS_VALID_IMPORT.test(line)); if (!validationResult.isValid()) { if (warnOnlyModules.contains(project.getArtifactId()) || warnOnlyModules.contains("*")) { getLog().warn("Import with missing version found: " + line); } else { getLog().error("Import with missing version found: " + line); } } return validationResult; }

Target:
private ValidationResult validate(String line) { getLog().info("Testing import: " + line); ValidationResult validationResult = new ValidationResult(line, IS_VALID_IMPORT.test(line)); if (validationResult.isValid()) { return validationResult; } if (warnOnlyModules.contains(project.getArtifactId()) || warnOnlyModules.contains("*")) { getLog().warn("Import with missing version found: " + line); } else { getLog().error("Import with missing version found: " + line); } return validationResult; }
Source:
public void testFactories() { assertTrue(OkHttpClientConnectionPoolFactory.class.isInstance(connectionPoolFactory)); assertTrue(OkHttpClientConfigurationTestApp.MyOkHttpClientConnectionPoolFactory.class.isInstance(connectionPoolFactory)); assertTrue(OkHttpClientFactory.class.isInstance(okHttpClientFactory)); assertTrue(OkHttpClientConfigurationTestApp.MyOkHttpClientFactory.class.isInstance(okHttpClientFactory)); }

Target:
public void testFactories() { Assertions.assertThat(connectionPoolFactory).isInstanceOf(OkHttpClientConnectionPoolFactory.class); Assertions.assertThat(connectionPoolFactory).isInstanceOf(OkHttpClientConfigurationTestApp.MyOkHttpClientConnectionPoolFactory.class); Assertions.assertThat(okHttpClientFactory).isInstanceOf(OkHttpClientFactory.class); Assertions.assertThat(okHttpClientFactory).isInstanceOf(OkHttpClientConfigurationTestApp.MyOkHttpClientFactory.class); }
Source:
public void getDiseaseOccurrencesYetToBeReviewedMustOnlyReturnSpecifiedDiseaseGroup() { Expert expert = expertDao.getByEmail("zool1250@zoo.ox.ac.uk"); DiseaseOccurrence occurrence = diseaseOccurrenceDao.getById(1); DiseaseOccurrenceReviewResponse response = DiseaseOccurrenceReviewResponse.YES; createAndSaveDiseaseOccurrenceReview(expert, occurrence, response); Integer expertId = expert.getId(); Integer diseaseGroupId = occurrence.getDiseaseGroup().getId(); List<DiseaseOccurrence> list = diseaseOccurrenceDao.getDiseaseOccurrencesYetToBeReviewed(expertId, diseaseGroupId); for (DiseaseOccurrence item : list) { assertThat(item.getDiseaseGroup().getId()).isSameAs(diseaseGroupId); } }

Target:
public void getDiseaseOccurrencesYetToBeReviewedMustOnlyReturnSpecifiedDiseaseGroup() { Expert expert = expertDao.getByEmail("zool1250@zoo.ox.ac.uk"); DiseaseOccurrence occurrence = diseaseOccurrenceDao.getById(1); DiseaseOccurrenceReviewResponse response = DiseaseOccurrenceReviewResponse.YES; createAndSaveDiseaseOccurrenceReview(expert, occurrence, response); Integer expertId = expert.getId(); Integer diseaseGroupId = occurrence.getDiseaseGroup().getId(); List<DiseaseOccurrence> list = diseaseOccurrenceDao.getDiseaseOccurrencesYetToBeReviewed(expertId, diseaseGroupId); for (DiseaseOccurrence item : list) { assertThat(item.getDiseaseGroup().getId()).isEqualTo(diseaseGroupId); } }
Source:
public void GIVEN_correct_date_from_UI_WHEN_validate_date_time_THEN_validation_pass() { String actual = "" ; Calendar calendar_1 = new GregorianCalendar(2013, 2, 12, 10, 2, 3); Calendar calendar_2 = new GregorianCalendar(2015, 2, 12, 15, 3, 4); viewModel = new JournalViewModel(model); viewModel.setInitialFromDateTime(calendar_1, calendar_1); viewModel.setInitialToDateTime(calendar_2, calendar_2); viewModel.setFromDate(calendar_1); viewModel.setFromTime(calendar_1); viewModel.setToDate(calendar_2); viewModel.setToTime(calendar_2); viewModel.setErrorMessage(actual); String expected = viewModel.getErrorMessage(); assertEquals(expected, actual); }

Target:
public void GIVEN_correct_date_from_UI_WHEN_validate_date_time_THEN_validation_pass() { String actual = "" ; Calendar calendar_1 = new GregorianCalendar(2013, 2, 12, 10, 2, 3); Calendar calendar_2 = new GregorianCalendar(2015, 2, 12, 15, 3, 4); viewModel = new JournalViewModel(model); viewModel.setInitialFromDateTime((Calendar)calendar_1.clone(), (Calendar)calendar_1.clone()); viewModel.setInitialToDateTime((Calendar)calendar_2.clone(), (Calendar)calendar_2.clone()); viewModel.setFromDate(calendar_1); viewModel.setFromTime(calendar_1); viewModel.setToDate(calendar_2); viewModel.setToTime(calendar_2); String expected = viewModel.getErrorMessage(); assertEquals(expected, actual); }
Source:
public static SAXParserProvider getInstance() throws PrivilegedActionException { final SecurityManager sm = System.getSecurityManager(); ClassLoader tccl = null; if (sm == null) { tccl = Thread.currentThread().getContextClassLoader(); } else { tccl = AccessController.doPrivileged(new PrivilegedExceptionAction<ClassLoader>() { public ClassLoader run() throws Exception { return Thread.currentThread().getContextClassLoader(); } }); } SAXParserProvider spp; spp = saxParserProviders.get(tccl); if (spp == null) { spp = new SAXParserProvider(); SAXParserProvider s = saxParserProviders.putIfAbsent(tccl, spp); if (s != null) spp = s; } return spp; }

Target:
public static SAXParserProvider getInstance() { final SecurityManager sm = System.getSecurityManager(); ClassLoader tccl = null; if (sm == null) { tccl = Thread.currentThread().getContextClassLoader(); } else { try { tccl = AccessController.doPrivileged(new PrivilegedExceptionAction<ClassLoader>() { public ClassLoader run() throws Exception { return Thread.currentThread().getContextClassLoader(); } }); } catch (PrivilegedActionException e) { throw new SecurityException(e); } } SAXParserProvider spp; spp = saxParserProviders.get(tccl); if (spp == null) { spp = new SAXParserProvider(); SAXParserProvider s = saxParserProviders.putIfAbsent(tccl, spp); if (s != null) spp = s; } return spp; }
Source:
static Evaluator forName(String nameOfScriptEngine, String name) { try { Class.forName(nameOfScriptEngine); } catch (Throwable cause) { String message = "Class `" + nameOfScriptEngine + "` is not loadable, " + "script-based test execution is disabled. " + "If the originating cause is a `NoClassDefFoundError: javax/script/...` and " + "the underlying runtime environment is executed with an activated module system " + "(aka Jigsaw or JPMS) you need to add the `java.scripting` module to the " + "root modules via `--add-modules ...,java.scripting`"; return new ThrowingEvaluator(message, cause); } try { return (Evaluator) Class.forName(name).getDeclaredConstructor().newInstance(); } catch (ReflectiveOperationException cause) { String message = "Creating instance of class `" + name + "` failed," + "script-based test execution is disabled."; return new ThrowingEvaluator(message, cause); } }

Target:
static Evaluator forName(String nameOfScriptEngine, String name) { try { Class.forName(nameOfScriptEngine); } catch (Throwable cause) { BlacklistedExceptions.rethrowIfBlacklisted(cause); String message = "Class `" + nameOfScriptEngine + "` is not loadable, " + "script-based test execution is disabled. " + "If the originating cause is a `NoClassDefFoundError: javax/script/...` and " + "the underlying runtime environment is executed with an activated module system " + "(aka Jigsaw or JPMS) you need to add the `java.scripting` module to the " + "root modules via `--add-modules ...,java.scripting`"; return new ThrowingEvaluator(message, cause); } try { return (Evaluator) Class.forName(name).getDeclaredConstructor().newInstance(); } catch (ReflectiveOperationException cause) { String message = "Creating instance of class `" + name + "` failed," + "script-based test execution is disabled."; return new ThrowingEvaluator(message, cause); } }
Source:
public Message<String> receive() { try { synchronized (this.monitor) { if (!this.blockAndCloseContext && !this.reader.ready()) { return null; } String line = this.reader.readLine(); if (line == null) { ConfigurableApplicationContext context = (ConfigurableApplicationContext) getApplicationContext(); if (context != null) { this.logger.info("EOF on stream; closing context"); context.close(); } } return (line != null) ? new GenericMessage<String>(line) : null; } } catch (IOException e) { throw new MessagingException("IO failure occurred in adapter", e); } }

Target:
public Message<String> receive() { try { synchronized (this.monitor) { if (!this.blockToDetectEOF && !this.reader.ready()) { return null; } String line = this.reader.readLine(); if (line == null && this.applicationEventPublisher != null) { this.applicationEventPublisher.publishEvent(new StreamClosedEvent(this)); } return (line != null) ? new GenericMessage<String>(line) : null; } } catch (IOException e) { throw new MessagingException("IO failure occurred in adapter", e); } }
Source:
void shouldReturnKeys() { final Issues<Issue> issues = new Issues<>(); IssueBuilder builder = new IssueBuilder(); issues.add(builder.setCategory("key").build()); PropertyStatistics statistics = new PropertyStatistics(issues, "category", Function.identity()); Set<String> str = new HashSet(); str.add("key"); Set<String> actualProperty = statistics.getKeys(); assertThat(actualProperty).isEqualTo(str); }

Target:
void shouldReturnKeys() { Issues<Issue> issues = new Issues<>(); IssueBuilder builder = new IssueBuilder(); issues.add(builder.setCategory("key").build()); PropertyStatistics statistics = new PropertyStatistics(issues, "category", Function.identity()); assertThat(statistics).hasOnlyKeys("key"); }
Source:
public void testSchemaRetrieval() throws IOException { InputStream stream = getClass().getClassLoader().getResourceAsStream("data/exemple.json"); Schema schema = new Schema.Parser().parse(stream); long fingerprint = SchemaNormalization.parsingFingerprint64(schema); Schema retrieved = service.findByFingerprint(fingerprint); Assert.assertEquals(schema, retrieved); }

Target:
public void testSchemaRetrieval() throws IOException { InputStream stream = getClass().getClassLoader().getResourceAsStream("data/avro-schema-example.json"); Schema schema = new Schema.Parser().parse(stream); long fingerprint = SchemaNormalization.parsingFingerprint64(schema); Schema retrieved = service.findByFingerprint(fingerprint); assertEquals(schema, retrieved); }
Source:
public IHyperlink[] detectHyperlinks(ITextViewer textViewer, IRegion region, boolean canShowMultipleHyperlinks) { for (@NonNull LSPDocumentInfo info : LanguageServiceAccessor.getLSPDocumentInfosFor(textViewer.getDocument(), capabilities -> Boolean.TRUE.equals(capabilities.getDefinitionProvider()))) { try { CompletableFuture<List<? extends Location>> documentHighlight = info.getInitializedLanguageClient() .get(500, TimeUnit.MILLISECONDS).getTextDocumentService() .definition(LSPEclipseUtils.toTextDocumentPosistionParams(info.getFileUri(), region.getOffset(), info.getDocument())); List<? extends Location> locations = documentHighlight.get(2, TimeUnit.SECONDS); if (locations == null || locations.isEmpty()) { continue; } IRegion linkRegion = findWord(textViewer.getDocument(), region.getOffset()); if (linkRegion == null) { linkRegion = region; } List<IHyperlink> hyperlinks = new ArrayList<IHyperlink>(locations.size()); for (Location responseLocation : locations) { hyperlinks.add(new LSBasedHyperlink(responseLocation, linkRegion)); } return hyperlinks.toArray(new IHyperlink[hyperlinks.size()]); } catch (BadLocationException | InterruptedException | ExecutionException | TimeoutException e) { LanguageServerPlugin.logError(e); } } return null; }

Target:
public IHyperlink[] detectHyperlinks(ITextViewer textViewer, IRegion region, boolean canShowMultipleHyperlinks) { for (@NonNull LSPDocumentInfo info : LanguageServiceAccessor.getLSPDocumentInfosFor(textViewer.getDocument(), capabilities -> Boolean.TRUE.equals(capabilities.getDefinitionProvider()))) { try { CompletableFuture<List<? extends Location>> documentHighlight = info.getInitializedLanguageClient().thenCompose(ls -> { try { return ls.getTextDocumentService() .definition(LSPEclipseUtils.toTextDocumentPosistionParams(info.getFileUri(), region.getOffset(), info.getDocument())); } catch (BadLocationException e) { LanguageServerPlugin.logError(e); return CompletableFuture.completedFuture(Collections.emptyList()); } } ); List<? extends Location> locations = documentHighlight.get(2, TimeUnit.SECONDS); if (locations == null || locations.isEmpty()) { continue; } IRegion linkRegion = findWord(textViewer.getDocument(), region.getOffset()); if (linkRegion == null) { linkRegion = region; } List<IHyperlink> hyperlinks = new ArrayList<IHyperlink>(locations.size()); for (Location responseLocation : locations) { hyperlinks.add(new LSBasedHyperlink(responseLocation, linkRegion)); } return hyperlinks.toArray(new IHyperlink[hyperlinks.size()]); } catch (InterruptedException | ExecutionException | TimeoutException e) { LanguageServerPlugin.logError(e); } } return null; }
Source:
public synchronized static MetricRegistry setDefault(String name) { if (defaultRegistryName == null) { final MetricRegistry registry = getOrCreate(name); defaultRegistryName = name; return registry; } throw new IllegalStateException("Default metric registry name is already set."); }

Target:
public synchronized static MetricRegistry setDefault(String name) { final MetricRegistry registry = getOrCreate(name); return setDefault(name, registry); }
Source:
private void updateGlobalKeys() { Set<String> activeKeys = new HashSet<String>(m_globalKeyStrokes.size()); for (IRwtKeyStroke stroke : m_globalKeyStrokes) { if (stroke.isRegisterActiveKey()) { String activeKey = resolveKeyString(stroke); activeKeys.add(activeKey); } } Set<Entry<Widget, List<String>>> map = m_widgetActiveKeys.entrySet(); Iterator<Entry<Widget, List<String>>> iterator = map.iterator(); while (iterator.hasNext()) { Entry<Widget, List<String>> item = iterator.next(); activeKeys.addAll(item.getValue()); } if (activeKeys.size() == 0) { m_environment.getDisplay().setData(RWT.ACTIVE_KEYS, EMPTY_STRING_ARRAY); } else { String[] activeKeyArray = activeKeys.toArray(new String[activeKeys.size()]); m_environment.getDisplay().setData(RWT.ACTIVE_KEYS, activeKeyArray); } if (m_globalCancelKeyList == null || m_globalCancelKeyList.size() == 0) { m_environment.getDisplay().setData(RWT.CANCEL_KEYS, EMPTY_STRING_ARRAY); } else { String[] cancelKeyArray = m_globalCancelKeyList.toArray(new String[m_globalCancelKeyList.size()]); m_environment.getDisplay().setData(RWT.CANCEL_KEYS, cancelKeyArray); } }

Target:
private void updateGlobalKeys() { Set<String> activeKeys = new HashSet<String>(m_globalKeyStrokes.size()); for (IRwtKeyStroke stroke : m_globalKeyStrokes) { if (stroke.isRegisterActiveKey()) { String activeKey = resolveKeyString(stroke); if (!activeKeys.contains(activeKey)) { activeKeys.add(activeKey); } } } if (activeKeys.size() == 0) { m_environment.getDisplay().setData(RWT.ACTIVE_KEYS, EMPTY_STRING_ARRAY); } else { String[] activeKeyArray = activeKeys.toArray(new String[activeKeys.size()]); m_environment.getDisplay().setData(RWT.ACTIVE_KEYS, activeKeyArray); } if (m_globalCancelKeyList == null || m_globalCancelKeyList.size() == 0) { m_environment.getDisplay().setData(RWT.CANCEL_KEYS, EMPTY_STRING_ARRAY); } else { String[] cancelKeyArray = m_globalCancelKeyList.toArray(new String[m_globalCancelKeyList.size()]); m_environment.getDisplay().setData(RWT.CANCEL_KEYS, cancelKeyArray); } }
Source:
public int writeAsBinary(ByteBuf buffer, @Nonnull Object value) { Period period = (Period) value; buffer.writeInt(TYPE_LEN); buffer.writeLong(period.getSeconds()); buffer.writeInt(period.getDays()); buffer.writeInt(period.getMonths()); return TYPE_LEN; }

Target:
public int writeAsBinary(ByteBuf buffer, @Nonnull Object value) { Period period = (Period) value; buffer.writeInt(TYPE_LEN); buffer.writeLong( (period.getHours() * 60 * 60 * 1000_000L) + (period.getMinutes() * 60 * 1000_000L) + (period.getSeconds() * 1000_000L) + (period.getMillis() * 1000) ); buffer.writeInt((period.getWeeks() * 7) + period.getDays()); buffer.writeInt((period.getYears() * 12) + period.getMonths()); return INT32_BYTE_SIZE + TYPE_LEN; }
Source:
public boolean isActivated() { Jenkins j = Jenkins.getInstance(); CrumbIssuer currentIssuer = j.getCrumbIssuer(); if (currentIssuer == null) { return true; } return false; }

Target:
public boolean isActivated() { return Jenkins.getInstance().getCrumbIssuer() == null; }
Source:
private void verifyHealthy(final String host, final TaskStatus status) { log.debug("Checking health of on {}", job.getImage(), host); final TaskStatus.State state = status.getState(); if (state == TaskStatus.State.UNKNOWN || state == TaskStatus.State.FAILED || state == TaskStatus.State.EXITED || state == TaskStatus.State.STOPPED) { String stateString = state.toString(); if (status.getThrottled() != ThrottleState.NO) { stateString += format("(%s)", status.getThrottled()); } throw new AssertionError(format( "Unexpected job state %s. Check helios agent logs for details.", stateString)); } }

Target:
private void verifyHealthy(final String host, final TaskStatus status) { log.debug("Checking health of on {}", job.getImage(), host); final TaskStatus.State state = status.getState(); if (state == TaskStatus.State.FAILED || state == TaskStatus.State.EXITED || state == TaskStatus.State.STOPPED) { String stateString = state.toString(); if (status.getThrottled() != ThrottleState.NO) { stateString += format("(%s)", status.getThrottled()); } throw new AssertionError(format( "Unexpected job state %s. Check helios agent logs for details.", stateString)); } }
Source:
private void routeItems(Location inputNode, Block inputTarget, int frequency, Map<Integer, List<Location>> outputNodes) { ItemStackAndInteger slot = CargoUtils.withdraw(inventories, inputNode.getBlock(), inputTarget); if (slot == null) { return; } ItemStack stack = slot.getItem(); int previousSlot = slot.getInt(); List<Location> destinations = outputNodes.get(frequency); if (destinations != null) { stack = distributeItem(stack, inputNode, destinations); } if (stack != null) { Inventory inv = inventories.get(inputTarget.getLocation()); if (inv != null) { if (inv.getItem(previousSlot) == null) { inv.setItem(previousSlot, stack); } else if((stack = inv.addItem(stack).get(0)) != null){ inputTarget.getWorld().dropItem(inputTarget.getLocation().add(0, 1, 0), stack); } } else { DirtyChestMenu menu = CargoUtils.getChestMenu(inputTarget); if (menu != null) { if (menu.getItemInSlot(previousSlot) == null) { menu.replaceExistingItem(previousSlot, stack); } else { inputTarget.getWorld().dropItem(inputTarget.getLocation().add(0, 1, 0), stack); } } } } }

Target:
private void routeItems(Location inputNode, Block inputTarget, int frequency, Map<Integer, List<Location>> outputNodes) { ItemStackAndInteger slot = CargoUtils.withdraw(inventories, inputNode.getBlock(), inputTarget); if (slot == null) { return; } ItemStack stack = slot.getItem(); int previousSlot = slot.getInt(); List<Location> destinations = outputNodes.get(frequency); if (destinations != null) { stack = distributeItem(stack, inputNode, destinations); } if (stack != null) { Inventory inv = inventories.get(inputTarget.getLocation()); if (inv != null) { if (inv.getItem(previousSlot) == null) { inv.setItem(previousSlot, stack); } else { ItemStack rest = inv.addItem(stack).get(0); if (rest != null) { inputTarget.getWorld().dropItem(inputTarget.getLocation().add(0, 1, 0), rest); } } } else { DirtyChestMenu menu = CargoUtils.getChestMenu(inputTarget); if (menu != null) { if (menu.getItemInSlot(previousSlot) == null) { menu.replaceExistingItem(previousSlot, stack); } else { inputTarget.getWorld().dropItem(inputTarget.getLocation().add(0, 1, 0), stack); } } } } }
Source:
private static void registerCustomIBClasses() { File ibClassesFile = new File(NSBundle.getMainBundle().getBundlePath() + "/ib.classes"); if (ibClassesFile.exists()) { try { BufferedReader reader = new BufferedReader(new FileReader(ibClassesFile)); String line = reader.readLine(); String[] customClasses = line.split(","); for (String customClass : customClasses) { try { ObjCClass.getByName(customClass); } catch (ObjCClassNotFoundException e) { } } reader.close(); } catch (IOException e) { e.printStackTrace(); } } }

Target:
private static void registerCustomIBClasses() { File ibClassesFile = new File(NSBundle.getMainBundle().getBundlePath() + "/ib.classes"); if (ibClassesFile.exists()) { try { try (BufferedReader reader = new BufferedReader(new FileReader(ibClassesFile))) { String line = reader.readLine(); String[] customClasses = line.split(","); for (String customClass : customClasses) { try { ObjCClass.getByName(customClass); } catch (ObjCClassNotFoundException e) { } } } } catch (IOException e) { e.printStackTrace(); } } }
Source:
void receiveMessageAutoComplete() { final String messageId = UUID.randomUUID().toString(); final String contents = "Some-contents"; final ServiceBusMessage message = TestUtils.getServiceBusMessage(contents, messageId, 0); StepVerifier.create(sender.send(message).thenMany(receiver.receive().take(1))) .assertNext(receivedMessage -> { Assertions.assertEquals(contents, receivedMessage.getBodyAsString()); Assertions.assertTrue(receivedMessage.getProperties().containsKey(MESSAGE_TRACKING_ID)); }) .verifyComplete(); System.out.println("Completed."); }

Target:
void receiveMessageAutoComplete() { final String messageId = UUID.randomUUID().toString(); final String contents = "Some-contents"; final ServiceBusMessage message = TestUtils.getServiceBusMessage(contents, messageId, 0); StepVerifier.create(sender.send(message).thenMany(receiver.receive().take(1))) .assertNext(receivedMessage -> { Assertions.assertEquals(contents, new String(receivedMessage.getBody())); Assertions.assertTrue(receivedMessage.getProperties().containsKey(MESSAGE_TRACKING_ID)); }) .verifyComplete(); }
Source:
private void renamePlaceDialog(final String placeName) { Log.d(TAG, "renamePlaceDialog"); AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity()); final EditText input = new EditText(getActivity()); dialog.setTitle("Rename " + placeName + "?") .setMessage(R.string.write_place_name) .setView(input) .setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { String newName = input.getText().toString(); renamePlace(placeName, newName); dialog.dismiss(); } }) .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); dialog.show(); }

Target:
private void renamePlaceDialog(final String placeName) { Log.d(TAG, "renamePlaceDialog"); AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity()); final EditText input = new EditText(getActivity()); String titleFormat = getResources().getString(R.string.rename_place); String title = String.format(titleFormat, placeName); dialog.setTitle(title) .setMessage(R.string.write_place_name) .setView(input) .setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { String newName = input.getText().toString(); renamePlace(placeName, newName); dialog.dismiss(); } }) .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); dialog.show(); }
Source:
public void buttonStateChanged(VRControllerState_t stateBefore, VRControllerState_t stateAfter, int handIndex) { cachedStateBefore = stateBefore; cachedStateAfter = stateAfter; queuedActions.add(new ControllerAction(InputType.CONTROLLER_BUTTON.getInput(ControllerId.X_AXIS), "OpenVR", ButtonState.DOWN, 1.0f)); if (handIndex == 0) { handleController0(); } else { handleController1(); } }

Target:
public void buttonStateChanged(VRControllerState_t stateBefore, VRControllerState_t stateAfter, int handIndex) { cachedStateBefore = stateBefore; cachedStateAfter = stateAfter; if (handIndex == 0) { handleController0(); } else { handleController1(); } }
Source:
private SearchResponse doSearch(Object searchAfterValues) { SearchRequest searchRequest = new SearchRequest(index); searchRequest.indicesOptions(MlIndicesUtils.addIgnoreUnavailable(SearchRequest.DEFAULT_INDICES_OPTIONS)); SearchSourceBuilder sourceBuilder = (new SearchSourceBuilder() .size(BATCH_SIZE) .query(getQuery()) .fetchSource(shouldFetchSource()) .trackTotalHits(true) .sort(sortField())); if (searchAfterValues != null) { sourceBuilder.searchAfter(searchAfterValues); } searchRequest.source(sourceBuilder); return client.search(searchRequest).actionGet(); }

Target:
private SearchResponse doSearch(Object searchAfterValues) { SearchRequest searchRequest = new SearchRequest(index); searchRequest.indicesOptions(MlIndicesUtils.addIgnoreUnavailable(SearchRequest.DEFAULT_INDICES_OPTIONS)); SearchSourceBuilder sourceBuilder = (new SearchSourceBuilder() .size(batchSize) .query(getQuery()) .fetchSource(shouldFetchSource()) .sort(sortField())); if (searchAfterValues != null) { sourceBuilder.searchAfter(searchAfterValues); } searchRequest.source(sourceBuilder); return client.search(searchRequest).actionGet(); }
Source:
public GlobalDirectoryResourceDefinition() { super(new SimpleResourceDefinition.Parameters(PathElement.pathElement(EESubsystemModel.GLOBAL_DIRECTORY), EeExtension.getResourceDescriptionResolver(EESubsystemModel.GLOBAL_DIRECTORY)) .setAddRestartLevel(OperationEntry.Flag.RESTART_JVM) .setRemoveRestartLevel(OperationEntry.Flag.RESTART_JVM) .setAddHandler(GlobalDirectoryResourceDefinition.ADD) .setRemoveHandler(GlobalDirectoryResourceDefinition.REMOVE) .setCapabilities(EE_GLOBAL_DIRECTORY_CAPABILITY) ); }

Target:
public GlobalDirectoryResourceDefinition() { super(new SimpleResourceDefinition.Parameters(PathElement.pathElement(EESubsystemModel.GLOBAL_DIRECTORY), EeExtension.getResourceDescriptionResolver(EESubsystemModel.GLOBAL_DIRECTORY)) .setAddHandler(GlobalDirectoryResourceDefinition.ADD) .setRemoveHandler(GlobalDirectoryResourceDefinition.REMOVE) .setCapabilities(EE_GLOBAL_DIRECTORY_CAPABILITY) ); }
Source:
public String getDisplayName() { return "VisualSVN"; }

Target:
public String getDisplayName() { return Messages.SubversionSCM_browsers_VisualSVN(); }
Source:
public static void main(String[] args) { HazelcastInstance hz = Hazelcast.newHazelcastInstance(); IMap<String, Person> map = hz.getMap("map"); map.put("1", new Person("peter", limb("left-hand"), limb("right-hand"))); map.put("2", new Person("hans", limb("linke-hand"), limb("rechte-hand"))); Set<Person> employees = (Set<Person>) map.values(new SqlPredicate("limbs[any].name == linke-hand")); System.out.println("People:" + employees); }

Target:
public static void main(String[] args) { HazelcastInstance hz = Hazelcast.newHazelcastInstance(); IMap<String, Person> map = hz.getMap("map"); map.put("1", new Person("peter", limb("left-hand"), limb("right-hand"))); map.put("2", new Person("hans", limb("left-leg"), limb("right-leg"))); Set<Person> employees = (Set<Person>) map.values(new SqlPredicate("limbs[any].name == right-leg")); System.out.println("People:" + employees); }
Source:
public void testGetCollectorConfigurationWithBusinessTxnConfigs() { assertNull(service.getBusinessTransaction(null, BTXNCONFIG1)); assertNull(service.getBusinessTransaction(null, BTXNCONFIG2)); BusinessTxnConfig btxnconfig1 = new BusinessTxnConfig(); btxnconfig1.setDescription(DESCRIPTION1); btxnconfig1.setFilter(new Filter()); btxnconfig1.getFilter().getInclusions().add("myfilter"); BusinessTxnConfig btxnconfig2 = new BusinessTxnConfig(); btxnconfig2.setDescription(DESCRIPTION2); btxnconfig2.setFilter(new Filter()); btxnconfig2.getFilter().getInclusions().add("myfilter"); try { service.setBusinessTransaction(null, BTXNCONFIG1, btxnconfig1); service.setBusinessTransaction(null, BTXNCONFIG2, btxnconfig2); } catch (Exception e1) { fail("Failed to add btxnconfigs: " + e1); } service.getCollector(null, null, null, null); Wait.until(() -> service.getCollector(null, null, null, null) != null); CollectorConfiguration cc = service.getCollector(null, null, null, null); assertNotNull(cc); assertNotNull(cc.getBusinessTransactions().get(BTXNCONFIG1)); assertNotNull(cc.getBusinessTransactions().get(BTXNCONFIG2)); try { service.removeBusinessTransaction(null, BTXNCONFIG1); service.removeBusinessTransaction(null, BTXNCONFIG2); } catch (Exception e1) { fail("Failed to remove btxnconfigs: " + e1); } Wait.until( () -> service.getBusinessTransaction(null, BTXNCONFIG1) == null && service.getBusinessTransaction(null, BTXNCONFIG2) == null); assertNull(service.getBusinessTransaction(null, BTXNCONFIG1)); assertNull(service.getBusinessTransaction(null, BTXNCONFIG2)); }

Target:
public void testGetCollectorConfigurationWithBusinessTxnConfigs() { assertNull(service.getBusinessTransaction(null, BTXNCONFIG1)); assertNull(service.getBusinessTransaction(null, BTXNCONFIG2)); BusinessTxnConfig btxnconfig1 = new BusinessTxnConfig(); btxnconfig1.setDescription(DESCRIPTION1); btxnconfig1.setFilter(new Filter()); btxnconfig1.getFilter().getInclusions().add("myfilter"); BusinessTxnConfig btxnconfig2 = new BusinessTxnConfig(); btxnconfig2.setDescription(DESCRIPTION2); btxnconfig2.setFilter(new Filter()); btxnconfig2.getFilter().getInclusions().add("myfilter"); try { service.setBusinessTransaction(null, BTXNCONFIG1, btxnconfig1); service.setBusinessTransaction(null, BTXNCONFIG2, btxnconfig2); } catch (Exception e1) { fail("Failed to add btxnconfigs: " + e1); } Wait.until(() -> service.getCollector(null, null, null, null) != null); CollectorConfiguration cc = service.getCollector(null, null, null, null); assertNotNull(cc); assertNotNull(cc.getBusinessTransactions().get(BTXNCONFIG1)); assertNotNull(cc.getBusinessTransactions().get(BTXNCONFIG2)); try { service.removeBusinessTransaction(null, BTXNCONFIG1); service.removeBusinessTransaction(null, BTXNCONFIG2); } catch (Exception e1) { fail("Failed to remove btxnconfigs: " + e1); } Wait.until( () -> service.getBusinessTransaction(null, BTXNCONFIG1) == null && service.getBusinessTransaction(null, BTXNCONFIG2) == null); assertNull(service.getBusinessTransaction(null, BTXNCONFIG1)); assertNull(service.getBusinessTransaction(null, BTXNCONFIG2)); }
Source:
public void close() throws Exception { writer.close(); super.close(); }

Target:
public void close() throws Exception { super.close(); writer.close(); }
Source:
public void testPersistBookieStatus() throws Exception { File tmpDir = createTempDir("bookie", "test"); final ServerConfiguration conf = TestBKConfiguration.newServerConfiguration(); conf.setJournalDirName(tmpDir.getPath()) .setLedgerDirNames(new String[] { tmpDir.getPath() }) .setReadOnlyModeEnabled(true) .setPersistBookieStatusEnabled(true).setZkServers(zkUtil.getZooKeeperConnectString()); BookieServer bookieServer = new BookieServer(conf); bookieServer.start(); Bookie bookie = bookieServer.getBookie(); assertFalse(bookie.isReadOnly()); ((Bookie.BookieStateManager) bookie.getStateManager()).doTransitionToReadOnlyMode(); assertTrue(bookie.isReadOnly()); bookieServer.shutdown(); bookieServer = new BookieServer(conf); bookieServer.start(); bookie = bookieServer.getBookie(); assertTrue(bookie.isReadOnly()); ((Bookie.BookieStateManager) bookie.getStateManager()).doTransitionToWritableMode(); bookieServer.shutdown(); bookieServer = new BookieServer(conf); bookieServer.start(); bookie = bookieServer.getBookie(); assertFalse(bookie.isReadOnly()); bookieServer.shutdown(); }

Target:
public void testPersistBookieStatus() throws Exception { File tmpDir = createTempDir("bookie", "test"); final ServerConfiguration conf = TestBKConfiguration.newServerConfiguration(); conf.setJournalDirName(tmpDir.getPath()) .setLedgerDirNames(new String[] { tmpDir.getPath() }) .setReadOnlyModeEnabled(true) .setPersistBookieStatusEnabled(true).setZkServers(zkUtil.getZooKeeperConnectString()); BookieServer bookieServer = new BookieServer(conf); bookieServer.start(); Bookie bookie = bookieServer.getBookie(); assertFalse(bookie.isReadOnly()); bookie.getStateManager().doTransitionToReadOnlyMode(); assertTrue(bookie.isReadOnly()); bookieServer.shutdown(); bookieServer = new BookieServer(conf); bookieServer.start(); bookie = bookieServer.getBookie(); assertTrue(bookie.isReadOnly()); bookie.getStateManager().doTransitionToWritableMode(); bookieServer.shutdown(); bookieServer = new BookieServer(conf); bookieServer.start(); bookie = bookieServer.getBookie(); assertFalse(bookie.isReadOnly()); bookieServer.shutdown(); }