auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public Builder setTitle(String title) { this.title = title; ORDER.put(++orderIndex,"title"); return this; }

Target:
public Builder setTitle(String title) { this.title = title; return this; }
Source:
public void testDisallowedOperations() { Disk disk = new DiskImage(); for (Map.Entry<VdcActionType, List<DiskContentType>> entry : DiskOperationsValidator.allowedCommandsOnTypes.entrySet()) { EnumSet<DiskContentType> allowedTypes = EnumSet.copyOf(entry.getValue()); EnumSet<DiskContentType> disallowedTypes = EnumSet.complementOf(allowedTypes); if (allowedTypes.isEmpty()) { continue; } disk.setContentType(disallowedTypes.iterator().next()); DiskOperationsValidator validator = new DiskOperationsValidator(disk); assertThat(validator.isOperationAllowedOnDisk(entry.getKey()), failsWith(EngineMessage.ACTION_TYPE_FAILED_DISK_CONTENT_TYPE_NOT_SUPPORTED_FOR_OPERATION, String.format("$diskContentType %s", disk.getContentType()))); } }

Target:
public void testDisallowedOperations() { Disk disk = new DiskImage(); for (Map.Entry<VdcActionType, List<DiskContentType>> entry : DiskOperationsValidator.allowedCommandsOnTypes.entrySet()) { EnumSet<DiskContentType> allowedTypes = EnumSet.copyOf(entry.getValue()); EnumSet<DiskContentType> disallowedTypes = EnumSet.complementOf(allowedTypes); disk.setContentType(disallowedTypes.iterator().next()); DiskOperationsValidator validator = new DiskOperationsValidator(disk); assertThat(validator.isOperationAllowedOnDisk(entry.getKey()), failsWith(EngineMessage.ACTION_TYPE_FAILED_DISK_CONTENT_TYPE_NOT_SUPPORTED_FOR_OPERATION, String.format("$diskContentType %s", disk.getContentType()))); } }
Source:
public void stop(final StopContext context) { if (!blockStart) { try { synchronized (waitObject) { log.info("BlockService blocking in start"); waitObject.wait(blockTime); } context.complete(); } catch (InterruptedException e) { log.info("BlockService interrupted"); Thread.currentThread().interrupt(); throw new RuntimeException(e); } } else { synchronized (waitObject) { log.info("BlockService Stopping"); waitObject.notifyAll(); } } }

Target:
public void stop(final StopContext context) { if (!blockStart) { try { synchronized (waitObject) { log.info("BlockService blocking in stop"); waitObject.wait(blockTime); } context.complete(); } catch (InterruptedException e) { log.info("BlockService interrupted"); Thread.currentThread().interrupt(); throw new RuntimeException(e); } } else { synchronized (waitObject) { log.info("BlockService Stopping"); waitObject.notifyAll(); } } }
Source:
public void testOnJoinChannelButtonClicked() throws Exception { assertThat(instance.tabPane.getTabs(), is(empty())); Tab tab = new Tab(); tab.setId(TEST_CHANNEL_NAME); when(channelTabController.getRoot()).thenReturn(tab); when(userService.getUsername()).thenReturn(TEST_USER_NAME); doAnswer(invocation -> { MapChangeListener.Change<? extends String, ? extends Channel> change = mock(MapChangeListener.Change.class); when(change.wasAdded()).thenReturn(true); doReturn(new Channel(invocation.getArgument(0))).when(change.getValueAdded()); channelsListener.getValue().onChanged(change); return null; }).when(chatService).joinChannel(anyString()); instance.channelNameTextField.setText(TEST_CHANNEL_NAME); instance.onJoinChannelButtonClicked(); verify(chatService).joinChannel(TEST_CHANNEL_NAME); verify(chatService).addUsersListener(eq(TEST_CHANNEL_NAME), onUsersListenerCaptor.capture()); MapChangeListener.Change<? extends String, ? extends ChatChannelUser> change = mock(MapChangeListener.Change.class); when(change.wasAdded()).thenReturn(true); doReturn(new ChatChannelUser(TEST_USER_NAME, null, false)).when(change.getValueAdded()); onUsersListenerCaptor.getValue().onChanged(change); CountDownLatch tabAddedLatch = new CountDownLatch(1); instance.tabPane.getTabs().addListener((InvalidationListener) observable -> tabAddedLatch.countDown()); tabAddedLatch.await(2, TimeUnit.SECONDS); assertThat(instance.tabPane.getTabs(), hasSize(1)); assertThat(instance.tabPane.getTabs().get(0).getId(), is(TEST_CHANNEL_NAME)); }

Target:
public void testOnJoinChannelButtonClicked() throws Exception { assertThat(instance.tabPane.getTabs(), is(empty())); Tab tab = new Tab(); tab.setId(TEST_CHANNEL_NAME); when(channelTabController.getRoot()).thenReturn(tab); when(userService.getUsername()).thenReturn(TEST_USER_NAME); doAnswer(invocation -> { MapChangeListener.Change<? extends String, ? extends Channel> change = mock(MapChangeListener.Change.class); when(change.wasAdded()).thenReturn(true); doReturn(new Channel(invocation.getArgument(0))).when(change).getValueAdded(); channelsListener.getValue().onChanged(change); return null; }).when(chatService).joinChannel(anyString()); instance.channelNameTextField.setText(TEST_CHANNEL_NAME); instance.onJoinChannelButtonClicked(); verify(chatService).joinChannel(TEST_CHANNEL_NAME); verify(chatService).addUsersListener(eq(TEST_CHANNEL_NAME), onUsersListenerCaptor.capture()); MapChangeListener.Change<? extends String, ? extends ChatChannelUser> change = mock(MapChangeListener.Change.class); when(change.wasAdded()).thenReturn(true); doReturn(new ChatChannelUser(TEST_USER_NAME, null, false)).when(change).getValueAdded(); onUsersListenerCaptor.getValue().onChanged(change); CountDownLatch tabAddedLatch = new CountDownLatch(1); instance.tabPane.getTabs().addListener((InvalidationListener) observable -> tabAddedLatch.countDown()); tabAddedLatch.await(2, TimeUnit.SECONDS); assertThat(instance.tabPane.getTabs(), hasSize(1)); assertThat(instance.tabPane.getTabs().get(0).getId(), is(TEST_CHANNEL_NAME)); }
Source:
public boolean isCompactionCandidate(long retentionPeriod) { return isDeleted() && deletionTime <= (System.currentTimeMillis() - retentionPeriod); }

