auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private synchronized Map<String, ThriftSerializedObject> partialSnapshot(TDeserializer td) { int attempts = 0; while (true) { try { return partialDeserializeLatestVersion(td); } catch (Exception e) { attempts++; if (attempts >= 10) { if (e.getCause() instanceof TProtocolException) { <START> LOG.warn("LocalState file is corrupted, resetting state"); <END> return new HashMap<>(); } throw new RuntimeException(e); } } } }</code><technical_language>more minor thing. Do sense exception stack trace well? hard debug if this case is hit unexpectedly</technical_language>

Target:
private synchronized Map<String, ThriftSerializedObject> partialSnapshot(TDeserializer td) { int attempts = 0; while (true) { try { return partialDeserializeLatestVersion(td); } catch (Exception e) { attempts++; if (attempts >= 10) { if (e.getCause() instanceof TProtocolException) { LOG.warn("LocalState file is corrupted, resetting state.", e); return new HashMap<>(); } throw new RuntimeException(e); } } } }
Source:
<code>List<MultipartUpload> listUploads() { List<MultipartUpload> result = null; try { if (bucketPoolSize > 0) { <START> result = new ArrayList<MultipartUpload>(); <END> for (int i = 0; i < bucketPoolSize; i++) { val actualBucketName = BucketResolver.constructBucketName(bucketName, i); val request = new ListMultipartUploadsRequest(actualBucketName); val response = s3Client.listMultipartUploads(request); result.addAll(response.getMultipartUploads()); } } else { val request = new ListMultipartUploadsRequest(bucketName); val response = s3Client.listMultipartUploads(request); result = response.getMultipartUploads(); } return result; } catch (AmazonServiceException e) { log.error("Failed to list uploads on partition : ", e); throw new RetryableException(e); } }</code><technical_language>Please favor immutable collections. val response = ImmutableList.<MultipartUpload>builder() here</technical_language>

Target:
List<MultipartUpload> listUploads() { List<MultipartUpload> result = null; try { if (bucketNamingService.isPartitioned()) { result = new ArrayList<MultipartUpload>(); for (int i = 0; i < bucketNamingService.getBucketPoolSize(); i++) { val actualBucketName = bucketNamingService.constructBucketName(bucketNamingService.getBaseObjectBucketName(), i); val request = new ListMultipartUploadsRequest(actualBucketName); val response = s3Client.listMultipartUploads(request); result.addAll(response.getMultipartUploads()); } } else { val request = new ListMultipartUploadsRequest(bucketNamingService.getBaseObjectBucketName()); val response = s3Client.listMultipartUploads(request); result = response.getMultipartUploads(); } return result; } catch (AmazonServiceException e) { log.error("Failed to list uploads on partition : ", e); throw new RetryableException(e); } }
Source:
<code>public String getNodeDownloadFilename(String nodeVersion) { if(isWindows()) { int versionCompare = nodeVersion.compareTo("v4.0.0"); if(architecture == Architecture.x64){ <START> if (versionCompare >= 0) { <END> return nodeVersion+"/win-x64/node.exe"; } else { return nodeVersion+"/x64/node.exe"; } } else { if (versionCompare < 0) { return nodeVersion+"/win-x86/node.exe"; } else { return nodeVersion + "/node.exe"; } } } else { return nodeVersion + "/" + getLongNodeFilename(nodeVersion) + ".tar.gz"; } }</code><technical_language>"v4.0.0".equals( nodeVersion ) suffice diff verbosity. some spacing changes here</technical_language>

Target:
public String getNodeDownloadFilename(String nodeVersion) { if(isWindows()) { if(architecture == Architecture.x64){ if (nodeVersion.startsWith("v0.")) { return nodeVersion+"/x64/node.exe"; } else { return nodeVersion+"/win-x64/node.exe"; } } else { if (nodeVersion.startsWith("v0.")) { return nodeVersion + "/node.exe"; } else { return nodeVersion+"/win-x86/node.exe"; } } } else { return nodeVersion + "/" + getLongNodeFilename(nodeVersion) + ".tar.gz"; } }
Source:
<code>private int getAdapterPosition(@Nullable String input) { int ret = -1; if (input != null && adapter != null) { for(int i=0 ; i<adapter.getCount() ; i++){ RegistrationOption item = adapter.getItem(i); if (item != null && input.equals(item.toString())) { ret = i; break; } } } <START> return ret; <END> }</code><technical_language>@mdinino more descriptive variable names</technical_language>

Target:
private int getAdapterPosition(@Nullable String input) { int posiiton = -1; if (input != null && adapter != null) { for(int i=0 ; i<adapter.getCount() ; i++){ RegistrationOption item = adapter.getItem(i); if (item != null && input.equals(item.toString())) { posiiton = i; break; } } } return posiiton; }
Source:
<code>public Collection<Class<?>> getProvidedServiceTypes() { <START> return Collections.singletonList(LogicalServerStateMBeanImpl.class); <END> }</code><technical_language>Needs replaced interface</technical_language>

Target:
public Collection<Class<?>> getProvidedServiceTypes() { return Collections.singletonList(LogicalServerStateProvider.class); }
Source:
<code>public ListenableFuture<String> renewAuthorizationHeader(final String ignored) { final String authRequest = CrtAuthClient.createRequest(username); try { final HeliosRequest request = HeliosRequest.builder() .method("GET") .uri(new URI(AUTH_URI)) .appendHeader(CRT_HEADER, "request:" + authRequest) .build(); final ListenableFuture<Response> challengeFuture = dispatcher.request(request); final ListenableFuture<Response> tokenFuture = Futures.transform(challengeFuture, new AsyncFunction<Response, Response>() { @Override public ListenableFuture<Response> apply(@NotNull final Response response) throws Exception { checkStatus(response, 200); final String challenge = getHeader(response, CRT_HEADER, CHALLENGE_PREFIX); final String crtResponse = crtClient.createResponse(challenge); final HeliosRequest request = HeliosRequest.builder() .method("GET") .uri(new URI(AUTH_URI)) .appendHeader(CRT_HEADER, "response:" + crtResponse) .build(); return dispatcher.request(request); } }); return Futures.transform(tokenFuture, new Function<Response, String>() { @Nullable @Override public String apply(final Response response) { try { checkStatus(response, 200); final String t = getHeader(response, CRT_HEADER, TOKEN_PREFIX); final String token = "chap:" + t; tokenRef.set(token); return token; } catch (CrtAuthException e) { throw Throwables.propagate(e); } } }); } catch (URISyntaxException e) { <START> throw Throwables.propagate(e); <END> } }</code><technical_language>minor: is this try-catch wrap line is potentially throwing it</technical_language>

