auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void prepareAmend(boolean amend) { String jobname = NLS.bind(UIText.ResetAction_reset, HEADS_FIRST_PARENT); final ResetOperation operation; if (amend) { amendedCommit = Activator.getDefault().getRepositoryUtil() .parseHeadCommit(currentRepository); operation = new ResetOperation(currentRepository, HEADS_FIRST_PARENT, ResetType.SOFT); } else { if (amendedCommit == null) { throw new IllegalStateException( "amendedCommit should have been set on previous amend"); } operation = new ResetOperation(currentRepository, amendedCommit.name(), ResetType.SOFT); } JobUtil.scheduleUserJob(operation, jobname, JobFamilies.RESET); }

Target:
private void prepareAmend(boolean amend) { String jobname = NLS.bind(UIText.ResetAction_reset, HEADS_FIRST_PARENT); final ResetOperation operation; if (amend) { amendedCommit = Activator.getDefault().getRepositoryUtil() .parseHeadCommit(currentRepository); operation = new ResetOperation(currentRepository, HEADS_FIRST_PARENT, ResetType.SOFT); } else { if (amendedCommit == null) { throw new IllegalStateException( "amendedCommit should have been set on previous amend"); } operation = new ResetOperation(currentRepository, amendedCommit.name(), ResetType.SOFT); } operation.disableReflog(true); JobUtil.scheduleUserJob(operation, jobname, JobFamilies.RESET); }
Source:
public static void main(String[] args) throws IOException { Connector connector = new Connector(); SessionManager sessionManager = connector.getSessionManager(); Session session = sessionManager.createOrFindSessionAndJoin("example2"); FileWriter writer = new FileWriter("demoBuildingText"); writer.write("Session link: " + "<LINK_0>" + session.getId() + "/?token=" + session.getServerToken() + "\n"); writer.close(); HttpConnection connection = connector.getConnection(); String allowInteraction = "event/SettingsLogicEventType/SETTINGS_ALLOW_GAME_INTERACTION/"; JSONArray param = new JSONArray(); param.put(true); connection.execute(allowInteraction, CallType.POST, new JsonObjectResultHandler(), session, param); Environment environment = session.getEnvironment(); environment.setStakeholder(2); StakeholderList stakeholderList = environment.loadStakeHolders(); Stakeholder selectedStakeholder = null; for (Stakeholder stakeholder : stakeholderList) { if (stakeholder.getType().equals("HOUSING_CORPORATION")) { selectedStakeholder = stakeholder; } } System.out.println("Building done: " + environment.build(selectedStakeholder, 500)); }

Target:
public static void main(String[] args) throws IOException { Connector connector = new Connector(); SessionManager sessionManager = connector.getSessionManager(); Session session = sessionManager.createOrFindSessionAndJoin("example2"); FileWriter writer = new FileWriter("demoBuildingText"); writer.write("Session link: " + "<LINK_0>" + session.getId() + "/?token=" + session.getServerToken() + "\n"); writer.close(); HttpConnection connection = connector.getConnection(); String allowInteraction = "event/SettingsLogicEventType/SETTINGS_ALLOW_GAME_INTERACTION/"; JSONArray param = new JSONArray(); param.put(true); connection.execute(allowInteraction, CallType.POST, new JsonObjectResultHandler(), session, param); Environment environment = session.getEnvironment(); environment.setStakeholder(2); StakeholderList stakeholderList = environment.loadStakeHolders(); Stakeholder selectedStakeholder = null; for (Stakeholder stakeholder : stakeholderList) { if (stakeholder.getType().equals("HOUSING_CORPORATION")) { selectedStakeholder = stakeholder; } } logger.info("Building done: " + environment.build(selectedStakeholder, 50)); }
Source:
protected String createADocument() throws Exception { DocumentModel doc = session.createDocumentModel("/", "myFolder", "Folder"); doc = session.createDocument(doc); ACP acp = new ACPImpl(); ACL acl = new ACLImpl(); acl.add(new ACE("Administrator", "Everything", true)); acl.add(new ACE(USERNAME, "Read", true)); acp.addACL(acl); doc.setACP(acp, false); session.save(); txFeature.nextTransaction(); return doc.getId(); }

Target:
protected String createADocument() throws Exception { DocumentModel doc = session.createDocumentModel("/", "myFolder", "Folder"); doc = session.createDocument(doc); ACP acp = new ACPImpl(); acp.getOrCreateACL().add(new ACE("Administrator", "Everything", true)); acp.getOrCreateACL().add(new ACE(USERNAME, "Read", true)); doc.setACP(acp, false); session.save(); txFeature.nextTransaction(); return doc.getId(); }
Source:
private BufferedImage createErrorImage(final Rectangle area) { final BufferedImage bufferedImage = new BufferedImage(area.width, area.height, TYPE_INT_ARGB_PRE); final Graphics2D graphics = bufferedImage.createGraphics(); try { graphics.setBackground(new Color(255, 78, 78, 125)); graphics.clearRect(0, 0, area.width, area.height); return bufferedImage; } finally { graphics.dispose(); } }

Target:
private BufferedImage createErrorImage(final Rectangle area) { final BufferedImage bufferedImage = new BufferedImage(area.width, area.height, TYPE_INT_ARGB_PRE); final Graphics2D graphics = bufferedImage.createGraphics(); try { graphics.setBackground(this.configuration.getTransparentTileErrorColor()); graphics.clearRect(0, 0, area.width, area.height); return bufferedImage; } finally { graphics.dispose(); } }
Source:
static KeyStore createTrustStoreFromCertificates(Path path) { KeyStore keyStore; keyStore = createKeyStore(); for (File currFile : getFilesForPath(path)) { try (InputStream in = Files.newInputStream(currFile.toPath())) { List<Certificate> certificates = readX509Certificates(in); int certIndex = 0; for (Certificate cert : certificates) { keyStore.setCertificateEntry(currFile.getName() + certIndex, cert); certIndex++; } } catch (IOException e) { throw new RuntimeException(String.format( "IOException encountered when opening '%s'", currFile.toPath()), e); } catch (CertificateException | KeyStoreException e) { throw new RuntimeException(String.format( "Could not read file at \"%s\" as an X.509 certificate", currFile.toPath()), e); } } return keyStore; }