Target:
public boolean isCompactionCandidate(long retentionPeriod) { return (isDeleted() && deletionTime <= (System.currentTimeMillis() - retentionPeriod)) || (isExpired() && expirationTime <= (System.currentTimeMillis() - retentionPeriod)); }
Source:
private List<Property> readProperties(Map<String, ExecutableElement> properties) { List<Property> values = new LinkedList<Property>(); for (Map.Entry<String, ExecutableElement> entry : properties.entrySet()) { values.add(new Property(entry.getKey(), entry.getValue())); } return values; }

Target:
private ImmutableList<Property> readProperties(Map<String, ExecutableElement> properties) { ImmutableList.Builder<Property> values = ImmutableList.builder(); for (Map.Entry<String, ExecutableElement> entry : properties.entrySet()) { values.add(new Property(entry.getKey(), entry.getValue())); } return values.build(); }
Source:
public Quote getBuyQuote(Money amount) throws IOException, CoinbaseException { String qtyParam; if(amount.getCurrencyUnit().getCode().equals("BTC")) qtyParam = "qty"; else qtyParam = "native_qty"; URL buyPriceUrl; try { buyPriceUrl = new URL( _baseApiUrl, "prices/buy?" + qtyParam +"=" + URLEncoder.encode(amount.getAmount().toPlainString(), "UTF-8") ); } catch (MalformedURLException ex) { throw new AssertionError(ex); } return deserialize(doHttp(buyPriceUrl, "GET", null), Quote.class); }

Target:
public Quote getBuyQuote(Money amount) throws IOException, CoinbaseException { String qtyParam; if(amount.getCurrencyUnit().getCode().equals("BTC")) { qtyParam = "qty"; } else { qtyParam = "native_qty"; } URL buyPriceUrl; try { buyPriceUrl = new URL( _baseApiUrl, "prices/buy?" + qtyParam +"=" + URLEncoder.encode(amount.getAmount().toPlainString(), "UTF-8") ); } catch (MalformedURLException ex) { throw new AssertionError(ex); } return deserialize(doHttp(buyPriceUrl, "GET", null), Quote.class); }
Source:
public void testBadSyntax() throws Exception { InputStream badRDF = openTestDatasetStream(BAD_RDF_FILE_NAME); validator.checkSyntax(badRDF, BASE_URI, RDF_FORMAT); badRDF.close(); }

Target:
public void testBadSyntax() throws Exception { try (InputStream badRDF = openTestDatasetStream(BAD_RDF_FILE_NAME)) { validator.checkSyntax(badRDF, BASE_URI, RDF_FORMAT); } }
Source:
private List<File> getFiles(Repository repo, final RevCommit unfilteredCommit) throws MissingObjectException, IOException, IncorrectObjectTypeException, CorruptObjectException { List<File> files = new ArrayList<File>(); TreeWalk tw = new TreeWalk(repo); tw.setRecursive(true); final PlotWalk walk = new PlotWalk(repo); try { for (RevCommit parent : unfilteredCommit.getParents()) walk.parseBody(parent); FileDiff[] diffs = FileDiff.compute(repo, tw, unfilteredCommit, TreeFilter.ALL); if (diffs != null && diffs.length > 0) { File repoDir = repo.getDirectory(); String repoPath = repoDir.getParentFile().getAbsolutePath(); for (FileDiff d : diffs) { String path = d.getPath(); File f = new File(repoPath + File.separator + path); files.add(f); } } } finally { tw.release(); walk.release(); } return files; }

Target:
private List<File> getFiles(Repository repo, final RevCommit unfilteredCommit) throws MissingObjectException, IOException, IncorrectObjectTypeException, CorruptObjectException { List<File> files = new ArrayList<File>(); TreeWalk tw = new TreeWalk(repo); tw.setRecursive(true); final RevWalk walk = new RevWalk(repo); try { for (RevCommit parent : unfilteredCommit.getParents()) walk.parseBody(parent); FileDiff[] diffs = FileDiff.compute(repo, tw, unfilteredCommit, TreeFilter.ALL); if (diffs != null && diffs.length > 0) { File repoDir = repo.getDirectory(); String repoPath = repoDir.getParentFile().getAbsolutePath(); for (FileDiff d : diffs) { String path = d.getPath(); File f = new File(repoPath + File.separator + path); files.add(f); } } } finally { tw.release(); walk.release(); } return files; }
Source:
public TypedElementBoundsRenderer(VControl vElement, ViewModelContext viewContext, ReportService reportService, EMFFormsDatabinding emfFormsDatabinding, EMFFormsLabelProvider emfFormsLabelProvider, VTViewTemplateProvider vtViewTemplateProvider) { super(vElement, viewContext, reportService, emfFormsDatabinding, emfFormsLabelProvider, vtViewTemplateProvider); dbc = new EMFDataBindingContext(); }

Target:
public TypedElementBoundsRenderer(VControl vElement, ViewModelContext viewContext, ReportService reportService, EMFFormsDatabinding emfFormsDatabinding, EMFFormsLabelProvider emfFormsLabelProvider, VTViewTemplateProvider vtViewTemplateProvider) { super(vElement, viewContext, reportService, emfFormsDatabinding, emfFormsLabelProvider, vtViewTemplateProvider); }
Source:
public void fillAllFields(User newUser) { fillLoginNameField(newUser.getLogin()); fillFirstNameField(newUser.getFirstName()); fillLastNameField(newUser.getLastName()); fillPasswordField(newUser.getPassword()); fillConfirmPasswordField(newUser.getPassword() + "_"); fillEmailField(newUser.getEmail()); Select regionSelect = new Select(driver.findElement(NewUserPageLocators.REGION_SELECT.getBy())); regionSelect.selectByVisibleText(newUser.getRegionName()); driver.findElement(By.xpath( String.format(NewUserPageLocators.ROLE_SELECT, newUser.getRoleName()))).click(); }