Target:
public ListenableFuture<String> renewAuthorizationHeader(final String ignored) { final String authRequest = CrtAuthClient.createRequest(username); final URI authUri; try { authUri = new URI(AUTH_URI); } catch (URISyntaxException e) { throw Throwables.propagate(e); } final HeliosRequest request = HeliosRequest.builder() .method("GET") .uri(authUri) .appendHeader(CRT_HEADER, "request:" + authRequest) .build(); final ListenableFuture<Response> challengeFuture = dispatcher.request(request); final ListenableFuture<Response> tokenFuture = Futures.transform(challengeFuture, new AsyncFunction<Response, Response>() { @Override public ListenableFuture<Response> apply(@NotNull final Response response) throws Exception { checkStatus(response, 200); final String challenge = getHeader(response, CRT_HEADER, CHALLENGE_PREFIX); final String crtResponse = crtClient.createResponse(challenge); final HeliosRequest request = HeliosRequest.builder() .method("GET") .uri(authUri) .appendHeader(CRT_HEADER, "response:" + crtResponse) .build(); return dispatcher.request(request); } }); return Futures.transform(tokenFuture, new Function<Response, String>() { @Nullable @Override public String apply(final Response response) { try { checkStatus(response, 200); final String token = "chap:" + getHeader(response, CRT_HEADER, TOKEN_PREFIX); tokenRef.set(token); return token; } catch (CrtAuthException e) { throw Throwables.propagate(e); } } }); }
Source:
<code>public RestrictedFunctionalityException(String message, RestrictedFunctionalityCallToAction... callToActions) { <START> super(message); <END> _callToActions = callToActions; }</code><technical_language>is a constructor explicitly disables stracktraces, dealing licensing code, I suggest one</technical_language>

Target:
public RestrictedFunctionalityException(String message, RestrictedFunctionalityCallToAction... callToActions) { super(message, null, true, false); _callToActions = callToActions; }
Source:
<code>public void run() { FileDialog dialog = new FileDialog(getViewSite().getShell()); dialog.setText(fDialogTitle); final String filePath = dialog.open(); if (filePath == null) { return; } Job job = new Job(Messages.CallStackView_ImportMappingJobName) { @Override public IStatus run(IProgressMonitor monitor) { fNameMapping = doMapping(new File(filePath)); synchronized (fBuildThreadMap) { ITmfTrace[] traces = TmfTraceManager.getTraceSet(fTrace); for (ITmfTrace trace : traces) { <START> BuildThread buildThread = fBuildThreadMap.remove(trace); <END> if (buildThread != null) { buildThread.cancel(); } buildThread = new BuildThread(trace, fTrace); fBuildThreadMap.put(trace, buildThread); buildThread.start(); } } return Status.OK_STATUS; } }; job.schedule(); }</code><technical_language>wrong name mapping. I select a file (executable text file), trace entry duplicated</technical_language>

Target:
public void run() { FileDialog dialog = new FileDialog(getViewSite().getShell()); dialog.setText(fDialogTitle); final String filePath = dialog.open(); if (filePath == null) { return; } Job job = new Job(Messages.CallStackView_ImportMappingJobName) { @Override public IStatus run(IProgressMonitor monitor) { fNameMapping = doMapping(new File(filePath)); Display.getDefault().asyncExec(new Runnable() { @Override public void run() { synchingToTime(fTimeGraphCombo.getTimeGraphViewer().getSelectionBegin()); } }); return Status.OK_STATUS; } }; job.schedule(); }
Source:
<code>protected void onBind() { super.onBind(); AbstractErrataListModel model = modelProvider.getModel(); changeListener = new IEventListener<PropertyChangedEventArgs>() { @Override public void eventRaised(Event<? extends PropertyChangedEventArgs> ev, Object sender, PropertyChangedEventArgs args) { getView().showErrataList(); } }; <START> model.addItemsChangeListener(changeListener); <END> getView().getErrataTable().addSelectionChangeHandler(new SelectionChangeEvent.Handler() { @Override public void onSelectionChange(SelectionChangeEvent event) { Erratum erratum = getView().getSelectedErratum(); if (erratum == null) { getView().setErrataDetailPanelVisibilty(false); } else { getView().updateErrataDetailFormPanel(erratum); getView().setErrataDetailPanelVisibilty(true); } } }); }</code><technical_language>modelProvider.getModel() inlined here</technical_language>

Target:
protected void onBind() { super.onBind(); changeListener = new IEventListener<PropertyChangedEventArgs>() { @Override public void eventRaised(Event<? extends PropertyChangedEventArgs> ev, Object sender, PropertyChangedEventArgs args) { getView().showErrataList(); } }; modelProvider.getModel().addItemsChangeListener(changeListener); getView().getErrataTable().addSelectionChangeHandler(new SelectionChangeEvent.Handler() { @Override public void onSelectionChange(SelectionChangeEvent event) { Erratum erratum = getView().getSelectedErratum(); if (erratum == null) { getView().setErrataDetailPanelVisibilty(false); } else { getView().updateErrataDetailFormPanel(erratum); getView().setErrataDetailPanelVisibilty(true); } } }); }
Source:
<code>protected IFile findFileInWorkspace(URI uri) { <START> if (!uri.isAbsolute()) <END> uri = URIUtil.makeAbsolute(uri, getWorkingDirectoryURI()); IFile f = ResourceLookup.selectFileForLocationURI(uri, fProject); if (f != null && f.isAccessible()) return f; return null; }</code><technical_language>Please bring braces back</technical_language>