Target:
static KeyStore createTrustStoreFromCertificates(Path path) { KeyStore keyStore; keyStore = createKeyStore(); for (File currFile : getFilesForPath(path)) { try (InputStream in = Files.newInputStream(currFile.toPath())) { addCertificatesToKeystore(keyStore, currFile.getName(), readX509Certificates(in)); } catch (IOException e) { throw new RuntimeException(String.format( "IOException encountered when opening '%s'", currFile.toPath()), e); } catch (CertificateException | KeyStoreException e) { throw new RuntimeException(String.format( "Could not read file at \"%s\" as an X.509 certificate", currFile.toPath()), e); } } return keyStore; }
Source:
public void dispose() { app.getChildren().remove(windowModel); coolBarManager.dispose(); menuManager.dispose(); statusLineManager.dispose(); windowModel.setToBeRendered(false); windowModel.getContext().deactivate(); windowModel.getContext().dispose(); ((Shell) windowModel.getWidget()).dispose(); }

Target:
public void dispose() { app.getChildren().remove(windowModel); coolBarManager.dispose(); menuManager.dispose(); statusLineManager.dispose(); windowModel.getContext().deactivate(); windowModel.getContext().dispose(); ((Shell) windowModel.getWidget()).dispose(); }
Source:
public Long getCurrSequenceValue(final String SequenceName) { session = HibernateUtil.getSessionFactory().openSession(); session.beginTransaction(); Query query = session.createSQLQuery(String.format("select currval('public.%s')", SequenceName)); return ((BigInteger) query.uniqueResult()).longValue(); }

Target:
public Long getCurrSequenceValue(final String SequenceName) { return getSequenceValue(SequenceName, COL_CURRVAl); }
Source:
private Library createLibrary(DetailedSample sample, int libraryNum) { Library lib = new LibraryImpl(); lib.setDescription("library"); lib.setSample(sample); LibraryType lt = new LibraryType(); lt.setId(libraryTypeId); lib.setLibraryType(lt); lib.setPlatformName("Illumina"); lib.setPaired(true); lib.setQcPassed(true); LibrarySelectionType sel = new LibrarySelectionType(); sel.setId(librarySelectionTypeId); lib.setLibrarySelectionType(sel); LibraryStrategyType strat = new LibraryStrategyType(); strat.setId(libraryStrategyTypeId); lib.setLibraryStrategyType(strat); ((DetailedLibrary) lib).setArchived(false); lib.setAlias(getRootSample(sample).getAlias() + "_Ad_R_PE_" + (libraryNum > 9 ? libraryNum : "0" + libraryNum) + "_WG"); return lib; }

Target:
private DetailedLibrary createLibrary(DetailedSample sample, int libraryNum) { DetailedLibrary lib = new DetailedLibraryImpl(); lib.setDescription("library"); lib.setSample(sample); LibraryType lt = new LibraryType(); lt.setId(libraryTypeId); lib.setLibraryType(lt); lib.setPlatformName("Illumina"); lib.setPaired(true); lib.setQcPassed(true); LibrarySelectionType sel = new LibrarySelectionType(); sel.setId(librarySelectionTypeId); lib.setLibrarySelectionType(sel); LibraryStrategyType strat = new LibraryStrategyType(); strat.setId(libraryStrategyTypeId); lib.setLibraryStrategyType(strat); lib.setAlias(getRootSample(sample).getAlias() + "_Ad_R_PE_" + (libraryNum > 9 ? libraryNum : "0" + libraryNum) + "_WG"); return lib; }
Source:
public Well(final Composite parent, final String text, final FormToolkit toolkit, final int severity) { super(parent, SWT.NONE); setLayout(GridLayoutFactory.fillDefaults().extendedMargins(10, 10, 5, 8).create()); addPaintListener(new PaintListener() { @Override public void paintControl(final PaintEvent e) { e.gc.setForeground(separatorColor(toolkit, severity)); e.gc.setLineWidth(2); e.gc.drawLine(5, -5, 5, e.height + 10); e.gc.setBackground(backgroundrColor(toolkit, severity)); e.gc.fillRectangle(6, -5, e.width, e.height + 10); } }); toolkit.adapt(this); label = toolkit.createLabel(this, text, SWT.WRAP); label.setBackground(backgroundrColor(toolkit, severity)); label.setLayoutData(GridDataFactory.fillDefaults().grab(true, false).hint(parent.computeSize(SWT.DEFAULT, SWT.DEFAULT).x, SWT.DEFAULT) .create()); }

Target:
public Well(final Composite parent, final String text, final FormToolkit toolkit, final int severity) { super(parent, SWT.NONE); setLayout(GridLayoutFactory.fillDefaults().extendedMargins(10, 10, 5, 8).create()); addPaintListener(new PaintListener() { @Override public void paintControl(final PaintEvent e) { e.gc.setForeground(separatorColor(toolkit, severity)); e.gc.setLineWidth(2); e.gc.drawLine(5, -5, 5, e.height + 10); e.gc.setBackground(backgroundColor(toolkit, severity)); e.gc.fillRectangle(6, -5, e.width, e.height + 10); } }); toolkit.adapt(this); label = toolkit.createLabel(this, text, SWT.WRAP); label.setBackground(backgroundColor(toolkit, severity)); label.setLayoutData(GridDataFactory.fillDefaults().grab(true, false).hint(parent.computeSize(SWT.DEFAULT, SWT.DEFAULT).x, SWT.DEFAULT) .create()); }
Source:
public <K, V> Store<K, V> createStore(Store.Configuration<K, V> storeConfig, ServiceConfiguration<?>... serviceConfigs) { ResourcePools resourcePools = storeConfig.getResourcePools(); ResourcePool heapPool = null; ResourcePool diskPool = null; if (resourcePools != null) { heapPool = resourcePools.getPoolForResource("heap"); diskPool = resourcePools.getPoolForResource("disk"); } List<ServiceConfiguration<?>> enhancedServiceConfigs = new ArrayList<ServiceConfiguration<?>>(Arrays.asList(serviceConfigs)); Store.Provider provider; if (diskPool != null) { if (heapPool == null) { throw new IllegalArgumentException("Cannot store to disk without heap resource"); } provider = serviceProvider.findService(CacheStore.Provider.class); enhancedServiceConfigs.add(new CacheStoreServiceConfig().cachingTierProvider(OnHeapStore.Provider.class).authoritativeTierProvider(DiskStore.Provider.class)); } else { provider = serviceProvider.findService(OnHeapStore.Provider.class); } return provider.createStore(storeConfig, enhancedServiceConfigs.toArray(new ServiceConfiguration<?>[0])); }