Target:
public void fillAllFields(User newUser) { fillLoginNameField(newUser.getLogin()); fillFirstNameField(newUser.getFirstName()); fillLastNameField(newUser.getLastName()); fillPasswordField(newUser.getPassword()); fillConfirmPasswordField(newUser.getPassword()); fillEmailField(newUser.getEmail()); selectRegion(Regions.valueOf(newUser.getRegionName().toUpperCase())); clickRoleRadioButton(Roles.valueOf(newUser.getRoleName().toUpperCase())); }
Source:
public IdpResponse build() { String providerId = mUser.getProviderId(); if (!AuthUI.SUPPORTED_PROVIDERS.contains(providerId)) { throw new IllegalStateException("Unknown provider: " + providerId); } if ((providerId.equals(GoogleAuthProvider.PROVIDER_ID) || providerId.equals(FacebookAuthProvider.PROVIDER_ID) || providerId.equals(TwitterAuthProvider.PROVIDER_ID)) && TextUtils.isEmpty(mToken)) { throw new IllegalStateException( "Token cannot be null when using a non-email provider."); } if (providerId.equals(TwitterAuthProvider.PROVIDER_ID) && TextUtils.isEmpty(mSecret)) { throw new IllegalStateException( "Secret cannot be null when using the Twitter provider."); } return new IdpResponse(mUser, mToken, mSecret, null); }

Target:
public IdpResponse build() { String providerId = mUser.getProviderId(); if (!AuthUI.SUPPORTED_PROVIDERS.contains(providerId)) { throw new IllegalStateException("Unknown provider: " + providerId); } if (AuthUI.SOCIAL_PROVIDERS.contains(providerId) && TextUtils.isEmpty(mToken)) { throw new IllegalStateException( "Token cannot be null when using a non-email provider."); } if (providerId.equals(TwitterAuthProvider.PROVIDER_ID) && TextUtils.isEmpty(mSecret)) { throw new IllegalStateException( "Secret cannot be null when using the Twitter provider."); } return new IdpResponse(mUser, mToken, mSecret); }
Source:
protected static NettyHttpService.Builder createBaseNettyHttpServiceBuilder() { return NettyHttpService.builder("test") .setHttpHandlers(new TestHandler()) .setHttpChunkLimit(75 * 1024) .setExceptionHandler(EXCEPTION_HANDLER) .setAuthHandler(new AuthHandler() { @Override public boolean isAuthenticated(HttpRequest request) { return request.headers().contains(HttpHeaderNames.AUTHORIZATION.toString()); } @Override public boolean hasRoles(HttpRequest request, String[] roles) { for (String role : roles) { if (request.headers().contains(HttpHeaderNames.AUTHORIZATION)) { if (!request.headers().get(HttpHeaderNames.AUTHORIZATION.toString()).contains(role)) { return false; } } else { return false; } } return true; } @Override public String getWWWAuthenticateHeader() { return "roles list"; } }) .setChannelPipelineModifier(new ChannelPipelineModifier() { @Override public void modify(ChannelPipeline pipeline) { pipeline.addAfter("codec", "testhandler", new TestChannelHandler()); } }); }

Target:
protected static NettyHttpService.Builder createBaseNettyHttpServiceBuilder() { return NettyHttpService.builder("test") .setHttpHandlers(new TestHandler()) .setHttpChunkLimit(75 * 1024) .setExceptionHandler(EXCEPTION_HANDLER) .setAuthHandler(new AuthHandler() { @Override public boolean isAuthenticated(HttpRequest request) { return request.headers().contains(HttpHeaderNames.AUTHORIZATION); } @Override public boolean hasRoles(HttpRequest request, String[] roles) { for (String role : roles) { if (request.headers().contains(HttpHeaderNames.AUTHORIZATION)) { if (!request.headers().get(HttpHeaderNames.AUTHORIZATION).contains(role)) { return false; } } else { return false; } } return true; } @Override public String getWWWAuthenticateHeader() { return "roles list"; } }) .setChannelPipelineModifier(new ChannelPipelineModifier() { @Override public void modify(ChannelPipeline pipeline) { pipeline.addAfter("codec", "testhandler", new TestChannelHandler()); } }); }
Source:
public void zeroSizeContentTest() throws Exception { NettyRequest nettyRequest = createNettyRequest(HttpMethod.POST, "/", null); List<HttpContent> httpContents = new ArrayList<HttpContent>(1); httpContents.add(new DefaultLastHttpContent()); nettyRequest.addContent(httpContents.get(0)); assertEquals("Reference count is not as expected", 2, httpContents.get(0).refCnt()); ByteBufferAsyncWritableChannel writeChannel = new ByteBufferAsyncWritableChannel(); ReadIntoCallback callback = new ReadIntoCallback(); Future<Long> future = nettyRequest.readInto(writeChannel, callback); assertEquals("There should be no content", 0, writeChannel.getNextChunk().remaining()); writeChannel.resolveOldestChunk(null); closeRequestAndValidate(nettyRequest); writeChannel.close(); verifyRefCnts(httpContents); if (callback.exception != null) { throw callback.exception; } long futureBytesRead = future.get(); assertEquals("Total bytes read does not match (callback)", 0, callback.bytesRead); assertEquals("Total bytes read does not match (future)", 0, futureBytesRead); }

Target:
public void zeroSizeContentTest() throws Exception { NettyRequest nettyRequest = createNettyRequest(HttpMethod.POST, "/", null); HttpContent httpContent = new DefaultLastHttpContent(); nettyRequest.addContent(httpContent); assertEquals("Reference count is not as expected", 2, httpContent.refCnt()); ByteBufferAsyncWritableChannel writeChannel = new ByteBufferAsyncWritableChannel(); ReadIntoCallback callback = new ReadIntoCallback(); Future<Long> future = nettyRequest.readInto(writeChannel, callback); assertEquals("There should be no content", 0, writeChannel.getNextChunk().remaining()); writeChannel.resolveOldestChunk(null); closeRequestAndValidate(nettyRequest); writeChannel.close(); assertEquals("Reference count of http content has changed", 1, httpContent.refCnt()); if (callback.exception != null) { throw callback.exception; } long futureBytesRead = future.get(); assertEquals("Total bytes read does not match (callback)", 0, callback.bytesRead); assertEquals("Total bytes read does not match (future)", 0, futureBytesRead); }
Source:
public void internalStop() throws Exception { server.stop(); if (webContexts != null) { File tmpdir = null; StringBuilder strBuilder = new StringBuilder(); boolean found = false; for (WebAppContext context : webContexts) { tmpdir = context.getTempDirectory(); if (tmpdir != null && tmpdir.exists() && !context.isPersistTempDirectory()) { FileUtil.deleteDirectory(tmpdir); if (tmpdir.exists()) { ActiveMQWebLogger.LOGGER.tmpFileNotDeleted(tmpdir); strBuilder.append(tmpdir); strBuilder.append(","); found = true; } } } if (found) { String artemisHome = System.getProperty("artemis.home"); String bootJar = artemisHome + File.separator + "lib" + File.separator + "artemis-boot.jar"; String[] command = {"java", "-cp", bootJar, "org.apache.activemq.artemis.boot.WebTmpCleaner", strBuilder.toString()}; ProcessBuilder pb = new ProcessBuilder(command); pb.start(); } webContexts.clear(); } }