Target:
protected IFile findFileInWorkspace(URI uri) { if (!uri.isAbsolute()) { uri = URIUtil.makeAbsolute(uri, getWorkingDirectoryURI()); } IFile f = ResourceLookup.selectFileForLocationURI(uri, fProject); if (f != null && f.isAccessible()) { return f; } return null; }
Source:
<code>private QualifyingSet evaluateFilterFunction(int streamIdx, QualifyingSet qualifyingSet) { boolean isFirstFunction = true; for (FilterFunction function : filterFunctionOrder[streamIdx]) { int[] channels = function.getInputChannels(); Block[] blocks = new Block[channels.length]; int numRows = qualifyingSet.getPositionCount(); for (int channelIdx = 0; channelIdx < channels.length; channelIdx++) { blocks[channelIdx] = makeFilterFunctionInputBlock(channelIdx, streamIdx, numRows, function); } if (filterResults == null || filterResults.length < numRows) { filterResults = new int[numRows + 100]; } StreamReader reader = sortedStreamReaders[streamIdx]; qualifyingSet = reader.getOrCreateOutputQualifyingSet(); long start = System.nanoTime(); int numHits = function.filter(new Page(numRows, blocks), filterResults, qualifyingSet.getOrCreateErrorSet()); function.updateStats(numRows, numHits, System.nanoTime() - start); if (reader.getFilter() == null && isFirstFunction) { qualifyingSet.copyFrom(reader.getInputQualifyingSet()); <START> int end = qualifyingSet.getEnd(); <END> qualifyingSet.setEnd(end); int[] inputNumbers = qualifyingSet.getMutableInputNumbers(numHits); System.arraycopy(filterResults, 0, inputNumbers, 0, numHits); } else { qualifyingSet.compactInputNumbers(filterResults, numHits); } reader.compactValues(filterResults, numRowsInResult, numHits); if (numHits == 0) { return qualifyingSet; } isFirstFunction = false; } return qualifyingSet; }</code><technical_language>end variable is once, hence, is inline it: qualifyingSet.setEnd(qualifyingSet.getEnd()); However, inlining shows variable statement necessary. remove these</technical_language>

Target:
private QualifyingSet evaluateFilterFunction(int streamIdx, QualifyingSet qualifyingSet) { boolean isFirstFunction = true; for (FilterFunction function : filterFunctionOrder[streamIdx]) { int[] channels = function.getInputChannels(); Block[] blocks = new Block[channels.length]; int numRows = qualifyingSet.getPositionCount(); for (int channelIdx = 0; channelIdx < channels.length; channelIdx++) { blocks[channelIdx] = makeFilterFunctionInputBlock(channelIdx, streamIdx, numRows, function); } if (filterResults == null || filterResults.length < numRows) { filterResults = new int[numRows + 100]; } StreamReader reader = sortedStreamReaders[streamIdx]; qualifyingSet = reader.getOrCreateOutputQualifyingSet(); long start = System.nanoTime(); int numHits = function.filter(new Page(numRows, blocks), filterResults, qualifyingSet.getOrCreateErrorSet()); function.updateStats(numRows, numHits, System.nanoTime() - start); if (reader.getFilter() == null && isFirstFunction) { qualifyingSet.copyFrom(reader.getInputQualifyingSet()); int[] inputNumbers = qualifyingSet.getMutableInputNumbers(numHits); System.arraycopy(filterResults, 0, inputNumbers, 0, numHits); } else { qualifyingSet.compactInputNumbers(filterResults, numHits); } reader.compactValues(filterResults, numRowsInResult, numHits); if (numHits == 0) { return qualifyingSet; } isFirstFunction = false; } return qualifyingSet; }
Source:
<code>private void removeIncludeExcludeWithHandler() { new PushButton("Remove...").click(); <START> new WaitUntil(new ShellIsAvailable("Confirmation")); <END> new DefaultShell("Confirmation"); new PushButton("OK").click(); }</code><technical_language>need for wait, DefaultShell wait</technical_language>

Target:
private void removeIncludeExcludeWithHandler() { new PushButton("Remove...").click(); new DefaultShell("Confirmation"); new PushButton("OK").click(); }
Source:
<code>public void testSwitchToFilter() { final Rectangle cellBounds = SWTBotUtils.getCellBounds(fTableBot.widget, ROW, TIMESTAMP_COLUMN); ImageHelper before = ImageHelper.grabImage(cellBounds); fTableBot.click(0, TIMESTAMP_COLUMN); fBot.text().typeText("00\n", 100); fTableBot.select(ROW - 1); ImageHelper after = ImageHelper.grabImage(cellBounds); fTableBot.click(0, 0); ImageHelper afterFilter = ImageHelper.grabImage(cellBounds); List<RGB> beforeLine = before.getPixelRow(2); List<RGB> afterLine = after.getPixelRow(2); List<RGB> afterFilterLine = afterFilter.getPixelRow(2); assertEquals(beforeLine.size(), afterLine.size()); assertEquals(beforeLine.size(), afterFilterLine.size()); for (int i = 0; i < beforeLine.size(); i++) { RGB afterFilterPixel = afterFilterLine.get(i); RGB beforePixel = beforeLine.get(i); RGB afterPixel = afterLine.get(i); assertEquals(beforePixel, afterFilterPixel); if (!afterPixel.equals(YELLOW)) { assertEquals(beforePixel, afterPixel); } else { assertNotEquals(YELLOW, beforePixel); } } assertEquals(beforeLine, afterFilterLine); assertNotEquals(afterLine, beforeLine); <START> fTableBot.click(0, <END> 0); }</code><technical_language>check this is in assert</technical_language>

Target:
public void testSwitchToFilter() { final Rectangle cellBounds = SWTBotUtils.getCellBounds(fTableBot.widget, ROW, TIMESTAMP_COLUMN); ImageHelper before = ImageHelper.grabImage(cellBounds); fTableBot.click(0, TIMESTAMP_COLUMN); fBot.text().typeText("00\n", 100); fTableBot.select(ROW - 1); ImageHelper after = ImageHelper.grabImage(cellBounds); fTableBot.click(0, 0); ImageHelper afterFilter = ImageHelper.grabImage(cellBounds); List<RGB> beforeLine = before.getPixelRow(2); List<RGB> afterLine = after.getPixelRow(2); List<RGB> afterFilterLine = afterFilter.getPixelRow(2); assertEquals(beforeLine.size(), afterLine.size()); assertEquals(beforeLine.size(), afterFilterLine.size()); for (int i = 0; i < beforeLine.size(); i++) { RGB afterFilterPixel = afterFilterLine.get(i); RGB beforePixel = beforeLine.get(i); RGB afterPixel = afterLine.get(i); assertEquals(beforePixel, afterFilterPixel); if (!afterPixel.equals(YELLOW)) { assertEquals(beforePixel, afterPixel); } else { assertNotEquals(YELLOW, beforePixel); } } assertEquals(beforeLine, afterFilterLine); assertNotEquals(afterLine, beforeLine); }
Source:
<code>public void deleteWorkflowByWorkflowItem(Context context, BasicWorkflowItem wi, EPerson e) throws SQLException, AuthorizeException, IOException { Item myitem = wi.getItem(); UUID itemID = myitem.getID(); Integer workflowID = wi.getID(); UUID collID = wi.getCollection().getID(); taskListItemService.deleteByWorkflowItem(context, wi); workflowItemService.deleteWrapper(context, wi); itemService.delete(context, myitem); <START> log.info(LogManager.getHeader(context, "delete_workflow", "workflow_item_id=" <END> + workflowID + "item_id=" + itemID + "collection_id=" + collID + "eperson_id=" + e.getID())); }</code><technical_language>Consider String.format()</technical_language>

