auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void setAndCreateWebViewsStyleSheet(String styleSheetUrl) { Path cacheDirectory = preferencesService.getCacheDirectory(); noCatch(() -> { Files.createDirectories(cacheDirectory); Path newTempStyleSheet = Files.createTempFile(cacheDirectory, "style-webview", ".css"); Files.delete(newTempStyleSheet); try (InputStream inputStream = new URL(styleSheetUrl).openStream()) { Files.copy(inputStream, newTempStyleSheet); } String newStyleSheetUrl = newTempStyleSheet.toUri().toURL().toString(); webViews.forEach(webView -> Platform.runLater(() -> webView.getEngine().setUserStyleSheetLocation(newStyleSheetUrl))); logger.debug("{} created and applied to all web views", newTempStyleSheet.getFileName()); if (currentTempStyleSheet != null) { Files.delete(currentTempStyleSheet); } currentTempStyleSheet = newTempStyleSheet; }); }

Target:
private void setAndCreateWebViewsStyleSheet(String styleSheetUrl) { Path stylesheetsCacheDirectory = preferencesService.getCacheStylesheetsDirectory(); noCatch(() -> { Files.createDirectories(stylesheetsCacheDirectory); Path newTempStyleSheet = Files.createTempFile(stylesheetsCacheDirectory, "style-webview", ".css"); try (InputStream inputStream = new URL(styleSheetUrl).openStream()) { Files.copy(inputStream, newTempStyleSheet, StandardCopyOption.REPLACE_EXISTING); } String newStyleSheetUrl = newTempStyleSheet.toUri().toURL().toString(); webViews.forEach(webView -> Platform.runLater(() -> webView.getEngine().setUserStyleSheetLocation(newStyleSheetUrl))); logger.debug("{} created and applied to all web views", newTempStyleSheet.getFileName()); if (currentTempStyleSheet != null) { Files.delete(currentTempStyleSheet); } currentTempStyleSheet = newTempStyleSheet; }); }
Source:
private void checkAnnotators() { synchronized (observedRequests) { long waitingTime; long currentTime = System.currentTimeMillis(); ObservedHttpRequest observedRequest; for (Entry<ObservedHttpRequest, Long> e : observedRequests.entrySet()) { waitingTime = currentTime - e.getValue(); if (waitingTime > maxWaitingTime) { observedRequest = e.getKey(); if (observedRequest.request.isAborted()) { LOGGER.warn( "Observing an HTTP request that is already aborted. This could be mean that the HTTP management does not have been informed about the termination of a request."); observedRequests.remove(observedRequest); } else { LOGGER.info("The HTTP request emitter \"{}\" already runs for ms. Trying to interrupt it.", observedRequest.emitter.getName(), waitingTime); try { observedRequest.emitter.interrupt(observedRequest.request); } catch (UnsupportedOperationException ex) { LOGGER.error("Couldn't interrupt request of HTTP request emitter \"" + observedRequest.emitter.getName() + "\" that is already running for " + waitingTime + " ms."); } } } } } }

Target:
private void checkAnnotators() { synchronized (observedRequests) { long waitingTime; long currentTime = System.currentTimeMillis(); ObservedHttpRequest observedRequest; Iterator<Entry<ObservedHttpRequest, Long>> iterator = observedRequests.entrySet().iterator(); while (iterator.hasNext()) { Entry<ObservedHttpRequest, Long> entry = iterator.next(); waitingTime = currentTime - entry.getValue(); if (waitingTime > maxWaitingTime) { observedRequest = entry.getKey(); if (observedRequest.request.isAborted()) { LOGGER.warn( "Observing an HTTP request that is already aborted. This could be mean that the HTTP management does not have been informed about the termination of a request."); iterator.remove(); } else { LOGGER.info("The HTTP request emitter \"{}\" already runs for ms. Trying to interrupt it.", observedRequest.emitter.getName(), waitingTime); try { observedRequest.emitter.interrupt(observedRequest.request); } catch (UnsupportedOperationException ex) { LOGGER.error("Couldn't interrupt request of HTTP request emitter \"" + observedRequest.emitter.getName() + "\" that is already running for " + waitingTime + " ms."); } } } } } }
Source:
public RowData readRecord(RowData reuse, byte[] bytes, int offset, int numBytes) throws IOException { GenericRowData returnRecord = rowData; if (this.getDelimiter() != null && this.getDelimiter().length == 1 && this.getDelimiter()[0] == NEW_LINE && offset + numBytes >= 1 && bytes[offset + numBytes - 1] == CARRIAGE_RETURN){ numBytes -= 1; } byte[] trimBytes = Arrays.copyOfRange(bytes, offset, offset + numBytes); GenericRowData jsonRow = (GenericRowData) deserializationSchema.deserialize(trimBytes); if (jsonRow != null) { for (int i = 0; i < jsonSelectFieldNames.size(); i++) { returnRecord.setField(jsonFieldMapping[i], jsonRow.getField(i)); } } emitted++; return returnRecord; }

Target:
public RowData readRecord(RowData reuse, byte[] bytes, int offset, int numBytes) throws IOException { if (this.getDelimiter() != null && this.getDelimiter().length == 1 && this.getDelimiter()[0] == NEW_LINE && offset + numBytes >= 1 && bytes[offset + numBytes - 1] == CARRIAGE_RETURN) { numBytes -= 1; } byte[] trimBytes = Arrays.copyOfRange(bytes, offset, offset + numBytes); GenericRowData jsonRow = (GenericRowData) deserializationSchema.deserialize(trimBytes); if (jsonRow == null) { return null; } GenericRowData returnRecord = rowData; for (int i = 0; i < jsonSelectFieldToJsonFieldMapping.length; i++) { returnRecord.setField(jsonSelectFieldToProjectFieldMapping[i], jsonRow.getField(jsonSelectFieldToJsonFieldMapping[i])); } emitted++; return returnRecord; }
Source:
public FedoraId getContainerIdByPath(final String txID, final FedoraId fedoraId) { if (fedoraId.isRepositoryRoot()) { return fedoraId; } final String parent = getContainedBy(txID, fedoraId); if (parent != null) { return FedoraId.create(parent); } String idIterator = fedoraId.getFullId(); while (idIterator.contains("/")) { idIterator = fedoraId.getResourceId().substring(0, idIterator.lastIndexOf("/")); if (idIterator.equals(FEDORA_ID_PREFIX)) { return FedoraId.getRepositoryRootId(); } final FedoraId testID = FedoraId.create(idIterator); if (resourceExists(txID, testID)) { return testID; } } return FedoraId.getRepositoryRootId(); }