Target:
public void internalStop() throws Exception { server.stop(); if (webContexts != null) { File tmpdir = null; StringBuilder strBuilder = new StringBuilder(); boolean found = false; for (WebAppContext context : webContexts) { tmpdir = context.getTempDirectory(); if (tmpdir != null && tmpdir.exists() && !context.isPersistTempDirectory()) { FileUtil.deleteDirectory(tmpdir); if (tmpdir.exists()) { ActiveMQWebLogger.LOGGER.tmpFileNotDeleted(tmpdir); strBuilder.append(tmpdir); strBuilder.append(","); found = true; } } } if (found) { String bootJar = artemisHome + File.separator + "lib" + File.separator + "artemis-boot.jar"; String[] command = {"java", "-cp", bootJar, "org.apache.activemq.artemis.boot.WebTmpCleaner", strBuilder.toString()}; ProcessBuilder pb = new ProcessBuilder(command); pb.start(); } webContexts.clear(); } }
Source:
void generateGeneralReport(GeneralReportModule generalReportModule) throws IOException { if (generalReportModule != null) { reportPathFormatString = createReportDirectory(generalReportModule, reportPathFormatString); setupProgressPanel(generalReportModule); ReportWorker worker = new ReportWorker(() -> { generalReportModule.generateReport(reportPathFormatString, progressPanel); }); worker.execute(); displayProgressPanel(); } }

Target:
void generateGeneralReport(GeneralReportModule generalReportModule) throws IOException { if (generalReportModule != null) { String reportDir = createReportDirectory(generalReportModule); setupProgressPanel(generalReportModule, reportDir); ReportWorker worker = new ReportWorker(() -> { generalReportModule.generateReport(reportDir, progressPanel); }); worker.execute(); displayProgressPanel(); } }
Source:
public boolean isOpen() { if (this.delegate instanceof AutorecoveringConnection && !this.delegate.isOpen()) { throw new AmqpException("Auto recovery connection is not currently open"); } return this.delegate != null && (this.delegate.isOpen()); }

Target:
public boolean isOpen() { if (!this.explicitlyClosed && this.delegate instanceof AutorecoveringConnection && !this.delegate.isOpen()) { throw new AutoRecoverConnectionNotCurrentlyOpenException("Auto recovery connection is not currently open"); } return this.delegate != null && (this.delegate.isOpen()); }
Source:
public String getReplPolicy() { if (dbName == null) { return null; } else if (tableName == null) { return dbName.toLowerCase() + ".*"; } else { return dbName.toLowerCase() + "." + tableName.toLowerCase(); } }

Target:
public String getReplPolicy() { if ((dbName == null) || (dbName.isEmpty())) { return null; } else if ((tableName == null) || (tableName.isEmpty())) { return dbName.toLowerCase() + ".*"; } else { return dbName.toLowerCase() + "." + tableName.toLowerCase(); } }
Source:
public Builder setSuffix(String suffix) throws IllegalArgumentException { format = DateTimeFormatter.ofPattern(suffix.replaceAll("[\\/:*?\"<>|]", "_")).withZone(timeZone); final int len = suffix.length(); period = Period.NEVER; for (int i = 0; i < len; i ++) { switch (suffix.charAt(i)) { case 'y': period = min(period, Period.YEAR); break; case 'M': period = min(period, Period.MONTH); break; case 'w': case 'W': period = min(period, Period.WEEK); break; case 'D': case 'd': case 'F': case 'E': period = min(period, Period.DAY); break; case 'a': period = min(period, Period.HALF_DAY); break; case 'H': case 'k': case 'K': case 'h': period = min(period, Period.HOUR); break; case 'm': period = min(period, Period.MINUTE); break; case '\'': while (suffix.charAt(++i) != '\''){} break; case 's': case 'S': throw audit.rotatingBySecondUnsupported(suffix); } } return this; }

Target:
public Builder setSuffix(String suffix) throws IllegalArgumentException { format = DateTimeFormatter.ofPattern(suffix).withZone(timeZone); final int len = suffix.length(); period = Period.NEVER; for (int i = 0; i < len; i ++) { switch (suffix.charAt(i)) { case 'y': period = min(period, Period.YEAR); break; case 'M': period = min(period, Period.MONTH); break; case 'w': case 'W': period = min(period, Period.WEEK); break; case 'D': case 'd': case 'F': case 'E': period = min(period, Period.DAY); break; case 'a': period = min(period, Period.HALF_DAY); break; case 'H': case 'k': case 'K': case 'h': period = min(period, Period.HOUR); break; case 'm': period = min(period, Period.MINUTE); break; case '\'': while (suffix.charAt(++i) != '\''){} break; case 's': case 'S': throw audit.rotatingBySecondUnsupported(suffix); } } return this; }
Source:
public InputColumn<?>[] getUpdatedInputColumns(InputColumn<?>[] allInputColumns, boolean exceptionOnMissing) { final String[] newInputColumnNames = getInputColumnNames(); final List<InputColumn<?>> newInputColumns = new ArrayList<>(newInputColumnNames.length); for (final String newInputColumnName : newInputColumnNames) { final InputColumn<?> updatedInputColumn = updateInputColumn(allInputColumns, newInputColumnName); if (updatedInputColumn == null) { if(exceptionOnMissing) { final List<String> names = Arrays.stream(allInputColumns).map(InputColumn::getName).collect(Collectors.toList()); throw new IllegalStateException( "Column '" + newInputColumnName + "' not found. Available columns: " + names); } } else { newInputColumns.add(updatedInputColumn); } } return newInputColumns.toArray(new InputColumn[newInputColumns.size()]); }