Target:
public void deleteWorkflowByWorkflowItem(Context context, BasicWorkflowItem wi, EPerson e) throws SQLException, AuthorizeException, IOException { Item myitem = wi.getItem(); UUID itemID = myitem.getID(); Integer workflowID = wi.getID(); UUID collID = wi.getCollection().getID(); taskListItemService.deleteByWorkflowItem(context, wi); workflowItemService.deleteWrapper(context, wi); itemService.delete(context, myitem); log.info(LogManager.getHeader(context, "delete_workflow", String.format("workflow_item_id=%s " + "item_id=%s collection_id=%s eperson_id=%s", workflowID, itemID, collID, e.getID()))); }
Source:
<code>public Optional<InsightCard.Category> selectMarketingInsightToGenerate(final DateTime currentTime, final Set<InsightCard.Category> marketingSeenCategories, final Random random, final DateTime lastUpdate) { <START> final DateTime today = currentTime.withHourOfDay(0).withMinuteOfHour(0).withSecondOfMinute(0).withMillisOfSecond(0); END> final DateTime lastMarketingUpdate = lastUpdate.withHourOfDay(0).withMinuteOfHour(0).withSecondOfMinute(0).withMillisOfSecond(0); if (today == lastMarketingUpdate) { return Optional.absent(); } final Integer dayOfMonth = currentTime.getDayOfMonth(); LOGGER.debug("The day of the month is {}", dayOfMonth); switch (dayOfMonth) { case 1: case 4: case 7: case 10: case 13: case 16: case 19: final Optional<InsightCard.Category> pickedRandomInsight = pickRandomInsightCategory(marketingInsightPool, marketingSeenCategories, random); return pickedRandomInsight; } return Optional.absent(); }</code><technical_language>atStartOfDay() that</technical_language>

Target:
public Optional<InsightCard.Category> selectMarketingInsightToGenerate(final DateTime currentTime, final Set<InsightCard.Category> marketingSeenCategories, final Random random, final DateTime lastUpdate) { final DateTime today = currentTime.withTimeAtStartOfDay(); final DateTime lastMarketingUpdate = lastUpdate.withTimeAtStartOfDay(); if (today.isEqual(lastMarketingUpdate)) { return Optional.absent(); } final Integer dayOfMonth = currentTime.getDayOfMonth(); LOGGER.debug("The day of the month is {}", dayOfMonth); switch (dayOfMonth) { case 1: case 4: case 7: case 10: case 13: case 16: case 19: final Optional<InsightCard.Category> pickedRandomInsight = pickRandomInsightCategory(marketingInsightPool, marketingSeenCategories, random); return pickedRandomInsight; } return Optional.absent(); }
Source:
<code><START> public TimestampService createTimestampService(KeyValueService rawKvs, boolean initializeAsync) { <END> AtlasDbVersion.ensureVersionReported(); return new InMemoryTimestampService(); }</code><technical_language>Another place note boolean is unused</technical_language>

Target:
public TimestampService createTimestampService(KeyValueService rawKvs, boolean initializeAsync) { if (initializeAsync) { log.warn("Asynchronous initialization not implemented, will initialize synchronousy."); } AtlasDbVersion.ensureVersionReported(); return new InMemoryTimestampService(); }
Source:
<code>private boolean validate() { controlResult = executeQueryControl(); if (controlResult.getState() == State.TOO_MANY_ROWS) { testResult = new QueryResult(State.INVALID, null, null, null, null, ImmutableList.of()); return false; } if (controlResult.getState() != State.SUCCESS) { testResult = new QueryResult(State.INVALID, null, null, null, null, ImmutableList.of()); return true; } testResult = executeQueryTest(); if (controlResult.getState() != State.SUCCESS || testResult.getState() != State.SUCCESS) { return false; } if (!checkCorrectness) { return true; } boolean matches = resultsMatch(controlResult, testResult, precision); <START> <END> if (!matches && checkDeterministic) { return checkForDeterministicAndRerunTestQueriesIfNeeded(); } return matches; }</code><technical_language>Remove extra newline</technical_language>

Target:
private boolean validate() { controlResult = executeQueryControl(null); if (controlResult.getState() == State.TOO_MANY_ROWS) { testResult = new QueryResult(State.INVALID, null, null, null, null, ImmutableList.of()); return false; } if (controlResult.getState() != State.SUCCESS) { testResult = new QueryResult(State.INVALID, null, null, null, null, ImmutableList.of()); return true; } testResult = executeQueryTest(null); if (controlResult.getState() != State.SUCCESS || testResult.getState() != State.SUCCESS) { return false; } if (!checkCorrectness) { return true; } boolean matches = resultsMatch(controlResult, testResult, precision); if (!matches && checkDeterministic) { return checkForDeterministicAndRerunTestQueriesIfNeeded(); } return matches; }
Source:
<code>public void testSimple() throws Exception { final TreeMap<String, EntryType> expectedEntries = new TreeMap<>(); <START> expectedEntries.put("java/", EntryType.FOLDER); <END> expectedEntries.put("resources/", EntryType.FOLDER); assertEquals(expectedEntries,ffTree.resolveEntries("src/main")); }</code><technical_language>This is unexpected result, a look</technical_language>

Target:
public void testSimple() throws Exception { final TreeMap<String, EntryType> expectedEntries = new TreeMap<>(); expectedEntries.put("java/", EntryType.FOLDER); expectedEntries.put("resources/", EntryType.FOLDER); assertEquals(expectedEntries,ffTree.resolveEntries("src/main/")); }
Source:
<code>private ObjectId locateBlobObjectId() throws CoreException { try { final TreeWalk w = TreeWalk.forPath(db, path, commit.getTree()); if (w == null) throw new CoreException(new Status(IStatus.ERROR, path, NLS .bind(CoreText.CommitFileRevision_pathNotIn, commit <START> .getId()), null)); <END> return w.getObjectId(0); } catch (IOException e) { throw new CoreException(new Status(IStatus.ERROR, path, NLS.bind( CoreText.CommitFileRevision_errorLookingUpPath, commit .getId()), e)); } }</code><technical_language>parameter of Status is pluginId. pass path here</technical_language>