Target:
public <K, V> Store<K, V> createStore(Store.Configuration<K, V> storeConfig, ServiceConfiguration<?>... serviceConfigs) { ResourcePool heapPool = storeConfig.getResourcePools().getPoolForResource(ResourceType.Core.HEAP); ResourcePool diskPool = storeConfig.getResourcePools().getPoolForResource(ResourceType.Core.DISK); List<ServiceConfiguration<?>> enhancedServiceConfigs = new ArrayList<ServiceConfiguration<?>>(Arrays.asList(serviceConfigs)); Store.Provider provider; if (diskPool != null) { if (heapPool == null) { throw new IllegalArgumentException("Cannot store to disk without heap resource"); } provider = serviceProvider.findService(CacheStore.Provider.class); enhancedServiceConfigs.add(new CacheStoreServiceConfig().cachingTierProvider(OnHeapStore.Provider.class).authoritativeTierProvider(DiskStore.Provider.class)); } else { provider = serviceProvider.findService(OnHeapStore.Provider.class); } return provider.createStore(storeConfig, enhancedServiceConfigs.toArray(new ServiceConfiguration<?>[0])); }
Source:
public static boolean match (final String mimeType1, final String mimeType2) { if (ACCEPT_ALL.equals(mimeType1)) { return true; } final MimeType mimeTypeObj1 = Sneaky.sneak(() -> new MimeType(mimeType1)); final MimeType mimeTypeObj2 = Sneaky.sneak(() -> new MimeType(mimeType2)); return mimeTypeObj1.match(mimeTypeObj2); }

Target:
public static boolean match (final String mimeType1, final String mimeType2) { if (ACCEPT_ALL.equals(mimeType1)) { return true; } if (FileAsset.UNKNOWN_MIME_TYPE.equals(mimeType1) || FileAsset.UNKNOWN_MIME_TYPE.equals(mimeType2)) { return false; } final MimeType mimeTypeObj1 = Sneaky.sneak(() -> new MimeType(mimeType1)); final MimeType mimeTypeObj2 = Sneaky.sneak(() -> new MimeType(mimeType2)); return mimeTypeObj1.match(mimeTypeObj2); }
Source:
public void verifyConnectionTimeoutSettingWorks() throws IOException { String testPathPrefix = IntegrationTestConfigContext.generateBasePath( config, this.getClass().getSimpleName()); Instant start = null; Instant stop; try (MantaClient client = new MantaClient(config)) { start = Instant.now(); client.head(testPathPrefix); } catch (ConnectTimeoutException e) { } catch(InterruptedIOException e){ Assert.assertEquals(e.getClass().getSimpleName(), "ConnectTimeoutException"); Assert.assertTrue(e.getMessage().endsWith("connect timed out"), "ConnectTimeoutException didn't end with expected " + "connection timeout message. Actual exception:\n" + ExceptionUtils.getStackTrace(e)); } finally { stop = Instant.now(); } Duration totalTime = Duration.between(start, stop); if (totalTime.getSeconds() != 1) { String msg = String.format("Expected total connection time duration " + "to be 1 second. Actually [%d] ms", totalTime.toMillis()); Assert.fail(msg); } }

Target:
public void verifyConnectionTimeoutSettingWorks() throws IOException { String testPathPrefix = IntegrationTestConfigContext.generateBasePath( config, this.getClass().getSimpleName()); Instant start = null; Instant stop; try (MantaClient client = new MantaClient(config)) { start = Instant.now(); client.head(testPathPrefix); } catch(InterruptedIOException e){ Assert.assertEquals(e.getClass().getSimpleName(), "ConnectTimeoutException"); Assert.assertTrue(e.getMessage().endsWith("connect timed out"), "ConnectTimeoutException didn't end with expected " + "connection timeout message. Actual exception:\n" + ExceptionUtils.getStackTrace(e)); } finally { stop = Instant.now(); } Duration totalTime = Duration.between(start, stop); if (totalTime.getSeconds() != 1) { String msg = String.format("Expected total connection time duration " + "to be 1 second. Actually [%d] ms", totalTime.toMillis()); Assert.fail(msg); } }
Source:
public void install(TextEditor editor) { this.editor = editor; this.dirtyRegionQueue = new DirtyRegionQueue(); reconcilerDocumentChanged(); editor.addPropertyListener(new PropertyListener() { @Override public void propertyChanged(PartPresenter source, int propId) { } }); }

Target:
public void install(TextEditor editor) { this.editor = editor; this.dirtyRegionQueue = new DirtyRegionQueue(); reconcilerDocumentChanged(); }
Source:
private HttpsServerFake startHttpsServerFake(String statusLine) throws Exception { int port = new Random().nextInt(9 * 1024) + 1024; HttpsServerFake serverFake; if (statusLine == null) { serverFake = new HttpsServerFake(port); } else { serverFake = new HttpsServerFake(port, null, statusLine); } serverFake.start(); return serverFake; }

Target:
private HttpsServerFake startHttpsServerFake(String statusLine) throws Exception { int port = new Random().nextInt(9 * 1024) + 1024; HttpsServerFake serverFake = null; if (statusLine == null) { serverFake = new HttpsServerFake(port); } else { serverFake = new HttpsServerFake(port, null, statusLine); } serverFake.start(); return serverFake; }
Source:
void verifyClosureExpressionBraceStyle(ClosureExpressionContext ctx) { ParseTree left = ParseTreeUtil.getLeftNode(ctx); if (left == null) { return; } Location leftLocation = ListenerUtil.getTokenLocation(ParseTreeUtil.getStopTokenForNode(left)); verifyCodeBlockOpenBraceIsInline(ctx, leftLocation, Messages.CLOSURE); verifyBodyCloseBraceStyle(ctx, Messages.CLOSURE); ParseTree leftSibling = ParseTreeUtil.getLeftSibling(ctx); if (leftSibling != null && (leftSibling instanceof ParenthesizedExpressionContext || leftSibling instanceof PostfixExpressionContext)) { Token leftToken = ((ParserRuleContext) leftSibling).getStop(); verifySingleSpaceBeforeOpenBrace(ctx, leftToken); } }

Target:
void verifyClosureExpressionBraceStyle(ClosureExpressionContext ctx) { ParseTree left = ParseTreeUtil.getLeftNode(ctx); if (left == null) { return; } Location leftLocation = ListenerUtil.getTokenLocation(ParseTreeUtil.getStopTokenForNode(left)); verifyCodeBlockOpenBraceIsInline(ctx, leftLocation, Messages.CLOSURE); verifyClosureCloseBraceStyle(ctx); ParseTree leftSibling = ParseTreeUtil.getLeftSibling(ctx); if (leftSibling != null && (leftSibling instanceof ParenthesizedExpressionContext || leftSibling instanceof PostfixExpressionContext)) { Token leftToken = ((ParserRuleContext) leftSibling).getStop(); verifySingleSpaceBeforeOpenBrace(ctx, leftToken); } }
Source:
public GetDeviceListQueryParameters() { privateStorageType = StorageType.UNKNOWN; checkStatus = false; }