Target:
public FedoraId getContainerIdByPath(final String txID, final FedoraId fedoraId) { if (fedoraId.isRepositoryRoot()) { return fedoraId; } final String parent = getContainedBy(txID, fedoraId); if (parent != null) { return FedoraId.create(parent); } String fullId = fedoraId.getFullId(); while (fullId.contains("/")) { fullId = fedoraId.getResourceId().substring(0, fullId.lastIndexOf("/")); if (fullId.equals(FEDORA_ID_PREFIX)) { return FedoraId.getRepositoryRootId(); } final FedoraId testID = FedoraId.create(fullId); if (resourceExists(txID, testID)) { return testID; } } return FedoraId.getRepositoryRootId(); }
Source:
private void setResponseHeaders(BlobInfo blobInfo) throws RestServiceException { BlobProperties blobProperties = blobInfo.getBlobProperties(); restResponseChannel.setStatus(ResponseStatus.Ok); restResponseChannel.setLastModified(new Date(blobProperties.getCreationTimeInMs())); restResponseChannel.setContentLength(blobProperties.getBlobSize()); restResponseChannel.setHeader(RestConstants.Headers.Blob_Size, blobProperties.getBlobSize()); restResponseChannel.setHeader(RestConstants.Headers.Service_Id, blobProperties.getServiceId()); restResponseChannel.setHeader(RestConstants.Headers.Creation_Time, new Date(blobProperties.getCreationTimeInMs())); restResponseChannel.setHeader(RestConstants.Headers.Private, blobProperties.isPrivate()); if (blobProperties.getTimeToLiveInSeconds() != Utils.Infinite_Time) { restResponseChannel.setHeader(RestConstants.Headers.TTL, Long.toString(blobProperties.getTimeToLiveInSeconds())); } if (blobProperties.getContentType() != null) { restResponseChannel.setHeader(RestConstants.Headers.Content_Type, blobProperties.getContentType()); restResponseChannel.setContentType(blobProperties.getContentType()); } if (blobProperties.getOwnerId() != null) { restResponseChannel.setHeader(RestConstants.Headers.Owner_Id, blobProperties.getOwnerId()); } }

Target:
private void setResponseHeaders(BlobInfo blobInfo) throws RestServiceException { BlobProperties blobProperties = blobInfo.getBlobProperties(); restResponseChannel.setStatus(ResponseStatus.Ok); restResponseChannel.setLastModified(new Date(blobProperties.getCreationTimeInMs())); restResponseChannel.setContentLength(blobProperties.getBlobSize()); restResponseChannel.setHeader(RestUtils.Headers.Blob_Size, blobProperties.getBlobSize()); restResponseChannel.setHeader(RestUtils.Headers.Service_Id, blobProperties.getServiceId()); restResponseChannel.setHeader(RestUtils.Headers.Creation_Time, new Date(blobProperties.getCreationTimeInMs())); restResponseChannel.setHeader(RestUtils.Headers.Private, blobProperties.isPrivate()); if (blobProperties.getTimeToLiveInSeconds() != Utils.Infinite_Time) { restResponseChannel.setHeader(RestUtils.Headers.TTL, Long.toString(blobProperties.getTimeToLiveInSeconds())); } if (blobProperties.getContentType() != null) { restResponseChannel.setHeader(RestUtils.Headers.Content_Type, blobProperties.getContentType()); restResponseChannel.setContentType(blobProperties.getContentType()); } if (blobProperties.getOwnerId() != null) { restResponseChannel.setHeader(RestUtils.Headers.Owner_Id, blobProperties.getOwnerId()); } }
Source:
private File createTempReactorProject(Server server) throws MojoFailureException, MojoExecutionException { File tempFolder = new File(server.getServerDirectory(), "temp-project"); if (!tempFolder.exists()) { tempFolder.mkdir(); } Model tempModel = createModel(); Set<Project> watchedModules = server.getWatchedProjects(); for(Project module: watchedModules){ if (!module.getModel().getPomFile().exists()) { throw new IllegalStateException("Source code of module " + module.getArtifactId() + " doesn't exist. " + "Unwatch this module by running mvn openmrs-sdk:unwatch -DartifactId="+module.getArtifactId()+" -DserverId=" + serverId); } Path newLink = Paths.get(new File(tempFolder, module.getArtifactId()).getAbsolutePath()); Path existingfile = Paths.get(module.getPath()); try { Files.createSymbolicLink(newLink, existingfile); } catch (IOException e) { copyModuleToTempServer(module.getPath(), newLink.toString()); } finally { tempModel.addModule(module.getArtifactId()); } } try { Writer writer = new FileWriter(new File(tempFolder, "pom.xml")); new MavenXpp3Writer().write(writer, tempModel); } catch (IOException e) { throw new RuntimeException("Failed to write pom.xml", e); } return tempFolder; }

Target:
private File createTempReactorProject(Server server) throws MojoFailureException, MojoExecutionException { File tempFolder = new File(server.getServerDirectory(), "temp-project"); if (!tempFolder.exists()) { tempFolder.mkdir(); } Model tempModel = createModel(); Set<Project> watchedModules = server.getWatchedProjects(); for(Project module: watchedModules){ if (!module.getModel().getPomFile().exists()) { throw new IllegalStateException("Module " + module.getArtifactId() + " could not be found at " + module.getModel().getPomFile().getAbsolutePath() + ". " + "Unwatch this module by running mvn openmrs-sdk:unwatch -DartifactId="+module.getArtifactId()+" -DserverId=" + serverId); } Path newLink = Paths.get(new File(tempFolder, module.getArtifactId()).getAbsolutePath()); Path existingfile = Paths.get(module.getPath()); try { Files.createSymbolicLink(newLink, existingfile); } catch (IOException e) { copyModuleToTempServer(module.getPath(), newLink.toString()); } finally { tempModel.addModule(module.getArtifactId()); } } try { Writer writer = new FileWriter(new File(tempFolder, "pom.xml")); new MavenXpp3Writer().write(writer, tempModel); } catch (IOException e) { throw new RuntimeException("Failed to write pom.xml", e); } return tempFolder; }
Source:
public void testMultipartRequest() throws Exception { String BOUNDARY = "01f136d9282f"; ByteBuf byteBuf = Unpooled.wrappedBuffer(("--" + BOUNDARY + "\n" + "Content-Disposition: form-data; name=\"msg_id\"\n" + "\n" + "15200\n" + "--" + BOUNDARY + "\n" + "Content-Disposition: form-data; name=\"msg\"\n" + "\n" + "test message\n" + "--" + BOUNDARY + "--").getBytes()); DefaultFullHttpRequest req = new DefaultFullHttpRequest(HttpVersion.HTTP_1_0, HttpMethod.POST, "/up", byteBuf); req.headers().add(HttpHeaderNames.CONTENT_TYPE, "multipart/form-data; boundary=" + BOUNDARY); HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(new DefaultHttpDataFactory(DefaultHttpDataFactory.MINSIZE), req, java.nio.charset.Charset.forName("utf-8")); assertTrue(decoder.isMultipart()); assertFalse(decoder.getBodyHttpDatas().isEmpty()); assertEquals(2, decoder.getBodyHttpDatas().size()); assertEquals("test message", ((Attribute) decoder.getBodyHttpData("msg")).getValue()); assertEquals("15200", ((Attribute) decoder.getBodyHttpData("msg_id")).getValue()); decoder.destroy(); }