Target:
private ObjectId locateBlobObjectId() throws CoreException { try { final TreeWalk w = TreeWalk.forPath(db, path, commit.getTree()); if (w == null) throw new CoreException(Activator.error(NLS.bind( CoreText.CommitFileRevision_pathNotIn, commit.getId().name(), path), null)); return w.getObjectId(0); } catch (IOException e) { throw new CoreException(Activator.error(NLS.bind( CoreText.CommitFileRevision_errorLookingUpPath, commit .getId().name(), path), e)); } }
Source:
<code>protected void executeExtendedSynapseHandlerOnArtifactDeployment(String artifactName, String artifactType, String startTime) throws DeploymentException { List handlers = getSynapseEnvironment().getSynapseHandlers(); Iterator<SynapseHandler> iterator = handlers.iterator(); while (iterator.hasNext()) { SynapseHandler handler = iterator.next(); if ((handler instanceof AbstractExtendedSynapseHandler)) { if (!((AbstractExtendedSynapseHandler) handler). handleDeployArtifacts(artifactName, artifactType, startTime)) { <START> return; <END> } } } }</code><technical_language>do need return print logs</technical_language>

Target:
protected void executeExtendedSynapseHandlerOnArtifactDeployment(String artifactName, String artifactType, String startTime) throws DeploymentException { List handlers = getSynapseEnvironment().getSynapseHandlers(); Iterator<SynapseHandler> iterator = handlers.iterator(); while (iterator.hasNext()) { SynapseHandler handler = iterator.next(); if ((handler instanceof AbstractExtendedSynapseHandler)) { AbstractExtendedSynapseHandler abstractExtendedSynapseHandler = (AbstractExtendedSynapseHandler) handler; if (!abstractExtendedSynapseHandler.handleArtifactDeployment(artifactName, artifactType, startTime)) { log.warn("Synapse not executed in the artifact deployment in path"); } } } }
Source:
<code>public void handleCheckStateChangedEvent(Collection<ITmfTreeViewerEntry> entries) { cancelUpdate(); Iterable<TmfGenericTreeEntry> counterEntries = Iterables.filter(entries, TmfGenericTreeEntry.class); Collection<@NonNull Long> selectedIds = <START> Lists.newArrayList(Iterables.transform(counterEntries, <END> e -> e.getModel().getId())); if (!selectedIds.containsAll(fSelectedIds)) { clearContent(); } fSelectedIds = selectedIds; updateContent(); }</code><technical_language>Sets.newHashSet</technical_language>

Target:
public void handleCheckStateChangedEvent(Collection<ITmfTreeViewerEntry> entries) { cancelUpdate(); Iterable<TmfGenericTreeEntry> counterEntries = Iterables.filter(entries, TmfGenericTreeEntry.class); Collection<@NonNull Long> selectedIds = Sets.newHashSet(Iterables.transform(counterEntries, e -> e.getModel().getId())); if (!selectedIds.containsAll(fSelectedIds)) { clearContent(); } fSelectedIds = selectedIds; updateContent(); }
Source:
<code>public synchronized void addNode(Node node) { if (!PAResourceManagerProperties.RM_TOPOLOGY_ENABLED.getValueAsBoolean()) { return; } InetAddress host = node.getVMInformation().getInetAddress(); synchronized (topology) { if (topology.knownHost(host)) { logger.debug("The topology information has been already added for node " + node.getNodeInformation().getURL()); nodesOnHost.get(host).add(node); return; } } synchronized (node.getNodeInformation().getURL().intern()) { NodeSet toPing = new NodeSet(); synchronized (topology) { for (InetAddress h : nodesOnHost.keySet()) { toPing.add(nodesOnHost.get(h).iterator().next()); } } HashMap<InetAddress, Long> hostsTopology = null; <START> if (PAResourceManagerProperties.RM_TOPOLOGY_DISTANCE_ENABLED.isSet() && PAResourceManagerProperties.RM_TOPOLOGY_DISTANCE_ENABLED.getValueAsBoolean()) { <END> hostsTopology = pingNode(node, toPing); } synchronized (topology) { topology.addHostTopology(node.getVMInformation().getHostName(), host, hostsTopology); List<Node> nodesList = new LinkedList<>(); nodesList.add(node); nodesOnHost.put(node.getVMInformation().getInetAddress(), nodesList); } } }</code><technical_language>This condition put in a new method factorize code improve readability</technical_language>

Target:
public synchronized void addNode(Node node) { if (!PAResourceManagerProperties.RM_TOPOLOGY_ENABLED.getValueAsBoolean()) { return; } InetAddress host = node.getVMInformation().getInetAddress(); synchronized (topology) { if (topology.knownHost(host)) { logger.debug("The topology information has been already added for node " + node.getNodeInformation().getURL()); nodesOnHost.get(host).add(node); return; } } synchronized (node.getNodeInformation().getURL().intern()) { NodeSet toPing = new NodeSet(); synchronized (topology) { for (InetAddress h : nodesOnHost.keySet()) { toPing.add(nodesOnHost.get(h).iterator().next()); } } HashMap<InetAddress, Long> hostsTopology = null; if (PAResourceManagerProperties.RM_TOPOLOGY_DISTANCE_ENABLED.getValueAsBoolean()) { hostsTopology = pingNode(node, toPing); } synchronized (topology) { topology.addHostTopology(node.getVMInformation().getHostName(), host, hostsTopology); List<Node> nodesList = new LinkedList<>(); nodesList.add(node); nodesOnHost.put(node.getVMInformation().getInetAddress(), nodesList); } } }
Source:
<code><START> public static Set<Field> getAllFields() { <END> Set<Field> fields = new HashSet<>(); fields.addAll(EnumSet.allOf(IEEEField.class)); fields.addAll(EnumSet.allOf(InternalField.class)); fields.addAll(EnumSet.allOf(SpecialField.class)); fields.addAll(EnumSet.allOf(StandardField.class)); return fields; }</code><technical_language>I guess want show internal fields (e.g all) in dialog</technical_language>