Target:
public GetDeviceListQueryParameters() { this(null, StorageType.UNKNOWN, false, null); }
Source:
public void repeatedlyReassignsUnmarkedResidues() { givenGeneratorHasModulus(3); whenModuliAreRequested(9); whenResidueIsUnmarked(2); whenResidueIsUnmarked(2); whenResidueIsUnmarked(2); whenModuliAreRequested(6); thenOperationSucceeds(); thenResponsesSatisfy(responses -> { assertThat(responses).hasSize(15); assertThat(responses.get(9)).isEqualTo(2); assertThat(responses.get(10)).isEqualTo(2); assertThat(responses.get(11)).isEqualTo(2); assertThat(responses.subList(12, 15)).containsExactlyInAnyOrder(0, 1, 2); }); }

Target:
public void repeatedlyReassignsUnmarkedResidues() { setupGeneratorWithModulus(3); requestResiduesAndAssertEachUsedOnce(3); requestResiduesAndAssertEachUsedOnce(3); requestResiduesAndAssertEachUsedOnce(3); unmarkResidue(2); unmarkResidue(2); unmarkResidue(2); List<Integer> additionalResponses = requestResidues(3); assertThat(additionalResponses).containsExactly(2, 2, 2); requestResiduesAndAssertEachUsedOnce(3); }
Source:
private double[] getPercentages(List<Double> tBreaks, List<Bucket> buckets, int nvalues, int numClasses) { Map<Double, Integer> values = new HashMap<>(); for (Bucket b : buckets) { values.put(b.getMin(), b.getCount()); } ClassPercentagesManager percentagesManager = new ClassPercentagesManager(); return percentagesManager.getPercentages(values, tBreaks, nvalues, numClasses); }

Target:
private double[] getPercentages(List<Double> tBreaks, List<Bucket> buckets, int nvalues, int numClasses) { ClassPercentagesManager percentagesManager = new ClassPercentagesManager(); return percentagesManager.getPercentages(buckets, tBreaks, numClasses); }
Source:
private void revokeManyKeys(Address backup, CountDownCompletableFuture future, Collection<?> keys, int topologyId) { Map<Address, GroupRevocation> revokedKeys = new HashMap<>(); for (Object key : keys) { BiasManager.Revocation revocation = biasManager.startRevokingRemoteBias(key, backup); if (revocation != null) { if (revocation.shouldRevoke()) { for (Address member : revocation.biased()) { revokedKeys.computeIfAbsent(member, m -> new GroupRevocation()).add(key, revocation); } } else { future.increment(); revocation.handleCompose(() -> { CompletableFuture<?> revokeFuture = revokeBiasSync(key, backup, topologyId); if (revokeFuture == null) { future.countDown(); } else { revokeFuture.thenRun(future::countDown); } return CompletableFutures.completedNull(); }); } } } for (Map.Entry<Address, GroupRevocation> mapping : revokedKeys.entrySet()) { future.increment(); sendRevokeBias(Collections.singleton(mapping.getKey()), mapping.getValue().keys, topologyId, null).whenComplete((nil, throwable) -> { if (throwable != null) { mapping.getValue().revocations.forEach(BiasManager.Revocation::fail); future.completeExceptionally(throwable); } else { mapping.getValue().revocations.forEach(BiasManager.Revocation::complete); future.countDown(); } }); } }

Target:
private void revokeManyKeys(Address backup, CountDownCompletableFuture future, Collection<?> keys, int topologyId) { Map<Address, GroupRevocation> revokedKeys = new HashMap<>(); for (Object key : keys) { BiasManager.Revocation revocation = biasManager.startRevokingRemoteBias(key, backup); if (revocation != null) { if (revocation.shouldRevoke()) { for (Address member : revocation.biased()) { revokedKeys.computeIfAbsent(member, m -> new GroupRevocation()).add(key, revocation); } } else { future.increment(); revocation.handleCompose(() -> { CompletableFuture<?> revokeFuture = revokeBiasSync(key, backup, topologyId); revokeFuture.thenRun(future::countDown); return CompletableFutures.completedNull(); }); } } } for (Map.Entry<Address, GroupRevocation> mapping : revokedKeys.entrySet()) { future.increment(); sendRevokeBias(Collections.singleton(mapping.getKey()), mapping.getValue().keys, topologyId, null).whenComplete((nil, throwable) -> { if (throwable != null) { mapping.getValue().revocations.forEach(BiasManager.Revocation::fail); future.completeExceptionally(throwable); } else { mapping.getValue().revocations.forEach(BiasManager.Revocation::complete); future.countDown(); } }); } }
Source:
public ShapelessCraftingRecipe build() { Preconditions.checkState(this.exemplaryResult != null && this.exemplaryResult != ItemStackSnapshot.NONE, "The result is not set."); Preconditions.checkState(!this.ingredients.isEmpty(), "The ingredients are not set."); return new SpongeShapelessCraftingRecipe(exemplaryResult, ingredients); }

Target:
public ShapelessCraftingRecipe build() { checkState(this.exemplaryResult != null && this.exemplaryResult != ItemStackSnapshot.NONE, "The result is not set."); checkState(!this.ingredients.isEmpty(), "The ingredients are not set."); return new SpongeShapelessCraftingRecipe(this.exemplaryResult, this.ingredients); }
Source:
public void baseClassTearDown() { releaseBrowser(); removeTestData(); }