Target:
public InputColumn<?>[] getUpdatedInputColumns(InputColumn<?>[] allInputColumns, boolean exceptionOnMissing) { final String[] newInputColumnNames = getInputColumnNames(); final List<InputColumn<?>> newInputColumns = new ArrayList<>(newInputColumnNames.length); for (final String newInputColumnName : newInputColumnNames) { final InputColumn<?> updatedInputColumn = findInputColumn(allInputColumns, newInputColumnName); if (updatedInputColumn == null) { if (exceptionOnMissing) { final List<String> names = Arrays.stream(allInputColumns).map(InputColumn::getName).collect(Collectors.toList()); throw new CoalesceUnitMissingColumnException(this, newInputColumnName, "Column '" + newInputColumnName + "' not found. Available columns: " + names); } } else { newInputColumns.add(updatedInputColumn); } } return newInputColumns.toArray(new InputColumn[newInputColumns.size()]); }
Source:
private void initializeOutputSchema() { List<Schema.Field> fields = new ArrayList<>(); fields.add(Schema.Field.of(conf.getKeyField(), Schema.of(Schema.Type.STRING))); for (String outputField : outputFields) { fields.add(Schema.Field.of(outputField, Schema.nullableOf(Schema.of(Schema.Type.STRING)))); } outputSchema = Schema.recordOf("group.key.schema", fields); }

Target:
private Schema initializeOutputSchema() { List<Schema.Field> fields = new ArrayList<>(); fields.add(Schema.Field.of(conf.getKeyField(), Schema.of(Schema.Type.STRING))); for (String outputField : conf.getOutputSchemaFields()) { fields.add(Schema.Field.of(outputField, Schema.nullableOf(Schema.of(Schema.Type.STRING)))); } return Schema.recordOf("output.schema", fields); }
Source:
public void replaceInput(int ordinalInParent, RelNode p) { if (ordinalInParent == 0) { Preconditions.checkArgument( p instanceof DruidRel, "RelNode[%s] is not a DruidRel", p.getClass().getCanonicalName() ); this.left = (DruidRel<?>) p; } else if (ordinalInParent == 1) { this.right = p; } else { throw new IndexOutOfBoundsException(StringUtils.format("Invalid ordinalInParent[%s]", ordinalInParent)); } }

Target:
public void replaceInput(int ordinalInParent, RelNode p) { if (ordinalInParent != 0) { throw new IndexOutOfBoundsException(StringUtils.format("Invalid ordinalInParent[%s]", ordinalInParent)); } this.right = p; }
Source:
public static boolean isIdentifierKeyword(CharSequence text) { int pos = 0; int valueLength = text.length(); if(valueLength == 0) { return false; } boolean keyword = false; switch (text.charAt(pos++)) { case '$': if (valueLength == 1) return false; while (pos < valueLength) { char c = text.charAt(pos++); if (! isDecimalDigit(c)) return false; } keyword = true; break; case 'f': if (valueLength == 5 && text.charAt(pos++) == 'a' && text.charAt(pos++) == 'l' && text.charAt(pos++) == 's' && text.charAt(pos++) == 'e' ) { keyword = true; } break; case 'n': if (valueLength == 4 && text.charAt(pos++) == 'u' && text.charAt(pos++) == 'l' && text.charAt(pos++) == 'l' ) { keyword = true; } else if (valueLength == 3 && text.charAt(pos++) == 'a' && text.charAt(pos++) == 'n' ) { keyword = true; } break; case 't': if (valueLength == 4 && text.charAt(pos++) == 'r' && text.charAt(pos++) == 'u' && text.charAt(pos++) == 'e' ) { keyword = true; } break; } return keyword; }