Target:
public void testMultipartRequest() throws Exception { String BOUNDARY = "01f136d9282f"; ByteBuf byteBuf = Unpooled.wrappedBuffer(("--" + BOUNDARY + "\n" + "Content-Disposition: form-data; name=\"msg_id\"\n" + "\n" + "15200\n" + "--" + BOUNDARY + "\n" + "Content-Disposition: form-data; name=\"msg\"\n" + "\n" + "test message\n" + "--" + BOUNDARY + "--").getBytes()); FullHttpRequest req = new DefaultFullHttpRequest(HttpVersion.HTTP_1_0, HttpMethod.POST, "/up", byteBuf); req.headers().add(HttpHeaderNames.CONTENT_TYPE, "multipart/form-data; boundary=" + BOUNDARY); HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(new DefaultHttpDataFactory(DefaultHttpDataFactory.MINSIZE), req, CharsetUtil.UTF_8); assertTrue(decoder.isMultipart()); assertFalse(decoder.getBodyHttpDatas().isEmpty()); assertEquals(2, decoder.getBodyHttpDatas().size()); assertEquals("test message", ((Attribute) decoder.getBodyHttpData("msg")).getValue()); assertEquals("15200", ((Attribute) decoder.getBodyHttpData("msg_id")).getValue()); decoder.destroy(); assertEquals(1, req.refCnt()); }
Source:
private LiteralSuggestion getDmsSuggestion(final String query) { final List<LatLon> dmsCoordinates = new ArrayList<>(); final Matcher matcher = PATTERN_DMS_COORDINATE.matcher(query); final StringBuilder nameBuilder = new StringBuilder("DMS:"); int start = 0; while (matcher.find()) { LOGGER.trace("Match found [{}]", matcher.group()); LatLon parsedDms = CoordinateTranslator.dmsToLatLon(query.substring(start, matcher.end())); start = matcher.end(); if (parsedDms != null) { dmsCoordinates.add(parsedDms); nameBuilder .append(" [ ") .append(CoordinateTranslator.normalizedDmsString(matcher.group())) .append(" ]"); } } if (dmsCoordinates.isEmpty()) { LOGGER.trace("No valid DMS strings could be inferred from query [{}]", query); return null; } return new LiteralSuggestion(LITERAL_SUGGESTION_ID, nameBuilder.toString(), dmsCoordinates); }

Target:
private LiteralSuggestion getDmsSuggestion(final String query) { final List<LatLon> dmsCoordinates = new ArrayList<>(); final Matcher matcher = PATTERN_DMS_COORDINATES.matcher(query); final StringBuilder nameBuilder = new StringBuilder("DMS:"); int start = 0; while (matcher.find()) { final String dmsString = query.substring(start, matcher.end()); final LatLon latLon = dmsToLatLon(dmsString); start = matcher.end(); if (latLon != null) { LOGGER.trace("Match found [{}]", matcher.group()); dmsCoordinates.add(latLon); nameBuilder .append(" [ ") .append(DMSCoordinates.normalizedDmsString(dmsString)) .append(" ]"); } } if (dmsCoordinates.isEmpty()) { LOGGER.trace("No valid DMS strings could be inferred from query [{}]", query); return null; } return new LiteralSuggestion(LITERAL_SUGGESTION_ID, nameBuilder.toString(), dmsCoordinates); }
Source:
public Optional<StorageObject> openArchive(TaskRequest request) { if (!request.getRevision().isPresent()) { return Optional.absent(); } String revision = request.getRevision().get(); try { return tm.begin((TransactionManager.SupplierInTransaction< Optional<StorageObject>, ResourceNotFoundException, StorageFileNotFoundException, RuntimeException>) () -> archiveManager.openArchive( pm.getProjectStore(request.getSiteId()), request.getProjectId(), revision), ResourceNotFoundException.class, StorageFileNotFoundException.class); } catch (ResourceNotFoundException ex) { throw new IllegalStateException(String.format(ENGLISH, "Archive data for project id=%d revision='%s' is not found in database", request.getProjectId(), request.getRevision().or("") ), ex); } catch (StorageFileNotFoundException ex) { throw new IllegalStateException(String.format(ENGLISH, "Archive file for project id=%d revision='%s' is not found", request.getProjectId(), request.getRevision().or("") ), ex); } }

Target:
public Optional<StorageObject> openArchive(TaskRequest request) { if (!request.getRevision().isPresent()) { return Optional.absent(); } String revision = request.getRevision().get(); try { return tm.<Optional<StorageObject>, ResourceNotFoundException, StorageFileNotFoundException>begin(() -> archiveManager.openArchive( pm.getProjectStore(request.getSiteId()), request.getProjectId(), revision), ResourceNotFoundException.class, StorageFileNotFoundException.class); } catch (ResourceNotFoundException ex) { throw new IllegalStateException(String.format(ENGLISH, "Archive data for project id=%d revision='%s' is not found in database", request.getProjectId(), request.getRevision().or("") ), ex); } catch (StorageFileNotFoundException ex) { throw new IllegalStateException(String.format(ENGLISH, "Archive file for project id=%d revision='%s' is not found", request.getProjectId(), request.getRevision().or("") ), ex); } }
Source:
protected void executeQueryCommand() { getQueryReturnValue().setReturnValue( DbFacade.getInstance().getDiskImageDao().getImagesByStorageId(getParameters().getStorageDomainId())); }