Target:
public void baseClassTearDown() { releaseBrowser(); }
Source:
public void before() throws Throwable { if (Thread.interrupted()) { System.err.println("was interrupted before start"); } if(Functions.isWindows()) { URLConnection aConnection = new File(".").toURI().toURL().openConnection(); origDefaultUseCache = aConnection.getDefaultUseCaches(); aConnection.setDefaultUseCaches(false); } if (Boolean.getBoolean("ignore.random.failures")) { RandomlyFails rf = testDescription.getAnnotation(RandomlyFails.class); if (rf != null) { throw new AssumptionViolatedException("Known to randomly fail: " + rf.value()); } } env = new TestEnvironment(testDescription); env.pin(); recipe(); AbstractProject.WORKSPACE.toString(); User.clear(); try { jenkins = hudson = newHudson(); } catch (Exception e) { Field f = Jenkins.class.getDeclaredField("theInstance"); f.setAccessible(true); f.set(null,null); throw e; } jenkins.setNoUsageStatistics(true); jenkins.setCrumbIssuer(new TestCrumbIssuer()); jenkins.servletContext.setAttribute("app",jenkins); jenkins.servletContext.setAttribute("version","?"); WebAppMain.installExpressionFactory(new ServletContextEvent(jenkins.servletContext)); jenkins.getJDKs().add(new JDK("default",System.getProperty("java.home"))); configureUpdateCenter(); jenkins.getActions().add(this); JenkinsLocationConfiguration.get().setUrl(getURL().toString()); setUpTimeout(); }

Target:
public void before() throws Throwable { if (Thread.interrupted()) { LOGGER.warning("was interrupted before start"); } if(Functions.isWindows()) { URLConnection aConnection = new File(".").toURI().toURL().openConnection(); origDefaultUseCache = aConnection.getDefaultUseCaches(); aConnection.setDefaultUseCaches(false); } if (Boolean.getBoolean("ignore.random.failures")) { RandomlyFails rf = testDescription.getAnnotation(RandomlyFails.class); if (rf != null) { throw new AssumptionViolatedException("Known to randomly fail: " + rf.value()); } } env = new TestEnvironment(testDescription); env.pin(); recipe(); AbstractProject.WORKSPACE.toString(); User.clear(); try { jenkins = hudson = newHudson(); } catch (Exception e) { Field f = Jenkins.class.getDeclaredField("theInstance"); f.setAccessible(true); f.set(null,null); throw e; } jenkins.setNoUsageStatistics(true); jenkins.setCrumbIssuer(new TestCrumbIssuer()); jenkins.servletContext.setAttribute("app",jenkins); jenkins.servletContext.setAttribute("version","?"); WebAppMain.installExpressionFactory(new ServletContextEvent(jenkins.servletContext)); jenkins.getJDKs().add(new JDK("default",System.getProperty("java.home"))); configureUpdateCenter(); jenkins.getActions().add(this); JenkinsLocationConfiguration.get().setUrl(getURL().toString()); setUpTimeout(); }
Source:
public void testIPv4CountryOnly() throws Exception { morphline = buildCommand("ip", "GeoLite2-Country.mmdb"); final Record record = new Record(); final String ip = "128.101.101.101"; record.put("ip", ip); processAndVerifySuccess(record, true, false, 6252001, null); }

Target:
public void testIPv4CountryOnly() throws Exception { morphline = buildCommand("ip", "GeoLite2-Country.mmdb"); final Record record = new Record(); final String ip = "128.101.101.101"; record.put("ip", ip); processAndVerifySuccess2(record, true, false, 6252001, null); }
Source:
private static String processNumericType(String mgrsPart) { String[] numericParts = mgrsPart.split("[ ]+"); StringBuilder numericBuilder = new StringBuilder(); Runnable appendZero = () -> numericBuilder.append("0"); if (numericParts.length == 1) { String eastingAndNorthing = numericParts[0]; LOGGER.trace( "NUMERIC had no white space; easting and northing will be parsed as one [{}]", mgrsPart, eastingAndNorthing); if (eastingAndNorthing.length() >= MIN_EASTING_NORTHING_LENGTH) { return eastingAndNorthing; } int numberOfZerosNeeded = MIN_EASTING_NORTHING_LENGTH - eastingAndNorthing.length(); repeat(numberOfZerosNeeded, appendZero); return numericBuilder.append(eastingAndNorthing).toString(); } else { String easting = numericParts[0]; String northing = numericParts[1]; LOGGER.trace( "NUMERIC had white space; easting = and northing = [{}]", mgrsPart, easting, northing); if (easting.length() == MIN_EASTING_LENGTH) { return easting + northing; } int numberOfZerosNeeded = MIN_EASTING_LENGTH - easting.length(); repeat(numberOfZerosNeeded, appendZero); return numericBuilder.append(easting).append(northing).toString(); } }

Target:
private static String processNumericType(String mgrsPart) { final String[] numericParts = mgrsPart.split("(\\W)+"); if (numericParts.length >= 3 || numericParts.length == 0) { throw new IllegalArgumentException( "The mgrs part provided is not a valid NUMERIC type: " + mgrsPart); } if (numericParts.length == 2) { return assemble(numericParts[0], numericParts[1]); } String eastingAndNorthing = numericParts[0]; if (eastingAndNorthing.length() % 2 > 0) { eastingAndNorthing = eastingAndNorthing.substring(0, eastingAndNorthing.length() - 1); } final int halfway = eastingAndNorthing.length() / 2; final String easting = eastingAndNorthing.substring(0, halfway); final String northing = eastingAndNorthing.substring(halfway); return assemble(easting, northing); }
Source:
public static void main(String[] args) { if (args.length == 0) { System.err.println("No message id specified"); System.exit(1); } String messageId = args[0]; List<String> scopes = new ArrayList<String>(); scopes.add(YouTubeScopes.YOUTUBE_FORCE_SSL); scopes.add(YouTubeScopes.YOUTUBE); try { Credential credential = Auth.authorize(scopes, "deletelivechatmessage"); youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, credential) .setApplicationName("youtube-cmdline-deletechatmessages-sample").build(); String liveChatId = GetLiveChatId.getLiveChatId( youtube, args.length == 2 ? args[1] : null); if (liveChatId != null) { System.out.println("Live chat id: " + liveChatId); } else { System.err.println("Unable to find a live chat id"); System.exit(1); } YouTube.LiveChatMessages.Delete liveChatDelete = youtube.liveChatMessages().delete(messageId); liveChatDelete.execute(); System.out.println("Deleted message id " + messageId); } catch (GoogleJsonResponseException e) { System.err .println("GoogleJsonResponseException code: " + e.getDetails().getCode() + " : " + e.getDetails().getMessage()); e.printStackTrace(); } catch (IOException e) { System.err.println("IOException: " + e.getMessage()); e.printStackTrace(); } catch (Throwable t) { System.err.println("Throwable: " + t.getMessage()); t.printStackTrace(); } }