Target:
public static boolean isIdentifierKeyword(CharSequence text) { int pos = 0; int valuelen = text.length(); if(valuelen == 0) { return false; } boolean keyword = false; switch (text.charAt(pos++)) { case '$': if (valuelen == 1) return false; while (pos < valuelen) { char c = text.charAt(pos++); if (! isDecimalDigit(c)) return false; } return true; case 'f': if (valuelen == 5 && text.charAt(pos++) == 'a' && text.charAt(pos++) == 'l' && text.charAt(pos++) == 's' && text.charAt(pos++) == 'e' ) { keyword = true; } break; case 'n': if (valuelen == 4 && text.charAt(pos++) == 'u' && text.charAt(pos++) == 'l' && text.charAt(pos++) == 'l' ) { keyword = true; } else if (valuelen == 3 && text.charAt(pos++) == 'a' && text.charAt(pos++) == 'n' ) { keyword = true; } break; case 't': if (valuelen == 4 && text.charAt(pos++) == 'r' && text.charAt(pos++) == 'u' && text.charAt(pos++) == 'e' ) { keyword = true; } break; } return keyword; }
Source:
public static File checkJarFileForApplicationMode(Configuration configuration) { final List<File> pipelineJars = configuration.get(PipelineOptions.JARS).stream().map( FunctionUtils.uncheckedFunction( uri -> { final URI jarURI = PackagedProgramUtils.resolveURI(uri); if (jarURI.getScheme().equals("local") && jarURI.isAbsolute()) { return new File(jarURI.getPath()); } throw new IllegalArgumentException("Only support local schema for application mode. \"local\" means the " + "jar is located in the image, not Flink client. e.g. local:/ }) ).collect(Collectors.toList()); Preconditions.checkArgument(pipelineJars.size() == 1, "Should only have one jar"); return pipelineJars.get(0); }

Target:
public static List<File> checkJarFileForApplicationMode(Configuration configuration) { return configuration.get(PipelineOptions.JARS).stream().map( FunctionUtils.uncheckedFunction( uri -> { final URI jarURI = PackagedProgramUtils.resolveURI(uri); if (jarURI.getScheme().equals("local") && jarURI.isAbsolute()) { return new File(jarURI.getPath()); } throw new IllegalArgumentException("Only \"local\" is supported as schema for application mode." + " This assumes that the jar is located in the image, not the Flink client." + " An example of such path is: local:/ }) ).collect(Collectors.toList()); }
Source:
private File searchEnclosingProjectInWorkDir(File startFolder, String workingTreeRootPath) { File projectFile = null; File currentPath = startFolder; while (currentPath.toString().startsWith(workingTreeRootPath)) { projectFile = new File( currentPath.toString() + File.separator + ".project"); if (projectFile.isFile()) { break; } projectFile = null; currentPath = currentPath.getParentFile(); } return projectFile; }

Target:
private File searchEnclosingProjectInWorkDir(File startFolder, String workingTreeRootPath) { File projectFile = null; File currentPath = startFolder; while (currentPath.toString().startsWith(workingTreeRootPath)) { projectFile = new File( currentPath.toString() + File.separator + ".project"); if (projectFile.isFile()) break; projectFile = null; currentPath = currentPath.getParentFile(); } return projectFile; }
Source:
DropwizardTestResourceConfig(ResourceTestJerseyConfiguration configuration) { super(); property(TestProperties.CONTAINER_PORT, "0"); if (configuration.registerDefaultExceptionMappers) { register(new ExceptionMapperBinder(false)); } for (Class<?> provider : configuration.providers) { register(provider); } property(ServerProperties.RESPONSE_SET_STATUS_OVER_SEND_ERROR, "true"); for (Map.Entry<String, Object> property : configuration.properties.entrySet()) { property(property.getKey(), property.getValue()); } register(new JacksonFeature(configuration.mapper)); register(new HibernateValidationBinder(configuration.validator)); for (Supplier<?> singleton : configuration.singletons) { register(singleton.get().getClass()); } }

Target:
DropwizardTestResourceConfig(ResourceTestJerseyConfiguration configuration) { super(); property(TestProperties.CONTAINER_PORT, "0"); if (configuration.registerDefaultExceptionMappers) { register(new ExceptionMapperBinder(false)); } for (Class<?> provider : configuration.providers) { register(provider); } property(ServerProperties.RESPONSE_SET_STATUS_OVER_SEND_ERROR, "true"); for (Map.Entry<String, Object> property : configuration.properties.entrySet()) { property(property.getKey(), property.getValue()); } register(new JacksonFeature(configuration.mapper)); register(new HibernateValidationBinder(configuration.validator)); for (Supplier<?> singleton : configuration.singletons) { register(singleton.get()); } }
Source:
public void configure(HttpSecurity http) throws Exception { String[] unsecuredResources = new String[] { "/login", "/security/**", "/services/rest/login", "/services/rest/logout" }; http .authenticationProvider(this.authenticationProvider) .authorizeRequests().antMatchers(unsecuredResources).permitAll().anyRequest().authenticated().and() .csrf().requireCsrfProtectionMatcher(new CsrfRequestMatcher()).and() .formLogin().successHandler(new SimpleUrlAuthenticationSuccessHandler()).defaultSuccessUrl("/") .failureUrl("/login.html?error").loginProcessingUrl("/j_spring_security_login").usernameParameter("username") .passwordParameter("password").and() .logout().logoutSuccessUrl("/login.html").and() .addFilterBefore(basicAuthenticationFilter(), BasicAuthenticationFilter.class) .addFilterAfter(getSimpleRestAuthenticationFilter(), BasicAuthenticationFilter.class) .addFilterAfter(getSimpleRestLogoutFilter(), LogoutFilter.class); if (this.corsEnabled) { http.addFilterBefore(getCorsFilter(), CsrfFilter.class); } }

Target:
public void configure(HttpSecurity http) throws Exception { String[] unsecuredResources = new String[] { "/login", "/security/**", "/services/rest/login", "/services/rest/logout" }; http .authenticationProvider(this.authenticationProvider) .authorizeRequests().antMatchers(unsecuredResources).permitAll().anyRequest().authenticated().and() .csrf().requireCsrfProtectionMatcher(new CsrfRequestMatcher()).and() .formLogin().successHandler(new SimpleUrlAuthenticationSuccessHandler()).defaultSuccessUrl("/") .failureUrl("/login.html?error").loginProcessingUrl("/j_spring_security_login").usernameParameter("username") .passwordParameter("password").and() .logout().logoutSuccessUrl("/login.html").and() .addFilterAfter(getSimpleRestAuthenticationFilter(), BasicAuthenticationFilter.class) .addFilterAfter(getSimpleRestLogoutFilter(), LogoutFilter.class); if (this.corsEnabled) { http.addFilterBefore(getCorsFilter(), CsrfFilter.class); } }
Source:
NatsMessage(String subject, String replyTo, ByteBuffer data, boolean utf8mode) { this.subject = subject; this.replyTo = replyTo; this.data = data; if (utf8mode) { byte[] subjectBytes = subject.getBytes(StandardCharsets.UTF_8); byte[] replyBytes = (replyTo != null) ? replyTo.getBytes(StandardCharsets.UTF_8) : null; int replySize = (replyBytes != null) ? replyBytes.length + 1 : 0; this.protocolBytes = ByteBuffer.allocate(4 + subjectBytes.length + 1 + replySize + 2); protocolBytes.put((byte)'P').put((byte)'U').put((byte)'B').put((byte)' '); protocolBytes.put(subjectBytes); protocolBytes.put((byte)' '); if (replyTo != null) { protocolBytes.put(replyBytes); protocolBytes.put((byte)' '); } protocolBytes.put(String.valueOf(data.limit()).getBytes()); } else { int size = (data != null) ? data.limit() : 0; int sizeLength = fastIntLength(size); int len = 4 + subject.length() + 1 + sizeLength; if (replyTo != null) { len += replyTo.length() + 1; } this.protocolBytes = ByteBuffer.allocate(len); protocolBytes.put((byte)'P').put((byte)'U').put((byte)'B').put((byte)' '); protocolBytes.put(subject.getBytes()); protocolBytes.put((byte)' '); if (replyTo != null) { protocolBytes.put(replyTo.getBytes()); protocolBytes.put((byte)' '); } if (size > 0) { int base = protocolBytes.limit(); for (int i = size; i > 0; i /= 10) { base--; protocolBytes.put(base, (byte)(i % 10 + 0x30)); } } else { protocolBytes.put((byte)0x30); } } protocolBytes.clear(); }

Target:
NatsMessage(String subject, String replyTo, ByteBuffer data, boolean utf8mode) { this.subject = subject; this.replyTo = replyTo; this.data = data; Charset charset; int size = (data != null) ? data.limit() : 0; int len = fastIntLength(size) + 4; if (replyTo != null) { if (utf8mode) { len += fastUtf8Length(replyTo) + 1; } else { len += replyTo.length() + 1; } } if (utf8mode) { len += fastUtf8Length(subject) + 1; charset = StandardCharsets.UTF_8; } else { len += subject.length() + 1; charset = StandardCharsets.US_ASCII; } this.protocolBytes = ByteBuffer.allocate(len); protocolBytes.put((byte)'P').put((byte)'U').put((byte)'B').put((byte)' '); protocolBytes.put(subject.getBytes(charset)); protocolBytes.put((byte)' '); if (replyTo != null) { protocolBytes.put(replyTo.getBytes(charset)); protocolBytes.put((byte)' '); } if (size > 0) { int base = protocolBytes.limit(); for (int i = size; i > 0; i /= 10) { base--; protocolBytes.put(base, (byte)(i % 10 + (byte)'0')); } } else { protocolBytes.put((byte)'0'); } protocolBytes.clear(); }
Source:
synchronized SQLiteDatabase getReadableDbWithRetries() { int count = 0; while(true) { try { return getReadableDatabase(); } catch (SQLiteCantOpenDatabaseException t) { if (++count >= DB_OPEN_RETRY_MAX) throw t; SystemClock.sleep(count * DB_OPEN_RETRY_BACKOFF); } } }

Target:
synchronized SQLiteDatabase getReadableDbWithRetries() { int count = 0; while(true) { try { return getReadableDatabase(); } catch (SQLiteCantOpenDatabaseException e) { if (++count >= DB_OPEN_RETRY_MAX) throw e; SystemClock.sleep(count * DB_OPEN_RETRY_BACKOFF); } } }
Source:
private QueryObservable createQuery(Func1<Set<String>, Boolean> tableFilter, String sql, String... args) { if (transactions.get() != null) { throw new IllegalStateException("Cannot create observable query in transaction. " + "Use query() for a query inside a transaction."); } DatabaseQuery query = new DatabaseQuery(tableFilter, sql, args); final Observable<Query> queryObservable = triggers .filter(tableFilter) .map(query) .onBackpressureLatest() .startWith(query) .compose(queryTransformer) .observeOn(scheduler) .onBackpressureLatest() .doOnSubscribe(ensureNotInTransaction); return new QueryObservable(new Observable.OnSubscribe<Query>() { @Override public void call(Subscriber<? super Query> subscriber) { queryObservable.unsafeSubscribe(subscriber); } }); }

Target:
private QueryObservable createQuery(Func1<Set<String>, Boolean> tableFilter, String sql, String... args) { if (transactions.get() != null) { throw new IllegalStateException("Cannot create observable query in transaction. " + "Use query() for a query inside a transaction."); } DatabaseQuery query = new DatabaseQuery(tableFilter, sql, args); final Observable<Query> queryObservable = triggers .filter(tableFilter) .map(query) .onBackpressureLatest() .startWith(query) .observeOn(scheduler) .compose(queryTransformer) .onBackpressureLatest() .doOnSubscribe(ensureNotInTransaction); return new QueryObservable(new Observable.OnSubscribe<Query>() { @Override public void call(Subscriber<? super Query> subscriber) { queryObservable.unsafeSubscribe(subscriber); } }); }
Source:
public boolean is(Kind... kinds) { return Arrays.asList(kinds).contains(getKind()); }

Target:
public boolean is(Kind... kinds) { Kind treeKind = getKind(); for (Kind kindIter : kinds) { if (treeKind == kindIter) { return true; } } return false; }
Source:
private static ChefService initChefService(final String client, final String validator) { try { Properties chefConfig = new Properties(); chefConfig.put(ChefProperties.CHEF_VALIDATOR_NAME, validator); chefConfig .put(ChefProperties.CHEF_VALIDATOR_CREDENTIAL, credentialForClient(validator)); ContextBuilder builder = ContextBuilder.newBuilder(new ChefApiMetadata()) .credentials(client, credentialForClient(client)) .modules(ImmutableSet.<Module> of(new SLF4JLoggingModule())) .overrides(chefConfig); System.out.printf(">> initializing %s%n", builder.getApiMetadata()); ChefContext context = (ChefContext)builder.build(); return context.getChefService(); } catch (Exception e) { System.err.println("error reading private key " + e.getMessage()); System.exit(1); return null; } }

Target:
private static ChefService initChefService(final String client, final String validator) { try { Properties chefConfig = new Properties(); chefConfig.put(ChefProperties.CHEF_VALIDATOR_NAME, validator); chefConfig .put(ChefProperties.CHEF_VALIDATOR_CREDENTIAL, credentialForClient(validator)); ContextBuilder builder = ContextBuilder.newBuilder(new ChefApiMetadata()) .credentials(client, credentialForClient(client)) .modules(ImmutableSet.<Module>of(new SLF4JLoggingModule())) .overrides(chefConfig); System.out.printf(">> initializing %s%n", builder.getApiMetadata()); ChefContext context = builder.buildView(ChefContext.class); return context.getChefService(); } catch (Exception e) { System.err.println("error reading private key " + e.getMessage()); System.exit(1); return null; } }
Source:
public static LintResult fromJsonObject(JSONObject json) { String name = (String) json.get("name"); String code = (String) json.get("code"); String severity = (String) json.get("severity"); String path = (String) json.get("path"); Integer line = (Integer) json.opt("line"); Integer charPosition = (Integer) json.opt("char"); String description = (String) json.get("description"); return new LintResult(name, code, severity, path, line, charPosition, description); }

Target:
public static LintResult fromJsonObject(JSONObject json) { String name = (String) json.get("name"); String code = (String) json.get("code"); String severity = (String) json.get("severity"); String path = (String) json.get("path"); Integer line = (Integer) json.opt("line"); Integer charPosition = (Integer) json.opt("char"); String description = (String) json.opt("description"); return new LintResult(name, code, severity, path, line, charPosition, description); }
Source:
public void testTimeout() throws Exception { final MockRenderedReportBuilder builder = Mockito.mock(MockRenderedReportBuilder.class); final Config config = CHROME_RENDERER_CONFIG; _wireMock.givenThat( get(urlEqualTo("/")) .willReturn(aResponse() .withBody("here are some bytes") .withFixedDelay(1000) ) ); final HtmlReportFormat format = new HtmlReportFormat.Builder().build(); final HtmlScreenshotRenderer renderer = new HtmlScreenshotRenderer(config, new ScheduledThreadPoolExecutor(1)); final WebPageReportSource source = TestBeanFactory.createWebPageReportSourceBuilder() .setUri(URI.create("http://localhost:" + _wireMock.port())) .build(); final CompletionStage<MockRenderedReportBuilder> stage = renderer.render( source, format, new TimeRange(Instant.EPOCH, Instant.EPOCH), builder, Duration.ofMillis(500) ); boolean cancelled = false; try { stage.toCompletableFuture().get(1, TimeUnit.SECONDS); } catch (final CancellationException exception) { cancelled = true; } Assert.assertTrue("render().get() should have thrown a CancellationException", cancelled); }

Target:
public void testTimeout() throws Exception { final MockRenderedReportBuilder builder = Mockito.mock(MockRenderedReportBuilder.class); final Config config = CHROME_RENDERER_CONFIG; _wireMock.givenThat( get(urlEqualTo("/")) .willReturn(aResponse() .withBody("here are some bytes") .withFixedDelay(1000) ) ); final HtmlReportFormat format = new HtmlReportFormat.Builder().build(); final HtmlScreenshotRenderer renderer = new HtmlScreenshotRenderer(config, new ScheduledThreadPoolExecutor(1)); final WebPageReportSource source = TestBeanFactory.createWebPageReportSourceBuilder() .setUri(URI.create("http://localhost:" + _wireMock.port())) .build(); final CompletionStage<MockRenderedReportBuilder> stage = renderer.render( source, format, new TimeRange(Instant.EPOCH, Instant.EPOCH), builder, Duration.ofMillis(500) ); boolean cancelled = false; try { stage.toCompletableFuture().get(); } catch (final CancellationException exception) { cancelled = true; } Assert.assertTrue("render().get() should have thrown a CancellationException", cancelled); }
Source:
private void checkDoNotMockAnnotation(Class<?> typeToMock, MockCreationSettings<?> creationSettings) { ArrayList<Class<?>> unmockableTypes = new ArrayList<>( creationSettings.getExtraInterfaces()); Class<?> mockTypeToCheck = typeToMock; while (mockTypeToCheck != null && mockTypeToCheck != Object.class) { unmockableTypes.add(mockTypeToCheck); Class<?>[] interfaces = mockTypeToCheck.getInterfaces(); if (interfaces != null) { unmockableTypes.addAll(Arrays.asList(interfaces)); } mockTypeToCheck = mockTypeToCheck.getSuperclass(); } if (unmockableTypes.stream().anyMatch(clazz -> clazz.isAnnotationPresent(DoNotMock.class))) { throw new DoNotMockException(creationSettings.getTypeToMock() + " is annotated with @DoNoMock and can't be mocked."); } }

Target:
private void checkDoNotMockAnnotation(Class<?> typeToMock, MockCreationSettings<?> creationSettings) { checkDoNotMockAnnotationForType(typeToMock); for (Class<?> aClass : creationSettings.getExtraInterfaces()) { checkDoNotMockAnnotationForType(aClass); } }
Source:
public void htlExpression(Expression expression, Node node) { if (node instanceof TagNode && ((TagNode) node).getAttributes().iterator().next().getName().equals("data-sly-list")) { createViolation(node.getStartLinePosition(), RULE_MESSAGE); } }

Target:
public void htlExpression(Expression expression, Node node) { if (node instanceof TagNode && (isSlyList((TagNode)node) || isSlyRepeat((TagNode)node))) { createViolation(node.getStartLinePosition(), RULE_MESSAGE); } }
Source:
public static StringBuilder read(String fileName) throws IOException { try (FileReader reader = new FileReader(fileName)) { StringBuilder result = read(reader); return result; } }

Target:
public static StringBuffer read(String fileName) throws IOException { try (FileReader reader = new FileReader(fileName)) { StringBuffer result = read(reader); return result; } }
Source:
public String buildImage(final BuildImageParams params, final ProgressMonitor progressMonitor) throws IOException, InterruptedException { if (params.getRemote() != null) { DockerConnection dockerConnection = connectionFactory.openConnection(dockerDaemonUri) .query("remote", params.getRemote()); return buildImage(dockerConnection, params, progressMonitor); } else { final File tar = Files.createTempFile(null, ".tar").toFile(); try { File[] files = new File[params.getFiles().size()]; files = params.getFiles().toArray(files); createTarArchive(tar, files); try (InputStream tarInput = new FileInputStream(tar)) { DockerConnection dockerConnection = connectionFactory.openConnection(dockerDaemonUri) .header("Content-Type", "application/x-compressed-tar") .header("Content-Length", tar.length()) .entity(tarInput); return buildImage(dockerConnection, params, progressMonitor); } } finally { FileCleaner.addFile(tar); } } }

Target:
public String buildImage(final BuildImageParams params, final ProgressMonitor progressMonitor) throws IOException, InterruptedException { if (params.getRemote() != null) { DockerConnection dockerConnection = connectionFactory.openConnection(dockerDaemonUri) .query("remote", params.getRemote()); return buildImage(dockerConnection, params, progressMonitor); } final File tar = Files.createTempFile(null, ".tar").toFile(); try { File[] files = new File[params.getFiles().size()]; files = params.getFiles().toArray(files); createTarArchive(tar, files); try (InputStream tarInput = new FileInputStream(tar)) { DockerConnection dockerConnection = connectionFactory.openConnection(dockerDaemonUri) .header("Content-Type", "application/x-compressed-tar") .header("Content-Length", tar.length()) .entity(tarInput); return buildImage(dockerConnection, params, progressMonitor); } } finally { FileCleaner.addFile(tar); } }
Source:
public boolean getAllowUntrustedCertificate() { return vsConnectionConfig != null && vsConnectionConfig.getAllowUntrustedCertificate(); }

Target:
public boolean getAllowUntrustedCertificate() { return vsConnectionConfig != null ? vsConnectionConfig.getAllowUntrustedCertificate() : false; }
Source:
private Class<?> classFromInternalName(String name) { try { return Class.forName(name.replace('/', '.'), true, classLoader); } catch (ClassNotFoundException e) { throw new IllegalStateException(e); } }

Target:
private Class<?> classFromInternalName(String name) { try { return Class.forName(name.replace('/', '.'), false, classLoader); } catch (ClassNotFoundException e) { throw new IllegalStateException(e); } }
Source:
synchronized void publish() { if (publishedFullRegistry == null) { throw new RuntimeException("Cannot write directly to main registry"); } CapabilityRegistry published = publishedFullRegistry; published.capabilities.clear(); published.capabilities.putAll(capabilities); published.possibleCapabilities.clear(); published.possibleCapabilities.putAll(possibleCapabilities); published.requirements.clear(); published.requirements.putAll(requirements); published.runtimeOnlyRequirements.clear(); published.runtimeOnlyRequirements.putAll(runtimeOnlyRequirements); }

Target:
void publish() { assert publishedFullRegistry != null : "Cannot write directly to main registry"; writeLock.lock(); try { if (!modified) { return; } publishedFullRegistry.writeLock.lock(); try { CapabilityRegistry published = publishedFullRegistry; published.capabilities.clear(); published.capabilities.putAll(capabilities); published.possibleCapabilities.clear(); published.possibleCapabilities.putAll(possibleCapabilities); published.requirements.clear(); published.requirements.putAll(requirements); published.runtimeOnlyRequirements.clear(); published.runtimeOnlyRequirements.putAll(runtimeOnlyRequirements); modified = false; } finally { publishedFullRegistry.writeLock.unlock(); } } finally { writeLock.unlock(); } }