Target:
protected void executeQueryCommand() { getQueryReturnValue().setReturnValue( getDbFacade().getDiskImageDao().getImagesByStorageId(getParameters().getStorageDomainId())); }
Source:
public static String getMD5HashAsString(String plainText) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(plainText.getBytes()); byte[] hashInBytes = md.digest(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < hashInBytes.length; i++) sb.append(Integer.toString((hashInBytes[i] & 0xff) + 0x100, 16).substring(1)); return sb.toString(); } catch (NoSuchAlgorithmException e) { return ""; } }

Target:
public static String getMD5HashAsString(String plainText) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(plainText.getBytes()); byte[] hashInBytes = md.digest(); return Base64.encode(hashInBytes); } catch (NoSuchAlgorithmException e) { return ""; } }
Source:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_purchase_req_response); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_purchase_request); toolbar.setTitle("Purchase"); setSupportActionBar(toolbar); if (getSupportActionBar() != null) { getSupportActionBar().setDisplayHomeAsUpEnabled(true); } initializeComponents(); }

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_purchase_req_response); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_purchase_request); toolbar.setTitle("Purchase"); setSupportActionBar(toolbar); actionBar.enableHomeButton(this); initializeComponents(); }
Source:
public GetConfigurationValuesQuery(P parameters) { super(parameters); configValuesSet = new HashSet<String>(); }

Target:
public GetConfigurationValuesQuery(P parameters) { super(parameters); }
Source:
public PackingPlan repack(PackingPlan currentPackingPlan, Map<String, Integer> componentChanges) { this.numContainers = currentPackingPlan.getContainers().size(); resetState(); int additionalContainers = computeNumAdditionalContainers(componentChanges, currentPackingPlan); increaseNumContainers(additionalContainers); LOG.info(String.format( "Allocated %s additional containers for repack bring the number of containers to %s.", additionalContainers, this.numContainers)); int adjustments = 0; while (adjustments <= this.numAdjustments) { try { PackingPlanBuilder planBuilder = newPackingPlanBuilder(currentPackingPlan); planBuilder.updateNumContainers(numContainers); planBuilder = getResourceCompliantRRAllocation( planBuilder, currentPackingPlan, componentChanges); return planBuilder.build(); } catch (ResourceExceededException e) { LOG.info(String.format( "Increasing the number of containers to %s and attempting packing again.", this.numContainers + 1)); adjustNumContainers(1); containerId = 1; adjustments++; } } return null; }

Target:
public PackingPlan repack(PackingPlan currentPackingPlan, Map<String, Integer> componentChanges) { this.numContainers = currentPackingPlan.getContainers().size(); resetState(); int additionalContainers = computeNumAdditionalContainers(componentChanges, currentPackingPlan); increaseNumContainers(additionalContainers); LOG.info(String.format( "Allocated %s additional containers for repack bring the number of containers to %s.", additionalContainers, this.numContainers)); int adjustments = 0; while (adjustments <= this.numAdjustments) { try { PackingPlanBuilder planBuilder = newPackingPlanBuilder(currentPackingPlan); planBuilder.updateNumContainers(numContainers); planBuilder = getResourceCompliantRRAllocation( planBuilder, currentPackingPlan, componentChanges); return planBuilder.build(); } catch (ResourceExceededException e) { adjustNumContainers(1); containerId = 1; adjustments++; LOG.info(String.format( "Increasing the number of containers to %s and attempting packing again.", this.numContainers)); } } return null; }
Source:
public void commit(boolean ddl) { checkCommitRollback(); currentTransactionName = null; transactionStart = null; if (transaction != null) { try { if (!locks.isEmpty()) { for (Table t : locks) { if (t instanceof MVTable) { ((MVTable) t).commit(); } } } transaction.commit(); } finally { transaction = null; } } else if (containsUncommitted()) { database.commit(this); } analyzeTables(); removeTemporaryLobs(true); if (undoLog != null && undoLog.size() > 0) { undoLog.clear(); } if (!ddl) { cleanTempTables(false); if (autoCommitAtTransactionEnd) { autoCommit = true; autoCommitAtTransactionEnd = false; } } endTransaction(); }

Target:
public void commit(boolean ddl) { checkCommitRollback(); currentTransactionName = null; transactionStart = null; if (transaction != null) { try { if (!locks.isEmpty()) { for (Table t : locks) { if (t instanceof MVTable) { ((MVTable) t).commit(); } } } transaction.commit(); } finally { transaction = null; } } else if (containsUncommitted()) { database.commit(this); } removeTemporaryLobs(true); if (undoLog != null && undoLog.size() > 0) { undoLog.clear(); } if (!ddl) { cleanTempTables(false); if (autoCommitAtTransactionEnd) { autoCommit = true; autoCommitAtTransactionEnd = false; } } if (tablesToAnalyze != null) { if (database.isMVStore()) { analyzeTables(); commit(true); } else { analyzeTables(); } } endTransaction(); }
Source:
protected URI buildURI(String url) { LOG.info("buildURI The passed in URL is: " + url); URI uri; try { uri = new URI(url); } catch (URISyntaxException e) { throw new RuntimeException(e); } return uri; }

Target:
protected URI buildURI(String url) { LOG.debug("buildURI The passed in URL is: " + url); URI uri; try { uri = new URI(url); } catch (URISyntaxException e) { LOG.error("buildURI unable to build a URI object for the URL: '" + url + "' with the error: ", e); throw new RuntimeException("Unable to build URI for the URL: " + url, e); } return uri; }
Source:
public TokenManager getTokenManager(Mono<ClaimsBasedSecurityNode> cbsNodeMono, String resource) { final String scopes = getResourceString(resource); final String tokenAudience = String.format(Locale.US, TOKEN_AUDIENCE_FORMAT, fullyQualifiedNamespace, resource); logger.info("Creating new token manager for audience[{}], resource[{}]", tokenAudience, resource); return new ActiveClientTokenManager(cbsNodeMono, tokenAudience, scopes); }