Target:
public static void main(String[] args) { if (args.length == 0) { System.err.println("No message id specified"); System.exit(1); } String messageId = args[0]; List<String> scopes = Lists.newArrayList(YouTubeScopes.YOUTUBE_FORCE_SSL); try { Credential credential = Auth.authorize(scopes, "deletelivechatmessage"); youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, credential) .setApplicationName("youtube-cmdline-deletechatmessages-sample").build(); YouTube.LiveChatMessages.Delete liveChatDelete = youtube.liveChatMessages().delete(messageId); liveChatDelete.execute(); System.out.println("Deleted message id " + messageId); } catch (GoogleJsonResponseException e) { System.err .println("GoogleJsonResponseException code: " + e.getDetails().getCode() + " : " + e.getDetails().getMessage()); e.printStackTrace(); } catch (IOException e) { System.err.println("IOException: " + e.getMessage()); e.printStackTrace(); } catch (Throwable t) { System.err.println("Throwable: " + t.getMessage()); t.printStackTrace(); } }
Source:
public void shouldCreateAndDropIndex() { String indexName = "test_index"; Mono<Boolean> indexExists = reactorClient.indexExists(null, args.namespace, indexName); StepVerifier.create(indexExists) .expectNext(false) .verifyComplete(); Mono<Void> created = reactorClient.createIndex(null, args.namespace, args.set, indexName, indexName, IndexType.NUMERIC, IndexCollectionType.DEFAULT); StepVerifier.create(created) .verifyComplete(); indexExists = reactorClient.indexExists(null, args.namespace, indexName); StepVerifier.create(indexExists) .expectNext(true) .verifyComplete(); Mono<Void> dropped = reactorClient.dropIndex(null, args.namespace, args.set, indexName); StepVerifier.create(dropped) .verifyComplete(); indexExists = reactorClient.indexExists(null, args.namespace, indexName); StepVerifier.create(indexExists) .expectNext(false) .verifyComplete(); }

Target:
public void shouldCreateAndDropIndex() { Mono<Void> created = reactorClient.createIndex(null, args.namespace, args.set, indexName, args.getBinName(binName), IndexType.NUMERIC, IndexCollectionType.DEFAULT); StepVerifier.create(created) .verifyComplete(); Mono<Void> dropped = reactorClient.dropIndex(null, args.namespace, args.set, indexName); StepVerifier.create(dropped) .verifyComplete(); }
Source:
private synchronized String mergeItem(Item item) { String id; try(DataDomainManager dm = new DataDomainManager()){ if (anyCycles(item)) { throw new CycleIntroductionException(); } List<Item> children = item.getChildren(); List<Item> replaceList = new LinkedList<>(); if (children != null) { for (Item child : children) { replaceList.add(load(child.getId())); } item.setChildren(replaceList); } em.merge(item); id = item.getId(); if(dm.load(id) != null){ List<Item> domainsToDelete = findVisibleAncestors(item); for(Item toDelete : domainsToDelete){ dm.regenerateDomainForItem(toDelete); } } dm.close(); } catch (Exception e){ log.error("Failed to save item: " + item.getId() + " | Error: " + e.getMessage()); id = null; } return id; }

Target:
private synchronized String mergeItem(Item item) { String id; try(DataDomainManager dm = new DataDomainManager()){ if (anyCycles(item)) { throw new CycleIntroductionException(); } List<Item> children = item.getChildren(); List<Item> replaceList = new LinkedList<>(); if (children != null) { for (Item child : children) { replaceList.add(load(child.getId())); } item.setChildren(replaceList); } em.merge(item); id = item.getId(); if(dm.load(id) != null){ List<Item> domainsToDelete = findVisibleAncestors(item); for(Item toDelete : domainsToDelete){ dm.regenerateDomainForItem(toDelete); } } } catch (Exception e){ log.error("Failed to save item: " + item.getId() + " | Error: " + e.getMessage()); id = null; } return id; }
Source:
public void before() { when(this.environment.jersey()).thenReturn(this.jerseyEnvironment); }

Target:
public void before() { when(environment.jersey()).thenReturn(jerseyEnvironment); }
Source:
public RecConstructDeclaration(String fieldName, ValueType type, IExpr iExpr, FileLocation loc) { super(fieldName, iExpr, loc); this.type = type; System.out.println(); System.out.println("target/corewyvernIL/decl/RecConstructDeclaration"); System.out.println("RecConstructDeclaration Called"); System.out.println(" RecConstruct Name: " + fieldName); System.out.println(" RecConstruct Type: " + type); System.out.println(" RecConstruct Body: " + iExpr); System.out.println(" RecConstruct Location: " + loc); System.out.println(); }

Target:
public RecConstructDeclaration(String fieldName, ValueType type, IExpr iExpr, FileLocation loc) { super(fieldName, iExpr, loc); this.type = type; }
Source:
public void query( IndexProgressor.NodeValueClient cursor, IndexOrder indexOrder, IndexQuery... predicates ) { if ( predicates.length != 1 ) { throw new IllegalArgumentException( "Only single property temporal indexes are supported." ); } IndexQuery predicate = predicates[0]; if ( predicate instanceof ExistsPredicate ) { BridgingIndexProgressor multiProgressor = new BridgingIndexProgressor( cursor, descriptor.schema().getPropertyIds() ); cursor.initialize( descriptor, multiProgressor, predicates ); for ( NativeSchemaIndexReader reader : this ) { reader.query( multiProgressor, indexOrder, predicates ); } } else { if ( validPredicate( predicate ) ) { CoordinateReferenceSystem crs; if ( predicate instanceof IndexQuery.ExactPredicate ) { crs = ((PointValue) ((IndexQuery.ExactPredicate) predicate).value()).getCoordinateReferenceSystem(); } else if ( predicate instanceof IndexQuery.GeometryRangePredicate ) { crs = ((IndexQuery.GeometryRangePredicate) predicate).crs(); } else { throw new IllegalArgumentException( "Wrong type of predicate, couldn't get CoordinateReferenceSystem" ); } SpatialIndexPartReader<SpatialSchemaKey,NativeSchemaValue> part = uncheckedSelect( crs ); if ( part != null ) { part.query( cursor, indexOrder, predicates ); } else { cursor.initialize( descriptor, IndexProgressor.EMPTY, predicates ); } } else { cursor.initialize( descriptor, IndexProgressor.EMPTY, predicates ); } } }