Target:
private static Set<Field> getAllFields() { Set<Field> fields = new HashSet<>(); fields.addAll(EnumSet.allOf(IEEEField.class)); fields.addAll(EnumSet.allOf(InternalField.class)); fields.addAll(EnumSet.allOf(SpecialField.class)); fields.addAll(EnumSet.allOf(StandardField.class)); return fields; }
Source:
<code>private void createVolume() { populateDiskSnapshotsInfoFromStorage(); CreateVolumeContainerCommandParameters parameters = new CreateVolumeContainerCommandParameters( getParameters().getStoragePoolId(), getParameters().getDestDomain(), Guid.Empty, Guid.Empty, getParameters().getDestImageGroupId(), getParameters().getDestinationImageId(), getParameters().getDestinationFormat(), getParameters().getDescription(), getDiskImage().getSize(), <START> ImagesHandler.determineImageInitialSize(getDiskImage().getImage(), <END> getParameters().getDestinationFormat(), getParameters().getStoragePoolId(), getParameters() .getSrcDomain(), getParameters().getDestDomain(), getParameters().getImageGroupID())); parameters.setJobWeight(getParameters().getOperationsJobWeight().get(CopyStage.DEST_CREATION.name())); parameters.setParentCommand(getActionType()); parameters.setParentParameters(getParameters()); parameters.setEndProcedure(EndProcedure.COMMAND_MANAGED); runInternalAction(VdcActionType.CreateVolumeContainer, parameters); }</code><technical_language>this change incorrect. original code supposed calculate size needed for volumes (when performing collapse), while this consideration volume</technical_language>

Target:
private void createVolume() { populateDiskSnapshotsInfoFromStorage(); CreateVolumeContainerCommandParameters parameters = new CreateVolumeContainerCommandParameters( getParameters().getStoragePoolId(), getParameters().getDestDomain(), Guid.Empty, Guid.Empty, getParameters().getDestImageGroupId(), getParameters().getDestinationImageId(), getParameters().getDestinationFormat(), getParameters().getDescription(), getDiskImage().getSize(), ImagesHandler.determineTotalImageInitialSize(getDiskImage(), getParameters().getDestinationFormat(), getParameters().getDestDomain())); parameters.setJobWeight(getParameters().getOperationsJobWeight().get(CopyStage.DEST_CREATION.name())); parameters.setParentCommand(getActionType()); parameters.setParentParameters(getParameters()); parameters.setEndProcedure(EndProcedure.COMMAND_MANAGED); runInternalAction(VdcActionType.CreateVolumeContainer, parameters); }
Source:
<code>public ResponseEntity<ChallengeTemplateShowDto> get(@PathVariable Long id) { <START> return new ResponseEntity<>(service.findChallenge(id), HttpStatus.OK); <END> }</code><technical_language>challenge service returns a challengetemplate</technical_language>

Target:
public ResponseEntity<ChallengeTemplateShowDto> get(@PathVariable Long id) { return new ResponseEntity<>(challengeTemplateService.findByChallengeId(id), HttpStatus.OK); }
Source:
<code>private void discontinueExistingOrdersIfNecessary(Order order) { if (DISCONTINUE != order.getAction()) { return; } Order previousOrder = order.getPreviousOrder(); if (previousOrder != null) { stopOrder(previousOrder, aMomentBefore(order.getDateActivated())); return; } List<? extends Order> orders = getActiveOrders(order.getPatient(), order.getOrderType(), order.getCareSetting(), null); boolean isDrugOrderAndHasADrug = DrugOrder.class.isAssignableFrom(getActualType(order)) && ((DrugOrder) order).getDrug() != null; Order orderToBeDiscontinued = null; for (Order activeOrder : orders) { if (!getActualType(order).equals(getActualType(activeOrder))) { continue; } if (isDrugOrderAndHasADrug) { if(orderToBeDiscontinued==null){ orderToBeDiscontinued = checkDrugOrdersForDiscontinuing((DrugOrder) order, (DrugOrder) activeOrder); } } else if (activeOrder.getConcept().equals(order.getConcept())) { if(orderToBeDiscontinued==null){ orderToBeDiscontinued = activeOrder; }else{ throw new AmbiguousOrderException(); } } } <START> if(orderToBeDiscontinued!=null){ <END> order.setPreviousOrder(orderToBeDiscontinued); stopOrder(orderToBeDiscontinued, aMomentBefore(order.getDateActivated())); } }</code><technical_language>this i.e if clause</technical_language>

Target:
private void discontinueExistingOrdersIfNecessary(Order order) { if (DISCONTINUE != order.getAction()) { return; } Order previousOrder = order.getPreviousOrder(); if (previousOrder != null) { stopOrder(previousOrder, aMomentBefore(order.getDateActivated())); return; } List<? extends Order> orders = getActiveOrders(order.getPatient(), order.getOrderType(), order.getCareSetting(), null); boolean isDrugOrderAndHasADrug = DrugOrder.class.isAssignableFrom(getActualType(order)) && ((DrugOrder) order).getDrug() != null; Order orderToBeDiscontinued = null; for (Order activeOrder : orders) { if (!getActualType(order).equals(getActualType(activeOrder))) { continue; } if (isDrugOrderAndHasADrug) { if(orderToBeDiscontinued==null){ orderToBeDiscontinued = checkDrugOrdersForDiscontinuing((DrugOrder) order, (DrugOrder) activeOrder); }else{ throw new AmbiguousOrderException("Order.discontinuing.ambiguous.orders"); } } else if (activeOrder.getConcept().equals(order.getConcept())) { if(orderToBeDiscontinued==null){ orderToBeDiscontinued = activeOrder; }else{ throw new AmbiguousOrderException("Order.discontinuing.ambiguous.orders"); } } } if(orderToBeDiscontinued!=null){ order.setPreviousOrder(orderToBeDiscontinued); stopOrder(orderToBeDiscontinued, aMomentBefore(order.getDateActivated())); } }
Source:
<code><START> public void scheduleAll(final Project project, final String submitUser) <END> throws SchedulerException, ProjectManagerException { for (final Flow flow : project.getFlows()) { final String flowFileName = flow.getId() + ".flow"; final int latestFlowVersion = this.projectLoader .getLatestFlowVersion(flow.getProjectId(), flow .getVersion(), flowFileName); if (latestFlowVersion > 0) { final File tempDir = Files.createTempDir(); final File flowFile; try { flowFile = this.projectLoader .getUploadedFlowFile(project.getId(), project.getVersion(), flowFileName, latestFlowVersion, tempDir); final FlowTrigger flowTrigger = FlowLoaderUtils.getFlowTriggerFromYamlFile(flowFile); if (flowTrigger != null) { final String projectJson = FlowUtils.toJson(project); final Map<String, Object> contextMap = ImmutableMap .of(FlowTriggerQuartzJob.SUBMIT_USER, submitUser, FlowTriggerQuartzJob.FLOW_TRIGGER, flowTrigger, FlowTriggerQuartzJob.FLOW_ID, flow.getId(), FlowTriggerQuartzJob.FLOW_VERSION, latestFlowVersion, FlowTriggerQuartzJob.PROJECT, projectJson); logger.info("scheduling flow " + flow.getProjectId() + "." + flow.getId()); this.scheduler .registerJob(flowTrigger.getSchedule().getCronExpression(), new QuartzJobDescription (FlowTriggerQuartzJob.class, generateGroupName(flow), contextMap)); } } catch (final Exception ex) { logger.error("error in getting flow file", ex); } finally { FlowLoaderUtils.cleanUpDir(tempDir); } } } }</code><technical_language>this method is called scheduleAll</technical_language>