Target:
public TokenManager getTokenManager(Mono<ClaimsBasedSecurityNode> cbsNodeMono, String resource) { final String scopes = getScopesFromResource(resource); final String tokenAudience = String.format(Locale.US, TOKEN_AUDIENCE_FORMAT, fullyQualifiedNamespace, resource); logger.info("Creating new token manager for audience[{}], resource[{}]", tokenAudience, resource); return new ActiveClientTokenManager(cbsNodeMono, tokenAudience, scopes); }
Source:
public void comprehension_scope() { FunctionDef functionTree = functionTreesByName.get("scope_of_comprehension"); Map<String, Symbol> symbolByName = getSymbolByName(functionTree); assertThat(symbolByName).containsOnlyKeys("x"); assertThat(symbolByName.get("x").usages().stream().map(u -> u.tree().firstToken().line())).hasSize(2).containsExactly(98, 100).doesNotContain(99); Name name = (Name) ((ComprehensionExpression) ((ExpressionStatement) functionTree.body().statements().get(0)).expressions().get(0)).comprehensionFor().loopExpression(); assertThat(name.symbol().usages().stream().map(u -> u.tree().firstToken().line())).hasSize(2).doesNotContain(98, 100).containsExactly(99, 99); }

Target:
public void comprehension_scope() { FunctionDef functionTree = functionTreesByName.get("scope_of_comprehension"); Map<String, Symbol> symbolByName = getSymbolByName(functionTree); assertThat(symbolByName).containsOnlyKeys("x"); assertThat(symbolByName.get("x").usages()).extracting(u -> u.tree().firstToken().line()).containsExactly(98, 100).doesNotContain(99); Name name = (Name) ((ComprehensionExpression) ((ExpressionStatement) functionTree.body().statements().get(0)).expressions().get(0)).comprehensionFor().loopExpression(); assertThat(name.symbol().usages()).extracting(u -> u.tree().firstToken().line()).doesNotContain(98, 100).containsExactly(99, 99); }
Source:
static private void parse(Config cfg, GerritConfig c) { ArrayList<String> l = Lists.newArrayList(splitter.split(c.name())); if (l.size() == 2) { cfg.setString(l.get(0), null, l.get(1), c.value()); } else if (l.size() == 3) { cfg.setString(l.get(0), l.get(1), l.get(2), c.value()); } else { throw new IllegalArgumentException( "GerritConfig.name must of the following format" + " section.subsection.name or section.name"); } }

Target:
static private void parse(Config cfg, GerritConfig c) { ArrayList<String> l = Lists.newArrayList(splitter.split(c.name())); if (l.size() == 2) { cfg.setString(l.get(0), null, l.get(1), c.value()); } else if (l.size() == 3) { cfg.setString(l.get(0), l.get(1), l.get(2), c.value()); } else { throw new IllegalArgumentException( "GerritConfig.name must be of the format" + " section.subsection.name or section.name"); } }
Source:
private static Geometry readPolyline(SliceInput input, boolean multitype) { skipEsriType(input); skipEnvelope(input); int partCount = input.readInt(); if (partCount == 0) { if (multitype) { return GEOMETRY_FACTORY.createMultiLineString(); } else { return GEOMETRY_FACTORY.createLineString(); } } int pointCount = input.readInt(); int[] startIndexes = new int[partCount]; for (int i = 0; i < partCount; i++) { startIndexes[i] = input.readInt(); } int[] partLengths = new int[partCount]; if (partCount > 1) { partLengths[0] = startIndexes[1]; for (int i = 1; i < partCount - 1; i++) { partLengths[i] = startIndexes[i + 1] - startIndexes[i]; } } partLengths[partCount - 1] = pointCount - startIndexes[partCount - 1]; LineString[] lineStrings = new LineString[partCount]; for (int i = 0; i < partCount; i++) { lineStrings[i] = GEOMETRY_FACTORY.createLineString(readCoordinates(input, partLengths[i])); } if (multitype) { return GEOMETRY_FACTORY.createMultiLineString(lineStrings); } else { verify(lineStrings.length == 1); return lineStrings[0]; } }

Target:
private static Geometry readPolyline(SliceInput input, boolean multitype) { skipEsriType(input); skipEnvelope(input); int partCount = input.readInt(); if (partCount == 0) { if (multitype) { return GEOMETRY_FACTORY.createMultiLineString(); } return GEOMETRY_FACTORY.createLineString(); } int pointCount = input.readInt(); int[] startIndexes = new int[partCount]; for (int i = 0; i < partCount; i++) { startIndexes[i] = input.readInt(); } int[] partLengths = new int[partCount]; if (partCount > 1) { partLengths[0] = startIndexes[1]; for (int i = 1; i < partCount - 1; i++) { partLengths[i] = startIndexes[i + 1] - startIndexes[i]; } } partLengths[partCount - 1] = pointCount - startIndexes[partCount - 1]; LineString[] lineStrings = new LineString[partCount]; for (int i = 0; i < partCount; i++) { lineStrings[i] = GEOMETRY_FACTORY.createLineString(readCoordinates(input, partLengths[i])); } if (multitype) { return GEOMETRY_FACTORY.createMultiLineString(lineStrings); } verify(lineStrings.length == 1); return lineStrings[0]; }
Source:
public void testHddToVolume() { server.enqueue( new MockResponse().setBody(stringFromResource("/compute/volume.json")) ); org.apache.jclouds.oneandone.rest.domain.Hdd hdd = api.serverApi().getHdd("some-id", "hdd-id"); Volume actual = fnVolume.apply(hdd); Volume expected = new VolumeBuilder() .id(hdd.id()) .size((float) hdd.size()) .bootDevice(hdd.isMain()) .durable(true) .type(Volume.Type.LOCAL).build(); assertEquals(actual, expected); }

Target:
public void testHddToVolume() { org.apache.jclouds.oneandone.rest.domain.Hdd hdd = org.apache.jclouds.oneandone.rest.domain.Hdd.create("some-id", 40, true); Volume actual = fnVolume.apply(hdd); Volume expected = new VolumeBuilder() .id(hdd.id()) .size((float) hdd.size()) .bootDevice(hdd.isMain()) .durable(true) .type(Volume.Type.LOCAL).build(); assertEquals(actual, expected); }
Source:
private boolean canRemoveVm() { if (IsVmRunning(getVmId()) || (getVm().getStatus() == VMStatus.NotResponding)) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_VM_IS_RUNNING); } if (getVm().getStatus() == VMStatus.Suspended) { return failCanDoAction(VdcBllMessages.VM_CANNOT_REMOVE_VM_WHEN_STATUS_IS_NOT_DOWN); } if (isVmInPool(getVmId())) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_VM_ATTACHED_TO_POOL); } SnapshotsValidator snapshotsValidator = new SnapshotsValidator(); if (!validate(snapshotsValidator.vmNotDuringSnapshot(getVmId()))) { return false; } if (getParameters().getForce() && !validate(snapshotsValidator.vmNotInPreview(getVmId()))) { return false; } if (!ImagesHandler.PerformImagesChecks(getVm(), getReturnValue().getCanDoActionMessages(), getVm().getStoragePoolId(), Guid.Empty, false, !getParameters().getForce(), false, false, !getVm().getDiskMap().values().isEmpty(), true, getVm().getDiskMap().values())) { return false; } if (getVm().getStatus() == VMStatus.ImageLocked) { if (!getParameters().getForce()) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_VM_IS_LOCKED); } if (AsyncTaskManager.getInstance().HasTasksByStoragePoolId(getVm().getStoragePoolId())) { return failCanDoAction(VdcBllMessages.VM_CANNOT_REMOVE_HAS_RUNNING_TASKS); } } return true; }