Target:
public void query( IndexProgressor.NodeValueClient cursor, IndexOrder indexOrder, IndexQuery... predicates ) { if ( predicates.length != 1 ) { throw new IllegalArgumentException( "Only single property spatial indexes are supported." ); } IndexQuery predicate = predicates[0]; if ( predicate instanceof ExistsPredicate ) { loadAll(); BridgingIndexProgressor multiProgressor = new BridgingIndexProgressor( cursor, descriptor.schema().getPropertyIds() ); cursor.initialize( descriptor, multiProgressor, predicates ); for ( NativeSchemaIndexReader reader : this ) { reader.query( multiProgressor, indexOrder, predicates ); } } else { if ( validPredicate( predicate ) ) { CoordinateReferenceSystem crs; if ( predicate instanceof IndexQuery.ExactPredicate ) { crs = ((PointValue) ((IndexQuery.ExactPredicate) predicate).value()).getCoordinateReferenceSystem(); } else if ( predicate instanceof IndexQuery.GeometryRangePredicate ) { crs = ((IndexQuery.GeometryRangePredicate) predicate).crs(); } else { throw new IllegalArgumentException( "Wrong type of predicate, couldn't get CoordinateReferenceSystem" ); } SpatialIndexPartReader<SpatialSchemaKey,NativeSchemaValue> part = uncheckedSelect( crs ); if ( part != null ) { part.query( cursor, indexOrder, predicates ); } else { cursor.initialize( descriptor, IndexProgressor.EMPTY, predicates ); } } else { cursor.initialize( descriptor, IndexProgressor.EMPTY, predicates ); } } }
Source:
EhcacheActiveEntity(ServiceRegistry services, byte[] config) { this.identity = ClusteredEhcacheIdentity.deserialize(config); this.services = services; this.responseFactory = new EhcacheEntityResponseFactory(); this.clientCommunicator = services.getService(new CommunicatorServiceConfiguration()); OffHeapResources offHeapResources = services.getService(new OffHeapResourcesServiceConfiguration()); if(offHeapResources == null) { this.offHeapResourceIdentifiers = Collections.EMPTY_SET; } else { this.offHeapResourceIdentifiers = offHeapResources.getAllIdentifiers(); } }

Target:
EhcacheActiveEntity(ServiceRegistry services, byte[] config) { this.identity = ClusteredEhcacheIdentity.deserialize(config); this.services = services; this.responseFactory = new EhcacheEntityResponseFactory(); this.clientCommunicator = services.getService(new CommunicatorServiceConfiguration()); OffHeapResources offHeapResources = services.getService(new OffHeapResourcesServiceConfiguration()); if (offHeapResources == null) { this.offHeapResourceIdentifiers = Collections.emptySet(); } else { this.offHeapResourceIdentifiers = offHeapResources.getAllIdentifiers(); } }
Source:
public void addInput(Page page) { checkState(aggregationWork == null, "Operator has unfinished work"); checkState(!finishing, "Operator is already finishing"); requireNonNull(page, "page is null"); inputProcessed = true; if (aggregationBuilder == null) { if (step.isOutputPartial() || !spillEnabled) { aggregationBuilder = new InMemoryHashAggregationBuilder( accumulatorFactories, step, expectedGroups, groupByTypes, groupByChannels, hashChannel, operatorContext, maxPartialMemory, joinCompiler, true); } else { aggregationBuilder = new SpillableHashAggregationBuilder( accumulatorFactories, step, expectedGroups, groupByTypes, groupByChannels, hashChannel, operatorContext, memoryLimitForMerge, memoryLimitForMergeWithMemory, spillerFactory, joinCompiler); } } else { checkState(!aggregationBuilder.isFull(), "Aggregation buffer is full"); } aggregationWork = aggregationBuilder.processPage(page); if (aggregationWork.process()) { aggregationWork = null; } aggregationBuilder.updateMemory(); }

Target:
public void addInput(Page page) { checkState(unfinishedWork == null, "Operator has unfinished work"); checkState(!finishing, "Operator is already finishing"); requireNonNull(page, "page is null"); inputProcessed = true; if (aggregationBuilder == null) { if (step.isOutputPartial() || !spillEnabled) { aggregationBuilder = new InMemoryHashAggregationBuilder( accumulatorFactories, step, expectedGroups, groupByTypes, groupByChannels, hashChannel, operatorContext, maxPartialMemory, joinCompiler, true); } else { aggregationBuilder = new SpillableHashAggregationBuilder( accumulatorFactories, step, expectedGroups, groupByTypes, groupByChannels, hashChannel, operatorContext, memoryLimitForMerge, memoryLimitForMergeWithMemory, spillerFactory, joinCompiler); } } else { checkState(!aggregationBuilder.isFull(), "Aggregation buffer is full"); } unfinishedWork = aggregationBuilder.processPage(page); if (unfinishedWork.process()) { unfinishedWork = null; } aggregationBuilder.updateMemory(); }
Source:
public void eachNonZero(VectorProcedure procedure) { for (int i = 0; i < cardinality; i++) { if (Math.abs(values[i])>Vectors.EPS) procedure.apply(indices[i], values[i]); } }

Target:
public void eachNonZero(VectorProcedure procedure) { for (int i = 0; i < cardinality; i++) { procedure.apply(indices[i], values[i]); } }
Source:
private void validateExpectedColumnIndices(List<Integer> expectedColumnIndices, List<PinotColumnHandle> expectedColumnHandles) { int numValid = 0; Set<Integer> uniqueIndices = new HashSet<>(); for (int i : expectedColumnIndices) { assertTrue(i == -1 || i >= 0 && i < expectedColumnHandles.size()); if (i >= 0) { ++numValid; uniqueIndices.add(i); } } assertEquals(numValid, uniqueIndices.size()); }

Target:
private void validateExpectedColumnIndices(List<Integer> expectedColumnIndices, List<PinotColumnHandle> expectedColumnHandles) { int numValid = 0; Set<Integer> uniqueIndices = new HashSet<>(); for (int expectedColumnIndex : expectedColumnIndices) { assertTrue(expectedColumnIndex == -1 || expectedColumnIndex >= 0 && expectedColumnIndex < expectedColumnHandles.size()); if (expectedColumnIndex >= 0) { numValid++; uniqueIndices.add(expectedColumnIndex); } } assertEquals(numValid, uniqueIndices.size()); }
Source:
public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { if (args.length > 0 && args[0].contains("lock") && user.isAuthorized("essentials.jump.lock")) { if (user.isFlyClickJump()) { user.setRightClickJump(false); user.sendMessage("Flying wizard mode disabled"); } else { user.setRightClickJump(true); user.sendMessage("Enabling flying wizard mode"); } return; } Location loc; final Location cloc = user.getLocation(); try { loc = LocationUtil.getTarget(user.getBase()); loc.setYaw(cloc.getYaw()); loc.setPitch(cloc.getPitch()); loc.setY(loc.getY() + 1); } catch (NullPointerException ex) { throw new Exception(tl("jumpError"), ex); } final Trade charge = new Trade(this.getName(), ess); charge.isAffordableFor(user); if(Bukkit.getWorld(user.getWorld().getUID()).getWorldBorder().isInside(loc) || user.isAuthorized("essentials.jump.pastWorldBorder")) { user.getTeleport().teleport(loc, charge, TeleportCause.COMMAND); }else { user.sendMessage("You can not jump outside of the world border"); } throw new NoChargeException(); }