Target:
public void scheduleAll(final Project project, final String submitUser) throws SchedulerException, ProjectManagerException { for (final Flow flow : project.getFlows()) { if (flow.isEmbeddedFlow()) { continue; } final String flowFileName = flow.getId() + ".flow"; final int latestFlowVersion = this.projectLoader .getLatestFlowVersion(flow.getProjectId(), flow .getVersion(), flowFileName); if (latestFlowVersion > 0) { final File tempDir = Files.createTempDir(); final File flowFile; try { flowFile = this.projectLoader .getUploadedFlowFile(project.getId(), project.getVersion(), flowFileName, latestFlowVersion, tempDir); final FlowTrigger flowTrigger = FlowLoaderUtils.getFlowTriggerFromYamlFile(flowFile); if (flowTrigger != null) { final String projectJson = FlowUtils.toJson(project); final Map<String, Object> contextMap = ImmutableMap .of(FlowTriggerQuartzJob.SUBMIT_USER, submitUser, FlowTriggerQuartzJob.FLOW_TRIGGER, flowTrigger, FlowTriggerQuartzJob.FLOW_ID, flow.getId(), FlowTriggerQuartzJob.FLOW_VERSION, latestFlowVersion, FlowTriggerQuartzJob.PROJECT, projectJson); logger.info("scheduling flow " + flow.getProjectId() + "." + flow.getId()); this.scheduler .registerJob(flowTrigger.getSchedule().getCronExpression(), new QuartzJobDescription (FlowTriggerQuartzJob.class, generateGroupName(flow), contextMap)); } } catch (final Exception ex) { logger.error("error in getting flow file", ex); } finally { FlowLoaderUtils.cleanUpDir(tempDir); } } } }
Source:
<code>private Symbol getField(ExpressionTree tree) { if (tree.is(Kind.IDENTIFIER)) { IdentifierTree identifier = (IdentifierTree) tree; Symbol reference = getSemanticModel().getReference(identifier); if (reference != null && reference.owner().isKind(Symbol.TYP)) { return reference; } } else if (tree.is(Kind.MEMBER_SELECT)) { MemberSelectExpressionTree mse = (MemberSelectExpressionTree) tree; <START> if (isField(mse.expression())) { <END> return getField(mse.identifier()); } } return null; }</code><technical_language>checking expression of MemberSelectExpression</technical_language>

Target:
private Symbol getField(ExpressionTree tree) { if (tree.is(Kind.IDENTIFIER)) { Symbol reference = getSemanticModel().getReference((IdentifierTree) tree); if (reference != null && reference.owner().isKind(Symbol.TYP)) { return reference; } } else if (tree.is(Kind.MEMBER_SELECT)) { MemberSelectExpressionTree mse = (MemberSelectExpressionTree) tree; if (isField(mse)) { return getField(mse.identifier()); } } return null; }
Source:
<code>private void ensureFormController() { if (this.formController == null) { <START> Timber.w("Null formController"); <END> this.formController = Collect.getInstance().getFormController(); } }</code><technical_language>wondering if want add more logging here. great try get detail this happens</technical_language>

Target:
private void ensureFormController() { if (this.formController == null) { Timber.e(new IllegalStateException("ensureFormController called before formLoaded")); this.formController = Collect.getInstance().getFormController(); } }
Source:
<code>ListenableFuture<Void> setZoomRatio(float ratio) { synchronized (mActiveLock) { if (!mIsActive) { throw new IllegalStateException("Camera is not active."); } ListenableFuture<Void> result = setZoomRatioInternal(ratio, true); if (ratio > getMaxZoomRatio().getValue() || <START> (ratio <END> < getMinZoomRatio().getValue())) { synchronized (mCompleterLock) { mPendingZoomRatioCompleter = null; mPendingZoomCropRegion = null; } String outOfRangeDesc = "Requested zoomRatio " + ratio + " is not within valid " + "range [" + getMinZoomRatio().getValue() + " , " + getMaxZoomRatio().getValue() + "]"; result = Futures.immediateFailedFuture( new CameraControl.ArgumentOutOfRangeException(outOfRangeDesc)); Log.w(TAG, outOfRangeDesc); } return result; } }</code><technical_language>Unnecessary parentheses</technical_language>

Target:
ListenableFuture<Void> setZoomRatio(float ratio) { synchronized (mActiveLock) { if (!mIsActive) { return Futures.immediateFailedFuture( new OperationCanceledException("Camera is not active.")); } ListenableFuture<Void> result = setZoomRatioInternal(ratio, true); if (ratio > getMaxZoomRatio().getValue() || ratio < getMinZoomRatio().getValue()) { synchronized (mCompleterLock) { mPendingZoomRatioCompleter = null; mPendingZoomCropRegion = null; } String outOfRangeDesc = "Requested zoomRatio " + ratio + " is not within valid " + "range [" + getMinZoomRatio().getValue() + " , " + getMaxZoomRatio().getValue() + "]"; result = Futures.immediateFailedFuture( new CameraControl.ArgumentOutOfRangeException(outOfRangeDesc)); Log.w(TAG, outOfRangeDesc); } return result; } }
Source:
<code>void expectNext(T expected, long timeoutMillis) throws InterruptedException { T received = elements.next(timeoutMillis, String.format("Subscriber $sub did not call `registerOnNext(%s)`", expected)); <START> if (received != expected) { <END> env.flop(String.format("Subscriber $sub called `registerOnNext($received)` rather than `registerOnNext(%s)`", expected)); } }</code><technical_language>== != in Scala is .equals (with proper null handling), switched .equals reference equality</technical_language>