Target:
private boolean canRemoveVm() { if (IsVmRunning(getVmId()) || (getVm().getStatus() == VMStatus.NotResponding)) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_VM_IS_RUNNING); } if (getVm().getStatus() == VMStatus.Suspended) { return failCanDoAction(VdcBllMessages.VM_CANNOT_REMOVE_VM_WHEN_STATUS_IS_NOT_DOWN); } if (isVmInPool(getVmId())) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_VM_ATTACHED_TO_POOL); } SnapshotsValidator snapshotsValidator = new SnapshotsValidator(); if (!validate(snapshotsValidator.vmNotDuringSnapshot(getVmId()))) { return false; } if (getParameters().getForce() && !validate(snapshotsValidator.vmNotInPreview(getVmId()))) { return false; } if (!ImagesHandler.PerformImagesChecks(getVm(), getReturnValue().getCanDoActionMessages(), getVm().getStoragePoolId(), Guid.Empty, false, !getParameters().getForce(), false, false, !getVm().getDiskMap().values().isEmpty(), true, getVm().getDiskMap().values())) { return false; } VmValidator vmValidator = new VmValidator(getVm()); ValidationResult vmLockedValidatorResult = vmValidator.vmNotLocked(); if (!vmLockedValidatorResult.isValid()) { if (!getParameters().getForce()) { return failCanDoAction(vmLockedValidatorResult.getMessage()); } if (AsyncTaskManager.getInstance().HasTasksByStoragePoolId(getVm().getStoragePoolId())) { return failCanDoAction(VdcBllMessages.VM_CANNOT_REMOVE_HAS_RUNNING_TASKS); } } return true; }
Source:
public void shouldNotDeadlockOnConcurrentClassInitialization() throws InterruptedException { final ExecutorService executorService = Executors.newFixedThreadPool(2); executorService.execute(new ClassInitializer(javaslang.collection.Iterator.class.getName())); executorService.execute(new ClassInitializer(javaslang.collection.AbstractIterator.class.getName())); executorService.shutdown(); Iterator.empty().iterator(); }

Target:
public void shouldNotDeadlockOnConcurrentClassInitialization() throws InterruptedException { final ExecutorService executorService = Executors.newFixedThreadPool(2); executorService.execute(new ClassInitializer("javaslang.collection.Iterator")); executorService.execute(new ClassInitializer("javaslang.collection.AbstractIterator")); executorService.shutdown(); Iterator.empty().iterator(); }
Source:
public static List<String> getTableDataByColumn(WebElement table, int columnIndex) { List<WebElement> rows = getRowsOfTable(table); List<String> data = new ArrayList<>(); for (WebElement row : rows) { data.add(getCellDataByRow(row, columnIndex)); System.out.println(getCellDataByRow(row, columnIndex)); } return data; }

Target:
public static List<String> getTableDataByColumn(WebElement table, int columnIndex) { List<WebElement> rows = getRowsOfTable(table); List<String> data = new ArrayList<>(); for (WebElement row : rows) { data.add(getCellDataByRow(row, columnIndex)); } return data; }
Source:
public void executeTask(final CronTaskConfigurationDto config) throws Throwable { final String lastAccessedTimeInDaysText = config.getRequiredProperty(PROPERTY_LAST_ACCESSED_TIME_IN_DAYS); final String minSizeInBytesText = config.getProperty(PROPERTY_MIN_SIZE_IN_BYTES); final Integer lastAccessedTimeInDays; try { lastAccessedTimeInDays = Integer.valueOf(lastAccessedTimeInDaysText); } catch (NumberFormatException ex) { logger.error("Invalid integer value of 'lastAccessedTimeInDays' property. Cron job won't be fired.", lastAccessedTimeInDaysText, ex); return; } Long minSizeInBytes = Long.valueOf(-1); if (minSizeInBytesText != null) { try { minSizeInBytes = Long.valueOf(minSizeInBytesText); } catch (NumberFormatException ex) { logger.error("Invalid Long value of 'minSizeInBytes' property. Cron job won't be fired.", minSizeInBytesText, ex); return; } } proxyRepositoryObsoleteArtifactsCleaner.cleanup(lastAccessedTimeInDays, minSizeInBytes); }

Target:
public void executeTask(final CronTaskConfigurationDto config) throws Throwable { final String lastAccessedTimeInDaysText = config.getRequiredProperty(PROPERTY_LAST_ACCESSED_TIME_IN_DAYS); final String minSizeInBytesText = config.getProperty(PROPERTY_MIN_SIZE_IN_BYTES); final Integer lastAccessedTimeInDays; try { lastAccessedTimeInDays = Integer.valueOf(lastAccessedTimeInDaysText); } catch (NumberFormatException ex) { logger.error("Invalid integer value of 'lastAccessedTimeInDays' property. Cron job won't be fired.", lastAccessedTimeInDaysText, ex); return; } Long minSizeInBytes = Long.valueOf(-1); if (minSizeInBytesText != null) { try { minSizeInBytes = Long.valueOf(minSizeInBytesText); } catch (NumberFormatException ex) { logger.error("Invalid long value of 'minSizeInBytes' property. Cron job won't be fired.", minSizeInBytesText, ex); return; } } proxyRepositoryObsoleteArtifactsCleaner.cleanup(lastAccessedTimeInDays, minSizeInBytes); }
Source:
public InputStream openStream(long offset) throws IOException { try { return azureStorage.getBlobInputStream(offset, containerName, blobPath); } catch (StorageException | URISyntaxException e) { if (AzureUtils.AZURE_RETRY.apply(e)) { throw new IOException("Recoverable exception", e); } log.warn("Exception when opening stream to azure resource, containerName: %s, blobPath: %s, Error: %s", containerName, blobPath, e.getMessage() ); throw new RuntimeException(e); } }