Target:
public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { if (args.length > 0 && args[0].contains("lock") && user.isAuthorized("essentials.jump.lock")) { if (user.isFlyClickJump()) { user.setRightClickJump(false); user.sendMessage("Flying wizard mode disabled"); } else { user.setRightClickJump(true); user.sendMessage("Enabling flying wizard mode"); } return; } Location loc; final Location cloc = user.getLocation(); try { loc = LocationUtil.getTarget(user.getBase()); loc.setYaw(cloc.getYaw()); loc.setPitch(cloc.getPitch()); loc.setY(loc.getY() + 1); } catch (NullPointerException ex) { throw new Exception(tl("jumpError"), ex); } final Trade charge = new Trade(this.getName(), ess); charge.isAffordableFor(user); if (Bukkit.getWorld(user.getWorld().getUID()).getWorldBorder().isInside(loc) || user.isAuthorized("essentials.jump.border")) { user.getTeleport().teleport(loc, charge, TeleportCause.COMMAND); } else { user.sendMessage(tl("jumpBorder", user.getName())); } throw new NoChargeException(); }
Source:
public static ImmutableSet<String> getArrayMemberTypes(final Ds3ApiSpec spec) { final ImmutableSet.Builder<String> allArrayMemberTypesBuilder = ImmutableSet.builder(); for (final Ds3Type ds3TypeEntry : spec.getTypes().values()) { ds3TypeEntry.getElements().stream() .filter(element -> element.getType().equalsIgnoreCase("array")) .forEach(element -> allArrayMemberTypesBuilder.add(StructHelper.getResponseTypeName(element.getComponentType()))); } return allArrayMemberTypesBuilder.build(); }

Target:
public static ImmutableSet<String> getArrayMemberTypes(final Ds3ApiSpec spec) { return spec.getTypes().values().stream() .flatMap(entry -> entry.getElements().stream()) .filter(element -> element.getType().equalsIgnoreCase("array")) .map(element -> StructHelper.getResponseTypeName(element.getComponentType())) .collect(GuavaCollectors.immutableSet()); }
Source:
public MinioClient(String endpoint, int port, String accessKey, String secretKey, boolean secure) throws InvalidEndpointException, InvalidPortException { this(endpoint, port, accessKey, secretKey, "", secure); }

Target:
public MinioClient(String endpoint, int port, String accessKey, String secretKey, boolean secure) throws InvalidEndpointException, InvalidPortException { this(endpoint, port, accessKey, secretKey, null, secure); }
Source:
public void testIdUniqueness() throws Exception { Class clazz = ProtoStreamTypeIds.class; Field[] fields = clazz.getFields(); Set<Integer> messageIds = new HashSet<>(); Set<Integer> lowerBounds = new HashSet<>(); for (Field f : fields) { if (f.getName().endsWith("_LOWER_BOUND")) lowerBounds.add(f.getInt(clazz)); else messageIds.add(f.getInt(clazz)); } assertTrue(messageIds.size() > 0); assertTrue(lowerBounds.size() > 0); assertEquals(fields.length - lowerBounds.size(), messageIds.size()); assertEquals(fields.length - messageIds.size(), lowerBounds.size()); }

Target:
public void testIdUniqueness() throws Exception { Class clazz = ProtoStreamTypeIds.class; Field[] fields = clazz.getFields(); Set<Integer> messageIds = new HashSet<>(); Set<Integer> lowerBounds = new HashSet<>(); for (Field f : fields) { if (f.getName().endsWith("_LOWER_BOUND")) assertTrue(lowerBounds.add(f.getInt(clazz))); else assertTrue(messageIds.add(f.getInt(clazz))); } assertTrue(messageIds.size() > 0); assertTrue(lowerBounds.size() > 0); assertEquals(fields.length - lowerBounds.size(), messageIds.size()); assertEquals(fields.length - messageIds.size(), lowerBounds.size()); }
Source:
public void testJsonEmptyDiskDescription() throws IOException { String jsonDescription = null; jsonDescription = ImagesHandler.getJsonDiskDescription("DiskAlias", ""); assertTrue("Should be map of disk alias and disk description", jsonDescription.equals("{\"DiskDescription\":\"\",\"DiskAlias\":\"DiskAlias\"}")); }

Target:
public void testJsonEmptyDiskDescription() throws IOException { String jsonDescription = ImagesHandler.getJsonDiskDescription("DiskAlias", ""); assertTrue("Should be map of disk alias and disk description", jsonDescription.equals("{\"DiskDescription\":\"\",\"DiskAlias\":\"DiskAlias\"}")); }
Source:
private void assertTags(Node element) { Node tagsElement = element.getFirstChild(); if (tagsElement != null) { assertThat(tagsElement.getNodeName(), is("mgm:tags")); assertThat(tagsElement.getAttributes().getLength(), is(0)); Node tag1 = tagsElement.getFirstChild(); assertThat(tag1, is(notNullValue())); assertThat(tag1.getFirstChild(), is(notNullValue())); assertThat(tag1.getFirstChild().getNodeValue(), is("tag1")); Node tag2 = tagsElement.getLastChild(); assertThat(tag2, is(notNullValue())); assertThat(tag2.getFirstChild(), is(notNullValue())); assertThat(tag2.getFirstChild().getNodeValue(), is("tag2")); } }

Target:
private void assertTags(Node element) { Node tagsElement = element.getFirstChild(); assertThat(tagsElement.getNodeName(), is("mgm:tags")); assertThat(tagsElement.getAttributes().getLength(), is(0)); Node tag1 = tagsElement.getFirstChild(); assertThat(tag1, is(notNullValue())); assertThat(tag1.getFirstChild(), is(notNullValue())); assertThat(tag1.getFirstChild().getNodeValue(), is("tag1")); Node tag2 = tagsElement.getLastChild(); assertThat(tag2, is(notNullValue())); assertThat(tag2.getFirstChild(), is(notNullValue())); assertThat(tag2.getFirstChild().getNodeValue(), is("tag2")); }