Target:
void expectNext(T expected, long timeoutMillis) throws InterruptedException { T received = elements.next(timeoutMillis, String.format("Subscriber %s did not call `registerOnNext(%s)`", sub(), expected)); if (!received.equals(expected)) { env.flop(String.format("Subscriber %s called `registerOnNext(%s)` rather than `registerOnNext(%s)`", sub(), received, expected)); } }
Source:
<code>public static Archive createDeployment() { WebArchive archive = ShrinkWrap.create(ZipImporter.class, "genie-web.war") <START> .importFrom(new File("../genie-web/build/libs/genie-web-0.22-SNAPSHOT.war")) <END> .as(WebArchive.class); archive.setWebXML("web.xml"); archive.addAsResource("config.properties"); return archive; }</code><technical_language>@cfieber thinking pass a property build.gradle in maven local resolver here</technical_language>

Target:
public static Archive createDeployment() { WebArchive archive = ShrinkWrap.create(ZipImporter.class, "genie-web.war") .importFrom(resolveTestWar("../genie-web/")) .as(WebArchive.class); archive.setWebXML("web.xml"); archive.addAsResource("config.properties"); return archive; }
Source:
<code>private void closeSingleFile() throws IOException { headerOut.close(); final long numBytesWritten = headerOut.getCount() + valuesOut.getCount(); Preconditions.checkState( headerOut.getCount() == (numWritten * 4), "numWritten[%s] number of rows should have [%s] bytes written to headerOut, had[%s]", numWritten, numWritten * 4, headerOut.getCount() ); Preconditions.checkState( numBytesWritten < fileSizeLimit, "Wrote[%s] bytes, which is too many.", numBytesWritten ); try (OutputStream metaOut = ioPeon.makeOutputStream(makeFilename("meta"))) { metaOut.write(0x1); metaOut.write(objectsSorted ? 0x1 : 0x0); <START> metaOut.write(Ints.toByteArray(Ints.saturatedCast(numBytesWritten + 4))); <END> metaOut.write(Ints.toByteArray(Ints.saturatedCast(numWritten))); } }</code><technical_language>checkedCast()</technical_language>

Target:
private void closeSingleFile() throws IOException { headerOut.close(); final long numBytesWritten = headerOut.getCount() + valuesOut.getCount(); Preconditions.checkState( headerOut.getCount() == (numWritten * 4), "numWritten[%s] number of rows should have [%s] bytes written to headerOut, had[%s]", numWritten, numWritten * 4, headerOut.getCount() ); Preconditions.checkState( numBytesWritten < fileSizeLimit, "Wrote[%s] bytes, which is too many.", numBytesWritten ); try (OutputStream metaOut = ioPeon.makeOutputStream(makeFilename("meta"))) { metaOut.write(GenericIndexed.VERSION_ONE); metaOut.write(objectsSorted ? 0x1 : 0x0); metaOut.write(Ints.toByteArray(Ints.checkedCast(numBytesWritten + 4))); metaOut.write(Ints.toByteArray(Ints.checkedCast(numWritten))); } }
Source:
<code>public SystemStreamPartitionGrouper getSystemStreamPartitionGrouper(Config config) { int taskCount; int containerId = 0; boolean isPassthroughJobCoordinator = false; String jobCoordinatorFactoryClassName = config.get(JobCoordinatorConfig.JOB_COORDINATOR_FACTORY); <START> if (jobCoordinatorFactoryClassName != null && !jobCoordinatorFactoryClassName.isEmpty()) { <END> if (jobCoordinatorFactoryClassName.equals(ZK_JOB_COORDINATOR_FACTORY)) { taskCount = getNumProcessors(config); } else if (jobCoordinatorFactoryClassName.equals(PASSTHROUGH_JOB_COORDINATOR_FACTORY)) { if (config.get(JobConfig.PROCESSOR_ID()) == null) { throw new ConfigException("Could not find " + JobConfig.PROCESSOR_ID() + " in Config!"); } isPassthroughJobCoordinator = true; containerId = config.getInt(JobConfig.PROCESSOR_ID()); taskCount = 1; } else { throw new ConfigException("AllSspToSingleTaskGrouperFactory is not yet supported with " + jobCoordinatorFactoryClassName); } } else { taskCount = config.getInt(YARN_CONTAINER_COUNT); } Validate.isTrue(taskCount > 0, "Task count cannot be <= 0"); return new AllSspToSingleTaskGrouper(isPassthroughJobCoordinator, containerId, taskCount); }</code><technical_language>Ultimately, section is find Set&lt;String&gt; processorNames. I suggest fold this a single method getProcessorNames() pass grouper's constructor</technical_language>

Target:
public SystemStreamPartitionGrouper getSystemStreamPartitionGrouper(Config config) { if (!(new TaskConfigJava(config).getBroadcastSystemStreams().isEmpty())) { throw new ConfigException("The job configured with AllSspToSingleTaskGrouper cannot have broadcast streams."); } try { String jobCoordinatorFactoryClassName = new JobCoordinatorConfig(config).getJobCoordinatorFactoryClassName(); JobCoordinator jc = Util.<JobCoordinatorFactory>getObj(jobCoordinatorFactoryClassName).getJobCoordinator(config); return new AllSspToSingleTaskGrouper(jc.getProcessorNames()); } catch (ConfigException ex) { LOG.info("Guessing cluster-based jobCoordinator(Yarn)."); final Set<String> processorNames = new HashSet<>(); IntStream.range(0, new JobConfig(config).getContainerCount()).forEach(i -> processorNames.add(String.valueOf(i))); return new AllSspToSingleTaskGrouper(processorNames); } }
Source:
<code>private void writeProjectFile(File intoDir, String projectName, String sourcePath, String fileName) throws IOException { InputStream sourceInputStream = InitCommand.class.getClassLoader().getResourceAsStream(sourcePath); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(sourceInputStream, StandardCharsets.UTF_8)); File projectFile = new File(intoDir, fileName); PrintWriter writer = new PrintWriter(projectFile, "UTF-8"); String line; try { while ((line = bufferedReader.readLine()) != null) { writer.println(line.replace("{{projectName}}", projectName)); } <START> } finally { <END> writer.close(); bufferedReader.close(); } }</code><technical_language>sure, a "try resources" here</technical_language>

Target:
private void writeProjectFile(File intoDir, String projectName, String sourcePath, String fileName) throws IOException { InputStream sourceInputStream = InitCommand.class.getClassLoader().getResourceAsStream(sourcePath); File projectFile = new File(intoDir, fileName); String line; try ( BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(sourceInputStream, StandardCharsets.UTF_8)); PrintWriter writer = new PrintWriter(projectFile, "UTF-8")) { while ((line = bufferedReader.readLine()) != null) { writer.println(line.replace("{{projectName}}", projectName)); } } }