Target:
public InputStream openStream(long offset) throws IOException { try { return azureStorage.getBlobInputStream(offset, containerName, blobPath); } catch (StorageException | URISyntaxException e) { if (AzureUtils.AZURE_RETRY.apply(e)) { throw new IOException("Recoverable exception", e); } log.error("Exception when opening stream to azure resource, containerName: %s, blobPath: %s, Error: %s", containerName, blobPath, e.getMessage() ); throw new RuntimeException(e); } }
Source:
private List<VdcOption> moveDependentToEnd(List<VdcOption> list) { Predicate<VdcOption> isDependent = o -> { EnumValue parsed = parseEnumValue(o.getOptionName()); if (parsed != null) { OptionBehaviourAttribute behaviour = parsed.getOptionBehaviour(); if(behaviour == null){ return false; } return behaviour.behaviour() == ValueDependent; } return false; }; List<VdcOption> optionsList = list.stream().filter(isDependent.negate()).collect(Collectors.toList()); optionsList.addAll(list.stream().filter(isDependent).collect(Collectors.toList())); return optionsList; }

Target:
private List<VdcOption> moveDependentToEnd(List<VdcOption> list) { Predicate<VdcOption> isDependent = o -> { EnumValue parsed = parseEnumValue(o.getOptionName()); if (parsed != null) { OptionBehaviourAttribute behaviour = parsed.getOptionBehaviour(); return behaviour != null && behaviour.behaviour() == ValueDependent; } return false; }; List<VdcOption> optionsList = list.stream().filter(isDependent.negate()).collect(Collectors.toList()); optionsList.addAll(list.stream().filter(isDependent).collect(Collectors.toList())); return optionsList; }
Source:
public void provideUniqueRoutesNames() throws Exception { final HashMap<String, Route> routes = new HashMap<>(); routes.put(POD_NAME, newRoute()); doReturn(routes).when(osEnv).getRoutes(); uniqueNamesProvisioner.provision(environment, osEnv, runtimeIdentity); final String actual = osEnv .getRoutes() .values() .stream() .map(r -> r.getMetadata().getName()) .collect(toList()) .get(0); assertTrue(actual.startsWith(ROUTE_PREFIX)); assertTrue(actual.length() == ROUTE_PREFIX.length() + ROUTE_SUFFIX_SIZE); }

Target:
public void provideUniqueRoutesNames() throws Exception { final HashMap<String, Route> routes = new HashMap<>(); routes.put(POD_NAME, newRoute()); doReturn(routes).when(osEnv).getRoutes(); uniqueNamesProvisioner.provision(environment, osEnv, runtimeIdentity); final ObjectMeta routeData = osEnv.getRoutes().values().stream().map(Route::getMetadata).collect(toList()).get(0); assertTrue(routeData.getName().startsWith(ROUTE_PREFIX)); assertTrue(UNIQUE_ROUTE_NAME_REGEX.matcher(routeData.getName()).matches()); assertEquals(routeData.getLabels().get(CHE_ORIGINAL_NAME_LABEL), ROUTE_NAME); }
Source:
private static void assertDocumentPropertiesChanges(DocumentModel doc, Map<String, Object> originalProperties, Set<String> expectedChangedPropertyNames) { originalProperties.keySet().forEach(property -> { Object currentValue = doc.getProperty("dublincore", property); if (expectedChangedPropertyNames.contains(property)) { assertNotEquals(originalProperties.get(property), currentValue); } else { assertEquals(currentValue, originalProperties.get(property)); } }); }

Target:
protected static void assertDocumentPropertiesChanges(DocumentModel doc, Map<String, Object> originalProperties, Set<String> expectedChangedPropertyNames) { originalProperties.forEach((key, value) -> { Object currentValue = doc.getProperty("dublincore", key); if (expectedChangedPropertyNames.contains(key)) { assertNotEquals(value, currentValue); } else { assertEquals(currentValue, value); } }); }
Source:
public void addMeasurement(Integer rssi) { LogManager.d(TAG, "adding rssi: %s", rssi); armaMeasurement = Double.valueOf(armaMeasurement - 0.1*(armaMeasurement - rssi)).intValue(); LogManager.d(TAG, "armaMeasurement: %s", armaMeasurement); }

Target:
public void addMeasurement(Integer rssi) { LogManager.d(TAG, "adding rssi: %s", rssi); if (!isInitialized) { armaMeasurement = rssi; isInitialized = true; }; armaMeasurement = Double.valueOf(armaMeasurement - armaSpeed * (armaMeasurement - rssi)).intValue(); LogManager.d(TAG, "armaMeasurement: %s", armaMeasurement); }
Source:
public ISchedulingRule getRule(int kind, Map<String, String> args) { String pref = InstanceScope.INSTANCE.getNode(JavaCore.PLUGIN_ID).get(PREF_SCHEDULING_RULE, null); if (pref != null) { if(pref.equals("project")) return getProject(); else if(pref.equals("null")) { return null; } } return super.getRule(kind, args); }

Target:
public ISchedulingRule getRule(int kind, Map<String, String> args) { String pref = InstanceScope.INSTANCE.getNode(JavaCore.PLUGIN_ID).get(PREF_SCHEDULING_RULE, null); if (pref != null) { if(pref.equals("project")) { return getProject(); } else if(pref.equals("null") || Boolean.parseBoolean(pref)) { return null; } } return super.getRule(kind, args); }
Source:
public Tuple2<List<T>, List<T>> splitAtInclusive(Predicate<? super T> predicate) { Tuple2<List<T>, List<T>> t = splitByPredicateFirstRound(this, predicate); if (!t._2.isEmpty()) { return Tuple.of(t._1.prepend(t._2.head()).reverse(), t._2.tail()); } else { return Tuple.of(t._1.reverse(), t._2); } }

Target:
public Tuple2<List<T>, List<T>> splitAtInclusive(Predicate<? super T> predicate) { final Tuple2<List<T>, List<T>> t = splitByPredicateReversed(this, predicate); if (t._2.isEmpty() || t._2.tail().isEmpty()) { return Tuple.of(this, empty()); } else { return Tuple.of(t._1.prepend(t._2.head()).reverse(), t._2.tail()); } }
Source:
public PartialConfig load(File configRepoCheckoutDirectory, PartialConfigLoadContext context) { File[] allFiles = getFiles(configRepoCheckoutDirectory, context); PartialConfig[] allFragments = ParseFiles(allFiles); PartialConfig partialConfig = new PartialConfig(); CollectFragments(allFragments, partialConfig); partialConfig.validatePart(); return partialConfig; }

Target:
public PartialConfig load(File configRepoCheckoutDirectory, PartialConfigLoadContext context) { File[] allFiles = getFiles(configRepoCheckoutDirectory, context); PartialConfig[] allFragments = parseFiles(allFiles); PartialConfig partialConfig = new PartialConfig(); collectFragments(allFragments, partialConfig); partialConfig.validatePart(); return partialConfig; }
Source:
public ASTNode visit(TermCons tc, Void _) throws ParseFailedException { ASTNode vis; if (!tc.getProduction().containsAttribute("klabel")) vis = super.visitNode(tc.getContents().get(0), _); else vis = super.visit(tc, _); return vis; }

Target:
public ASTNode visit(TermCons tc, Void _) throws ParseFailedException { ASTNode vis; if (!tc.getProduction().containsAttribute("klabel")) vis = this.visitNode(tc.getContents().get(0), _); else vis = super.visit(tc, _); return vis; }
Source:
private Map<String, String> getNodeSelectorMap(String selectors) { ImmutableMap.Builder<String, String> builder = ImmutableMap.<String, String> builder(); for (String selector : selectors.split(",")) { String[] parts = selector.split("="); if (parts.length == 2) { if (parts.length == 2) { builder = builder.put(parts[0], parts[1]); } } } return builder.build(); }

Target:
private Map<String, String> getNodeSelectorMap(String selectors) { if (selectors.isEmpty()) { return ImmutableMap.of(); } else { ImmutableMap.Builder<String, String> builder = ImmutableMap.<String, String> builder(); for (String selector : selectors.split(",")) { String[] parts = selector.split("="); if (parts.length == 2 && !parts[0].isEmpty() && !parts[1].isEmpty()) { builder = builder.put(parts[0], parts[1]); } else { LOGGER.log(Level.WARNING, "Ignoring selector '" + selector + "'. Selectors must be in the format 'label1=value1,label2=value2'."); } } return builder.build(); } }
Source:
private void initApplicationState() { logic = new Logic(uiManager, prefs, Optional.empty(), Optional.empty()); TickingTimer refreshTimer = new TickingTimer("Refresh Timer", TickingTimerManager.DEFAULT_REFRESH_PERIOD_IN_SEC, status::updateTimeToRefresh, logic::refresh, TimeUnit.SECONDS); timerManager = new TickingTimerManager(refreshTimer); timerManager.startTimer(); undoController = new UndoController(notificationController); }

Target:
private void initApplicationState() { logic = new Logic(uiManager, prefs, Optional.empty(), Optional.empty()); apiQuotaManager = new ApiQuotaManager(logic); undoController = new UndoController(notificationController); }
Source:
public void x() throws Exception { HashSet<String> doNotStop = new HashSet<String>(); doNotStop.add("org.eclipse.core.resources"); doNotStop.add("org.eclipse.osgi"); OteServiceStarter service = ServiceUtility.getService(OteServiceStarter.class); if(service != null){ service.stop(); } BundleContext context = FrameworkUtil.getBundle(getClass()).getBundleContext(); long time = System.currentTimeMillis(); boolean canExit = false; int count = 0; while(!canExit && count < 2000){ count++; canExit = true; for(Bundle b:context.getBundles()){ String symbolicName = b.getSymbolicName(); if(!doNotStop.contains(symbolicName)){ if(b.getState() == Bundle.ACTIVE){ canExit = false; b.stop(); } } } try{ Thread.sleep(20); } catch (Throwable th){ } } System.out.printf("%d ms to shutdown server\n", (System.currentTimeMillis() - time)); System.exit(0); }

Target:
public void x() throws Exception { long time = System.currentTimeMillis(); OteServiceStarter service = ServiceUtility.getService(OteServiceStarter.class); if(service != null){ service.stop(); } OSGIShutdownUtil.stopBundles(); System.out.printf("%d ms to shutdown server\n", (System.currentTimeMillis() - time)); System.exit(0); }
Source:
public void forEachAssignedPartition(Consumer<TopicPartition> consumer) { this.assignment.partitionSet().forEach(consumer); }

Target:
public synchronized void forEachAssignedPartition(Consumer<TopicPartition> consumer) { this.assignment.partitionSet().forEach(consumer); }
Source:
public void createMultipleUpdateActions() throws Exception { final List<String> contentList = generateAsStrings(MyResource.class); final List<String> expectedContent = expectedContent(MyResource.class); int index = 0; for (String content : contentList) { assertThat(content).isEqualTo(expectedContent.get(index++)); } }

Target:
public void createMultipleUpdateActions() throws Exception { final List<String> contentList = generateAsStrings(MyResource.class); final List<String> expectedContent = expectedContent(MyResource.class); assertThat(contentList).hasSameSizeAs(expectedContent); for (int index = 0; index < contentList.size(); index++) { assertThat(contentList.get(index)).isEqualTo(expectedContent.get(index)); } }
Source:
public static byte[] getInputStreamBytes(InputStream inputStream) throws IOException { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); IOUtils.copy(inputStream, outputStream); return outputStream.toByteArray(); }

Target:
public static byte[] getInputStreamBytes(InputStream inputStream) throws IOException { try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) { IOUtils.copy(inputStream, outputStream); outputStream.toByteArray(); return outputStream.toByteArray(); } }
Source:
void listUsersSuccessfully() throws Exception { MvcResult result = mvc() .perform(get("/api/users")) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(document("users/list")) .andReturn(); GetUserResponse[] users = fromJson(result.getResponse().getContentAsString(), GetUserResponse[].class); Assertions.assertEquals(1, users.length); Assertions.assertEquals("username", users[0].getUsername()); }

Target:
void listUsersSuccessfully() throws Exception { MvcResult result = mvc() .perform(get("/api/users")) .andExpect(status().isOk()) .andDo(document("users/list")) .andReturn(); GetUserResponse[] users = fromJson(result.getResponse().getContentAsString(), GetUserResponse[].class); Assertions.assertEquals(1, users.length); Assertions.assertEquals("username", users[0].getUsername()); }
Source:
public RequestIdPolicy(String requestIdHeaderName) { this.requestIdHeaderName = Objects.requireNonNull(requestIdHeaderName, "messageIdHeaderName can not be null."); }

Target:
public RequestIdPolicy(String requestIdHeaderName) { this.requestIdHeaderName = Objects.requireNonNull(requestIdHeaderName, "requestIdHeaderName can not be null."); }