auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void doCopyRetry(FileSystem sourceFs, List<ReplChangeManager.FileInfo> srcFileList, FileSystem destinationFs, Path destination, boolean useRegularCopy) throws IOException, LoginException { int repeat = 0; boolean isCopyError; List<Path> pathList = Lists.transform(srcFileList, ReplChangeManager.FileInfo::getEffectivePath); while (!pathList.isEmpty() && (repeat < MAX_COPY_RETRY)) { LOG.info("Attempt: " + (repeat+1) + ". Copying files: " + pathList); try { isCopyError = false; doCopyOnce(sourceFs, pathList, destinationFs, destination, useRegularCopy); } catch (IOException e) { if (!(e instanceof FileNotFoundException)) { LOG.info(" File operation failed with error : " + e.getMessage()); sourceFs = pathList.get(0).getFileSystem(hiveConf); destinationFs = destination.getFileSystem(hiveConf); } isCopyError = true; } <START> pathList = getFilesToRetry(sourceFs, srcFileList, destinationFs, destination, isCopyError); <END> repeat++; } if (!pathList.isEmpty()) { LOG.error("File copy failed even after several attempts. Files list: " + srcFileList); throw new IOException("File copy failed even after several attempts."); } }</code><technical_language>Need catch IOException getFilesToRetry throw this exception for NN failures need retry</technical_language>

Target:
private void doCopyRetry(FileSystem sourceFs, List<ReplChangeManager.FileInfo> srcFileList, FileSystem destinationFs, Path destination, boolean useRegularCopy) throws IOException, LoginException { int repeat = 0; boolean isCopyError = false; List<Path> pathList = Lists.transform(srcFileList, ReplChangeManager.FileInfo::getEffectivePath); while (!pathList.isEmpty() && (repeat < MAX_COPY_RETRY)) { try { if (repeat > 0) { pathList = getFilesToRetry(sourceFs, srcFileList, destinationFs, destination, isCopyError); if (pathList.isEmpty()) { break; } } LOG.info("Attempt: " + (repeat+1) + ". Copying files: " + pathList); isCopyError = true; doCopyOnce(sourceFs, pathList, destinationFs, destination, useRegularCopy); isCopyError = false; } catch (IOException e) { LOG.info("file operation failed", e); if (repeat >= (MAX_COPY_RETRY - 1)) { break; } if (!(e instanceof FileNotFoundException)) { int sleepTime = FileUtils.getSleepTime(repeat); LOG.info("Sleep for " + sleepTime + " milliseconds before retry " + (repeat+1)); try { Thread.sleep(sleepTime); } catch (InterruptedException timerEx) { LOG.info("sleep interrupted", timerEx.getMessage()); } FileSystem.closeAllForUGI(Utils.getUGI()); sourceFs = pathList.get(0).getFileSystem(hiveConf); destinationFs = destination.getFileSystem(hiveConf); } } repeat++; } if (!pathList.isEmpty()) { LOG.error("File copy failed even after several attempts. Files list: " + pathList); throw new IOException("File copy failed even after several attempts."); } }
Source:
<code>public long forceNext() { long l = longs.incrementAndGet(INDEX_HEAD); <START> if (((l >> 3) << 3) == l && concurrentInvocations() > 10) { <END> concurrencyDetection.onDetected(); } return l; }</code><technical_language>minor: QuickMath.modPowerOfTwo(l, 8) == 0 instead of ((l >> 3) << 3) == l, more readable. I misread this ((l >> 3) << 3) == 1 initially (so 1 instead of small L) get means</technical_language>

Target:
public long forceNext() { long l = longs.incrementAndGet(INDEX_HEAD); if (modPowerOfTwo(l, MOD) == 0 && concurrentInvocations() > MAX_CONCURRENT_CALLS) { concurrencyDetection.onDetected(); } return l; }
Source:
<code>public boolean needsSequentialWriting() { <START> return !vfsList.get(0).getCapabilities().contains(Capabilities.PARALLEL_WRITE); <END> }</code><technical_language>capabilities here</technical_language>

Target:
public boolean needsSequentialWriting() { return !capabilities.contains(Capabilities.PARALLEL_WRITE); }
Source:
<code>private static NewIssueLocation locationForIssue(InputFile inputFile, HtmlIssue issue, NewIssue newIssue) { NewIssueLocation location = newIssue.newLocation() .on(inputFile) .message(issue.message()); Integer line = issue.line(); if (issue.startColumn() != null) { <START> location.at(inputFile.newRange(issue.line(), issue.startColumn(), issue.endLine(), issue.endColumn())); <END> } else if (line != null) { location.at(inputFile.selectLine(line)); } return location; }</code><technical_language>Do assume if startColumn is null, endLine endColumn either? is fine null? If case I check them</technical_language>

Target:
private static NewIssueLocation locationForIssue(InputFile inputFile, HtmlIssue issue, NewIssue newIssue) { NewIssueLocation location = newIssue.newLocation() .on(inputFile) .message(issue.message()); Integer line = issue.line(); if (issue instanceof PreciseHtmlIssue) { PreciseHtmlIssue preciseHtmlIssue = (PreciseHtmlIssue) issue; location.at(inputFile.newRange(issue.line(), preciseHtmlIssue.startColumn(), preciseHtmlIssue.endLine(), preciseHtmlIssue.endColumn())); } else if (line != null) { location.at(inputFile.selectLine(line)); } return location; }
Source:
<code>public FbChain(final Iterable<Fallback> fallbacks) { super( new Fallback() { @Override public Opt<Response> route(final RqFallback req) throws IOException { Opt<Response> rsp = new Opt.Empty<Response>(); for (final Fallback fbk : fallbacks) { final Opt<Response> opt = fbk.route(req); if (opt.has()) { <START> rsp = new Opt.Single<Response>(opt.get()); <END> break; } } return rsp; } } ); }</code><technical_language>@ekondrashev rsp = opt</technical_language>

Target:
public FbChain(final Iterable<Fallback> fallbacks) { super( new Fallback() { @Override public Opt<Response> route(final RqFallback req) throws IOException { Opt<Response> rsp = new Opt.Empty<Response>(); for (final Fallback fbk : fallbacks) { final Opt<Response> opt = fbk.route(req); if (opt.has()) { rsp = opt; break; } } return rsp; } } ); }
Source:
<code>protected void executeCommand() { final List<LUNs> lunsFromVgInfo = (List<LUNs>) runVdsCommand(VDSCommandType.GetVGInfo, new GetVGInfoVDSCommandParameters(getVds().getId(), getStorageDomain().getStorage())).getReturnValue(); final List<LUNs> lunsFromDb = getLunDao().getAllForVolumeGroup(getStorageDomain().getStorage()); Map<Consumer<List<LUNs>>, List<LUNs>> lunsToUpdateInDb = getLunsToUpdateInDb(lunsFromVgInfo, lunsFromDb); <START> Boolean dbShouldBeUpdated <END> = lunsToUpdateInDb.containsKey(updateExistingLuns) || lunsToUpdateInDb.containsKey(saveNewLuns); if (dbShouldBeUpdated) { TransactionSupport.executeInNewTransaction(() -> { updateLunsInDb(lunsToUpdateInDb); refreshLunsConnections(lunsFromVgInfo); cleanupLunsFromDb(lunsFromVgInfo, lunsFromDb); return null; }); } setSucceeded(true); }</code><technical_language>a java.lang.Boolean a primitive boolean</technical_language>

Target:
protected void executeCommand() { final List<LUNs> lunsFromVgInfo = (List<LUNs>) runVdsCommand(VDSCommandType.GetVGInfo, new GetVGInfoVDSCommandParameters(getVds().getId(), getStorageDomain().getStorage())).getReturnValue(); final List<LUNs> lunsFromDb = getLunDao().getAllForVolumeGroup(getStorageDomain().getStorage()); Map<Consumer<List<LUNs>>, List<LUNs>> lunsToUpdateInDb = getLunsToUpdateInDb(lunsFromVgInfo, lunsFromDb); boolean dbShouldBeUpdated = lunsToUpdateInDb.containsKey(updateExistingLuns) || lunsToUpdateInDb.containsKey(saveNewLuns); if (dbShouldBeUpdated) { TransactionSupport.executeInNewTransaction(() -> { updateLunsInDb(lunsToUpdateInDb); refreshLunsConnections(lunsFromVgInfo); cleanupLunsFromDb(lunsFromVgInfo, lunsFromDb); return null; }); } setSucceeded(true); }
Source:
<code>public void modifyAST(IIndex index, IMarker marker) { IASTTranslationUnit ast; try { ITranslationUnit tu = getTranslationUnitViaEditor(marker); ast = tu.getAST(index, ITranslationUnit.AST_SKIP_INDEXED_HEADERS); } catch (CoreException e) { CheckersUiActivator.log(e); return; } IASTNode astNode = null; if (isCodanProblem(marker)) { astNode = getASTNodeFromMarker(marker, ast); } if (astNode == null || !(astNode instanceof IASTCastExpression)) { return; } ASTRewrite r = ASTRewrite.create(ast); INodeFactory factory = ast.getASTNodeFactory(); IASTCastExpression oldcast = (IASTCastExpression) astNode; IASTCastExpression newcast = factory.newCastExpression(getCastType(), oldcast.getTypeId().copy(CopyStyle.withLocations), oldcast.getOperand().copy(CopyStyle.withLocations)); r.replace(oldcast, newcast, null); Change c = r.rewriteAST(); <START> try { <END> c.perform(new NullProgressMonitor()); } catch (CoreException e) { CheckersUiActivator.log(e); return; } try { marker.delete(); } catch (CoreException e) { CheckersUiActivator.log(e); } }</code><technical_language>merge try/catch below</technical_language>

Target:
public void modifyAST(IIndex index, IMarker marker) { IASTTranslationUnit ast; try { ITranslationUnit tu = getTranslationUnitViaEditor(marker); ast = tu.getAST(index, ITranslationUnit.AST_SKIP_INDEXED_HEADERS); } catch (CoreException e) { CheckersUiActivator.log(e); return; } IASTNode astNode = null; if (isCodanProblem(marker)) { astNode = getASTNodeFromMarker(marker, ast); } if (astNode == null || !(astNode instanceof IASTCastExpression)) { return; } ASTRewrite r = ASTRewrite.create(ast); INodeFactory factory = ast.getASTNodeFactory(); IASTCastExpression oldcast = (IASTCastExpression) astNode; IASTCastExpression newcast = factory.newCastExpression(getCastType(), oldcast.getTypeId().copy(CopyStyle.withLocations), oldcast.getOperand().copy(CopyStyle.withLocations)); r.replace(oldcast, newcast, null); Change c = r.rewriteAST(); try { c.perform(new NullProgressMonitor()); marker.delete(); } catch (CoreException e) { CheckersUiActivator.log(e); } }
Source:
<code>synchronized public void onExternalViewChange(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) { List<String> newSegments = new ArrayList<>(); for (String onlineSegment : onlineSegments) { <START> if (!_segmentToTimeRangeMSCache.containsKey(onlineSegment)) { <END> newSegments.add(onlineSegment); } } List<String> newSegmentZKMetadataPaths = new ArrayList<>(); for (String segment: newSegments) { newSegmentZKMetadataPaths.add(_segmentZKMetadataPathPrefix + segment); } List<ZNRecord> znRecords = _propertyStore.get(newSegmentZKMetadataPaths, null, AccessOption.PERSISTENT, true); for (int i = 0; i < newSegments.size(); i++) { String segment = newSegments.get(i); Interval range = extractTimeRangeMSFromSegmentZKMetaZNRecord(segment, znRecords.get(i)); _segmentToTimeRangeMSCache.put(segment, range); } _segmentToTimeRangeMSCache.keySet().retainAll(onlineSegments); _timeRangeMSToSegmentSearchTree = new IntervalST<String>(_segmentToTimeRangeMSCache); }</code><technical_language>@snleee This is handled API refreshSegment()</technical_language>

Target:
public synchronized void onExternalViewChange(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) { for (String segment : onlineSegments) { _intervalMap.computeIfAbsent(segment, k -> extractIntervalFromSegmentZKMetaZNRecord(k, _propertyStore.get(_segmentZKMetadataPathPrefix + k, null, AccessOption.PERSISTENT))); } _intervalMap.keySet().retainAll(onlineSegments); _intervalTree = new IntervalTree<>(_intervalMap); }
Source:
<code>private TracingContext traceToMap(Map<String, Object> map) { <START> long startParse = System.nanoTime(); <END> return () -> { long now = System.nanoTime(); long duration = now - startParse; long startOffset = now - startRequestNanos; map.put("startOffset", startOffset); map.put("duration", duration); }; }</code><technical_language>wants start startPhase if generic</technical_language>

Target:
private TracingContext traceToMap(Map<String, Object> map) { long start = System.nanoTime(); return () -> { long now = System.nanoTime(); long duration = now - start; long startOffset = now - startRequestNanos; map.put("startOffset", startOffset); map.put("duration", duration); }; }
Source:
<code>public void testIllegalMinMax() { try { new FixedDoubleHistogram(-200, 3.0, 3.0); fail("exception expected"); } catch (IllegalArgumentException e) { <START> assertTrue(e.getMessage().contains("bucketCount")); <END> } }</code><technical_language>nit: chance message assertion more specific? :)</technical_language>

Target:
public void testIllegalMinMax() { try { new FixedDoubleHistogram(200, 3.0, 3.0); fail("exception expected"); } catch (IllegalArgumentException e) { assertTrue(e.getMessage().contains("min")); assertTrue(e.getMessage().contains("must be smaller than")); } }
Source:
<code>public List<Modification> latestModification(File baseDir, final SubprocessExecutionContext execCtx) { <START> P4Client p4 = getP4(baseDir, false); <END> return p4.latestChange(); }</code><technical_language>do right? public List<Modification> latestModification(File baseDir, final SubprocessExecutionContext execCtx) { P4Client p4 = getP4(execCtx.isServer() ? baseDir: workingdir(baseDir)); return p4.latestChange(); }</technical_language>

Target:
public List<Modification> latestModification(File baseDir, final SubprocessExecutionContext execCtx) { P4Client p4 = getP4(execCtx.isServer() ? baseDir : workingdir(baseDir)); return p4.latestChange(); }
Source:
<code>public void putJobCompletedNotification() throws IOException, SignatureException { UUID notificationUUID = null; try { final PutJobCompletedNotificationRegistrationSpectraS3Response response = client .putJobCompletedNotificationRegistrationSpectraS3( new PutJobCompletedNotificationRegistrationSpectraS3Request("test@test.test")); notificationUUID = response.getJobCompletedNotificationRegistrationResult().getId(); assertThat(response.getStatusCode(), is(201)); } finally { client.deleteJobCompletedNotificationRegistrationSpectraS3( <START> new DeleteJobCompletedNotificationRegistrationSpectraS3Request(notificationUUID)); <END> } }</code><technical_language>check notificationUUID is null</technical_language>

Target:
public void putJobCompletedNotification() throws IOException, SignatureException { UUID notificationUUID = null; try { final PutJobCompletedNotificationRegistrationSpectraS3Response response = client .putJobCompletedNotificationRegistrationSpectraS3( new PutJobCompletedNotificationRegistrationSpectraS3Request("test@test.test")); notificationUUID = response.getJobCompletedNotificationRegistrationResult().getId(); assertThat(response.getStatusCode(), is(201)); } finally { if (notificationUUID != null) { client.deleteJobCompletedNotificationRegistrationSpectraS3( new DeleteJobCompletedNotificationRegistrationSpectraS3Request(notificationUUID)); } } }
Source:
<code>public static Pair<Boolean, String> checkFingerPrint(String expected, PublicKey key) throws Exception { if (key == null) { return null; } if (expected == null) { return new Pair<>(false, getFingerPrint(key)); <START> } <END> String comps[] = expected.split(":", 2); DigestFactory factory; if (comps[0].length() > 2) { factory = BuiltinDigests.fromString(comps[0]); if (factory == null) { return new Pair<>(false, getFingerPrint(key)); } } else { factory = BuiltinDigests.md5; expected = "MD5:" + expected; } String fingerprint = getFingerPrint(factory, key); return new Pair<>(expected.equals(fingerprint), fingerprint); }</code><technical_language>java if (GenericUtils.isEmpty(expected)) { return new Pair<>(false, getFingerPrint(key)); }</technical_language>

Target:
public static Pair<Boolean, String> checkFingerPrint(String expected, PublicKey key) throws Exception { if (key == null) { return null; } if (GenericUtils.isEmpty(expected)) { return new Pair<>(false, getFingerPrint(key)); } String comps[] = GenericUtils.trimToEmpty(expected).split(":", 2); if (GenericUtils.length(comps) < 2) { return new Pair<>(false, getFingerPrint(key)); } DigestFactory factory; if (comps[0].length() > 2) { factory = BuiltinDigests.fromString(comps[0]); if (factory == null) { return new Pair<>(false, getFingerPrint(key)); } expected = comps[0].toUpperCase() + ":" + comps[1]; } else { factory = BuiltinDigests.md5; expected = factory.getName().toUpperCase() + ":" + expected; } String fingerprint = getFingerPrint(factory, key); boolean matches = BuiltinDigests.md5.getName().equals(factory.getName()) ? expected.equalsIgnoreCase(fingerprint) : expected.equals(fingerprint); return new Pair<>(matches, fingerprint); }
Source:
<code>private boolean isValidationNecessaryOnReads(TableReference tableRef) { <START> return isValidationNecessary(tableRef) && validateLocksOnReads; <END> }</code><technical_language>premature, if in usage validateLocksOnReads is false, flipping arguments sense</technical_language>

Target:
private boolean isValidationNecessaryOnReads(TableReference tableRef) { return validateLocksOnReads && isValidationNecessary(tableRef); }
Source:
<code>public Trader(String name, double cashInHand) { <START> super(); <END> this.name = name; this.cashInHand = cashInHand; this.stocksOwned = new ArrayList<Order>(); this.ordersPlaced = new ArrayList<Order>(); }</code><technical_language>need super</technical_language>

Target:
public Trader(String name, double cashInHand) { this.name = name; this.cashInHand = cashInHand; this.stocksOwned = new ArrayList<Order>(); this.ordersPlaced = new ArrayList<Order>(); }
Source:
<code>public boolean isEnabled() { GitHistoryPage page = getPage(); if (page == null) return false; String head; try { head = page.getInputInternal().getRepository().getFullBranch(); } catch (IOException e) { <START> head = null; <END> } IStructuredSelection sel = getSelection(page); if (sel.size() != 1) return false; Object o = sel.getFirstElement(); if (!(o instanceof PlotCommit)) return false; PlotCommit commit = (PlotCommit) o; int refCount = commit.getRefCount(); for (int i = 0; i < refCount; i++) { String refName = commit.getRef(i).getName(); if (refName.equals(head)) continue; if (refName.startsWith(Constants.R_HEADS) || refName.startsWith(Constants.R_REMOTES)) return true; } return false; }</code><technical_language>sense continue here? return false</technical_language>

Target:
public boolean isEnabled() { GitHistoryPage page = getPage(); Repository repository = getRepository(page); if (repository == null) return false; List<Ref> branchesOfCommit; try { branchesOfCommit = getBranchesOfCommit(page, repository); } catch (IOException e) { Activator.logError("Could not calculate Enablement", e); return false; } return !branchesOfCommit.isEmpty(); }
Source:
<code>protected boolean isAnyAppConfiguredInSourceServerXml() { boolean bConfigured = false; Set<String> locations = getAppConfigLocationsFromSourceServerXml(); if (locations.size() > 0) { log.debug("Application configuration is found in server.xml."); <START> bConfigured = true; <END> } return bConfigured; }</code><technical_language>I return true. fall return false, instead of creating a variable</technical_language>

Target:
protected boolean isAnyAppConfiguredInSourceServerXml() { Set<String> locations = getAppConfigLocationsFromSourceServerXml(); if (locations.size() > 0) { log.debug("Application configuration is found in server.xml."); return true; } else { return false; } }
Source:
<code>protected void exportAsContext() { if (EDatabaseConnTemplate.isSchemaNeeded(getConnection().getDatabaseType()) && schemaText != null <START> && StringUtils.isEmpty(schemaText.getText())) { <END> MessageDialog.openWarning(getShell(), Messages.getString("AbstractForm.ExportAsContext"), Messages.getString("DatabaseForm.checkSchema")); } collectContextParams(); super.exportAsContext(); }</code><technical_language>**isBlank**</technical_language>

Target:
protected void exportAsContext() { if (EDatabaseConnTemplate.isSchemaNeeded(getConnection().getDatabaseType()) && schemaText != null && StringUtils.isBlank(schemaText.getText())) { boolean confirm = MessageDialog.openConfirm(getShell(), Messages.getString("AbstractForm.ExportAsContext"), Messages.getString("DatabaseForm.checkSchema")); if(!confirm) { return; } } collectContextParams(); super.exportAsContext(); }
Source:
<code>public boolean validate() { boolean isNew = getModel().getIsNew(); int maxAllowedVms = getMaxVmsInPool(); int assignedVms = getModel().getAssignedVms().asConvertible().integer(); getModel().getNumOfDesktops().validateEntity( new IValidation[] { new NotEmptyValidation(), new LengthValidation(4), new IntegerValidation(isNew ? 1 : 0, isNew ? maxAllowedVms : maxAllowedVms - assignedVms) }); getModel().getPrestartedVms().validateEntity( new IValidation[] { new NotEmptyValidation(), new IntegerValidation(0, assignedVms) }); getModel().getMaxAssignedVmsPerUser().validateEntity( new IValidation[] { new NotEmptyValidation(), <START> new IntegerValidation(1, 1000000) <END> }); getModel().setIsGeneralTabValid(getModel().getIsGeneralTabValid() && getModel().getName().getIsValid() && getModel().getNumOfDesktops().getIsValid() && getModel().getPrestartedVms().getIsValid() && getModel().getMaxAssignedVmsPerUser().getIsValid()); getModel().setIsPoolTabValid(true); return super.validate() && getModel().getName().getIsValid() && getModel().getNumOfDesktops().getIsValid() && getModel().getPrestartedVms().getIsValid() && getModel().getMaxAssignedVmsPerUser().getIsValid(); }</code><technical_language>please Short.MAX_VALUE</technical_language>

Target:
public boolean validate() { boolean isNew = getModel().getIsNew(); int maxAllowedVms = getMaxVmsInPool(); int assignedVms = getModel().getAssignedVms().asConvertible().integer(); getModel().getNumOfDesktops().validateEntity( new IValidation[] { new NotEmptyValidation(), new LengthValidation(4), new IntegerValidation(isNew ? 1 : 0, isNew ? maxAllowedVms : maxAllowedVms - assignedVms) }); getModel().getPrestartedVms().validateEntity( new IValidation[] { new NotEmptyValidation(), new IntegerValidation(0, assignedVms) }); getModel().getMaxAssignedVmsPerUser().validateEntity( new IValidation[] { new NotEmptyValidation(), new IntegerValidation(1, Short.MAX_VALUE) }); getModel().setIsGeneralTabValid(getModel().getIsGeneralTabValid() && getModel().getName().getIsValid() && getModel().getNumOfDesktops().getIsValid() && getModel().getPrestartedVms().getIsValid() && getModel().getMaxAssignedVmsPerUser().getIsValid()); getModel().setIsPoolTabValid(true); return super.validate() && getModel().getName().getIsValid() && getModel().getNumOfDesktops().getIsValid() && getModel().getPrestartedVms().getIsValid() && getModel().getMaxAssignedVmsPerUser().getIsValid(); }
Source:
<code>private void doConcurrentPutInTx(String s) throws Exception { for (int i = 0; i < totalNumberOfBuckets; i++) { <START> synchronized (list) { <END> list.add(i); } } Thread[] threads = new Thread[totalNumberOfBuckets]; for (int i = 0; i < totalNumberOfBuckets; i++) { threads[i] = new Thread(() -> doPutOpInTx(s)); } for (int i = 0; i < totalNumberOfBuckets; i++) { threads[i].start(); } for (int i = 0; i < totalNumberOfBuckets; i++) { threads[i].join(); } }</code><technical_language>This synchronization block replaced a collection handles concurrency, ConcurrencyLinkedQueue Collections.synchronizedList()</technical_language>

Target:
private void doConcurrentPutInTx(String s) throws Exception { for (int i = 0; i < totalNumberOfBuckets; i++) { queue.add(i); } ExecutorService pool = Executors.newCachedThreadPool(); Collection<Callable<Object>> tasks = new ArrayList<>(); Callable<Object> task = () -> { doPutOpInTx(s); return null; }; for (int i = 0; i < totalNumberOfBuckets; i++) { tasks.add(task); } List<Future<Object>> futures = pool.invokeAll(tasks); for (Future future : futures) { future.get(); } }
Source:
<code>private void addEditLink(WebMvcLinkBuilder selfLinkBuilder, GoalDto goalResource) { <START> goalResource.add(selfLinkBuilder.withRel(JsonRootLinkRelationProvider.EDIT_REL)); <END> }</code><technical_language>IanaLinkRelation.EDIT</technical_language>

Target:
private void addEditLink(WebMvcLinkBuilder selfLinkBuilder, GoalDto goalResource) { goalResource.add(selfLinkBuilder.withRel(IanaLinkRelations.EDIT)); }
Source:
<code>public VM() { mVmStatic = new VmStatic(); mVmDynamic = new VmDynamic(); mVmStatistics = new VmStatistics(); <START> mVmStatic.setImages(new java.util.ArrayList<DiskImage>()); <END> mVmStatic.setInterfaces(new java.util.ArrayList<VmNetworkInterface>()); mDiskMap = new java.util.HashMap<String, DiskImage>(); mCdPath = ""; mFloppyPath = ""; mRunAndPause = false; _diskSize = 0; }</code><technical_language>coudl ArrayList is imported ^^ vv</technical_language>

Target:
public VM() { mVmStatic = new VmStatic(); mVmDynamic = new VmDynamic(); mVmStatistics = new VmStatistics(); mVmStatic.setImages(new ArrayList<DiskImage>()); mVmStatic.setInterfaces(new ArrayList<VmNetworkInterface>()); mDiskMap = new java.util.HashMap<String, DiskImage>(); mCdPath = ""; mFloppyPath = ""; mRunAndPause = false; _diskSize = 0; }
Source:
<code>private void setCurentCommitInfo(String revision) { fCommitInfo.reset(); Iterator<Map.Entry<String, RevisionInfo>> itr1 = fRevisions.entrySet().iterator(); while (itr1.hasNext()) { Entry<String, RevisionInfo> entry = itr1.next(); if (entry.getKey().equals(revision)) { System.out.println("Looking at the Current patchset : " + entry.getValue().getNumber()); fCommitInfo.setCommit(revision); fCommitInfo.setMessage(entry.getValue().getCommit().getMessage()); fCommitInfo.setParents(entry.getValue().getCommit().getParents()); fCommitInfo.setAuthor(entry.getValue().getCommit().getAuthor()); fCommitInfo.setCommitter(entry.getValue().getCommit().getCommitter()); } else { <START> System.out.println("Looking <END> at the other patchset : " + entry.getValue().getNumber()); } } }</code><technical_language>log</technical_language>

Target:
private void setCurentCommitInfo(String revision) { fCommitInfo.reset(); Iterator<Map.Entry<String, RevisionInfo>> itr1 = fRevisions.entrySet().iterator(); while (itr1.hasNext()) { Entry<String, RevisionInfo> entry = itr1.next(); if (entry.getKey().equals(revision)) { fCommitInfo.setCommit(revision); fCommitInfo.setMessage(entry.getValue().getCommit().getMessage()); fCommitInfo.setParents(entry.getValue().getCommit().getParents()); fCommitInfo.setAuthor(entry.getValue().getCommit().getAuthor()); fCommitInfo.setCommitter(entry.getValue().getCommit().getCommitter()); } } }
Source:
<code>public void testQueryProcessByVariables() { <START> Map<String, Object> variables = Collections.<String, Object> singletonMap("var_a", "a1"); Map<String, Object> attributes = Collections.<String, Object> singletonMap("processId", "test.test_A"); <END> List<ProcessInstanceWithVarsDesc> data = advanceVariableDataService.queryProcessByVariables(attributes, variables, new QueryContext()); Assert.assertEquals(3, data.size()); for (ProcessInstanceWithVarsDesc p : data) { Assert.assertEquals("a1", p.getVariables().get("var_a")); Assert.assertEquals("test.test_A", p.getProcessId()); } }</code><technical_language>Collections.<String, Object> singletonMap replaced Collections.singletonMap</technical_language>

Target:
public void testQueryProcessByVariables() { List<QueryParam> variables = list(equalsTo("var_a", "a1"), equalsTo("var_b", "1")); List<QueryParam> attributes = list(equalsTo(PROCESS_ATTR_DEFINITION_ID, "test.test_A")); List<ProcessInstanceWithVarsDesc> data = advanceVariableDataService.queryProcessByVariables(attributes, variables, queryContext); if (queryContext.getCount() > 0) { Assert.assertThat(data.size(), is(queryContext.getCount())); } for (ProcessInstanceWithVarsDesc p : data) { Assert.assertEquals("a1", p.getVariables().get("var_a")); Assert.assertEquals("1", p.getVariables().get("var_b")); Assert.assertEquals("test.test_A", p.getProcessId()); } }
Source:
<code>void updateThreadPoolSize(int numThreads) { <START> m_scheduler.setCorePoolSize(numThreads); LOG.info("Updated PBD to use " + numThreads + " threads to enforce retention policy"); <END> }</code><technical_language>Do want check if thread count changed right this log message logged catalog update affects kipling</technical_language>

Target:
void updateThreadPoolSize(int numThreads) { if (numThreads != m_scheduler.getCorePoolSize()) { m_scheduler.setCorePoolSize(numThreads); LOG.info("Updated PBD to use " + numThreads + " threads to enforce retention policy"); } }
Source:
<code>protected void postProcessHeaderLines() { final List<String> headerLines = getHeaderLines(); <START> final Pattern blankLine = Pattern.compile(EMPTY_LINE_PATTERN); <END> for (final String line : headerLines) { try { if (line.isEmpty()) { headerRegexps.add(blankLine); } else { headerRegexps.add(Pattern.compile(line)); } } catch (final PatternSyntaxException ex) { throw new IllegalArgumentException("line " + (headerRegexps.size() + 1) + " in header specification" + " is not a regular expression", ex); } } }</code><technical_language>please move compilation of pattern class field, done ones, for execution of checkstyle</technical_language>

Target:
protected void postProcessHeaderLines() { final List<String> headerLines = getHeaderLines(); for (String line : headerLines) { try { if (line.isEmpty()) { headerRegexps.add(BLANK_LINE); } else { headerRegexps.add(Pattern.compile(line)); } } catch (final PatternSyntaxException ex) { throw new IllegalArgumentException("line " + (headerRegexps.size() + 1) + " in header specification" + " is not a regular expression", ex); } } }
Source:
<code>public void setActivePart(IAction action, IWorkbenchPart targetPart) { <START> if(targetPart instanceof IMavenProjectHolder) { <END> this.projectHolder = (IMavenProjectHolder) targetPart; } else { this.projectHolder = null; } }</code><technical_language>I IMavenProjectHolder. I targetPart.getAdapter(MavenProject.class) is more here</technical_language>

Target:
public void setActivePart(IAction action, IWorkbenchPart targetPart) { mavenProject = (MavenProject) targetPart.getAdapter(MavenProject.class); }
Source:
<code>public boolean tryAdd(final EventData eventData) throws PayloadSizeExceededException { if (eventData == null) { <START> throw new IllegalArgumentException("eventData cannot be null."); <END> } final EventDataImpl eventDataImpl = (EventDataImpl) eventData; final int size; try { size = getSize(eventDataImpl, events.isEmpty()); } catch (java.nio.BufferOverflowException exception) { throw new PayloadSizeExceededException(String.format(Locale.US, "Size of the payload exceeded Maximum message size: %s kb", this.maxMessageSize / 1024)); } if (this.currentSize + size > this.maxMessageSize) { return false; } this.events.add(eventDataImpl); this.currentSize += size; return true; }</code><technical_language>Replace Objects.requireNotNull</technical_language>

Target:
public boolean tryAdd(final EventData eventData) throws PayloadSizeExceededException { if (eventData == null) { throw new IllegalArgumentException("eventData cannot be null"); } final EventDataImpl eventDataImpl = (EventDataImpl) eventData; final int size; try { size = getSize(eventDataImpl, events.isEmpty()); } catch (java.nio.BufferOverflowException exception) { throw new PayloadSizeExceededException(String.format(Locale.US, "Size of the payload exceeded Maximum message size: %s kb", this.maxMessageSize / 1024)); } if (this.currentSize + size > this.maxMessageSize) { return false; } this.events.add(eventDataImpl); this.currentSize += size; return true; }
Source:
<code>private static void doAppendEscapedIdentifier(Appendable sbuf, String value) throws SQLException { try { sbuf.append('"'); <START> for (char ch : value.toCharArray()) { <END> if (ch == '\0') { throw new PSQLException(GT.tr("Zero bytes may not occur in identifiers."), PSQLState.INVALID_PARAMETER_VALUE); } if (ch == '"') { sbuf.append(ch); } sbuf.append(ch); } sbuf.append('"'); } catch (IOException e) { throw new PSQLException(GT.tr("No IOException expected from StringBuffer or StringBuilder"), PSQLState.UNEXPECTED_ERROR, e); } }</code><technical_language>I if this change result array allocation extra cpu/memory consumption issues</technical_language>

Target:
private static void doAppendEscapedIdentifier(Appendable sbuf, String value) throws SQLException { try { sbuf.append('"'); for (int i = 0; i < value.length(); ++i) { char ch = value.charAt(i); if (ch == '\0') { throw new PSQLException(GT.tr("Zero bytes may not occur in identifiers."), PSQLState.INVALID_PARAMETER_VALUE); } if (ch == '"') { sbuf.append(ch); } sbuf.append(ch); } sbuf.append('"'); } catch (IOException e) { throw new PSQLException(GT.tr("No IOException expected from StringBuffer or StringBuilder"), PSQLState.UNEXPECTED_ERROR, e); } }
Source:
<code>public void shouldScheduleDelayedActionOnHandlerThread() { Handler handler = mock(Handler.class); @SuppressWarnings("unchecked") Action0 action = mock(Action0.class); Scheduler scheduler = HandlerScheduler.create(handler); Worker inner = scheduler.createWorker(); <START> inner.schedule(action, 1L, TimeUnit.SECONDS); <END> ArgumentCaptor<Runnable> runnable = ArgumentCaptor.forClass(Runnable.class); verify(handler).postDelayed(runnable.capture(), eq(1000L)); runnable.getValue().run(); verify(action).call(); }</code><technical_language>static imports for TimeUnit values below</technical_language>

Target:
public void shouldScheduleDelayedActionOnHandlerThread() { Handler handler = mock(Handler.class); @SuppressWarnings("unchecked") Action0 action = mock(Action0.class); Scheduler scheduler = HandlerScheduler.from(handler); Worker inner = scheduler.createWorker(); inner.schedule(action, 1, SECONDS); ArgumentCaptor<Runnable> runnable = ArgumentCaptor.forClass(Runnable.class); verify(handler).postDelayed(runnable.capture(), eq(1000L)); runnable.getValue().run(); verify(action).call(); }
Source:
<code>public void aggregate(ByteBuffer buf, int position) { <START> boolean countNulls = !selector.nameLookupPossibleInAdvance() || NullHandlingHelper.useDefaultValuesForNull(); <END> MutableBitmap mutableBitmap = getMutableBitmap(position); IndexedInts row = selector.getRow(); for (int i = 0; i < row.size(); i++) { int index = row.get(i); if (countNulls || selector.lookupName(index) != null) { mutableBitmap.add(index); } } buf.putLong(position, mutableBitmap.size()); }</code><technical_language>Similar DistinctCountAggregator</technical_language>

Target:
public void aggregate(ByteBuffer buf, int position) { MutableBitmap mutableBitmap = getMutableBitmap(position); IndexedInts row = selector.getRow(); for (int i = 0; i < row.size(); i++) { int index = row.get(i); if (NullHandling.useDefaultValuesForNull() || isNotNull(index)) { mutableBitmap.add(index); } } buf.putLong(position, mutableBitmap.size()); }
Source:
<code>private List<ModelNode> adjustInfinispan(final PathAddress subsystem) throws Exception { final List<ModelNode> list = new ArrayList<>(); list.add(getWriteAttributeOperation(subsystem.append("cache-container", "server").append("transport", "jgroups"), "stack", new ModelNode("udp"))); <START> list.add(setStatisticsEnabledTrue( <END> subsystem.append("cache-container", "server"))); list.add(setStatisticsEnabledTrue( subsystem.append("cache-container", "server").append("replicated-cache", "default"))); list.add(setStatisticsEnabledTrue( subsystem.append("cache-container", "web"))); list.add(setStatisticsEnabledTrue( subsystem.append("cache-container", "web").append("distributed-cache", "dist"))); list.add(setStatisticsEnabledTrue( subsystem.append("cache-container", "ejb"))); list.add(setStatisticsEnabledTrue( subsystem.append("cache-container", "ejb").append("distributed-cache", "dist"))); list.add(setStatisticsEnabledTrue( subsystem.append("cache-container", "hibernate"))); list.add(setStatisticsEnabledTrue( subsystem.append("cache-container", "hibernate").append("invalidation-cache", "entity"))); list.add(setStatisticsEnabledTrue( subsystem.append("cache-container", "hibernate").append("local-cache", "local-query"))); list.add(setStatisticsEnabledTrue( subsystem.append("cache-container", "hibernate").append("replicated-cache", "timestamps"))); return list; }</code><technical_language>Statistics-enabled introduced in 6.3.0, is need set true for 6.3.0, for 6.2.0</technical_language>

Target:
private List<ModelNode> adjustInfinispan(final PathAddress subsystem) throws Exception { final List<ModelNode> list = new ArrayList<>(); list.add(getWriteAttributeOperation(subsystem.append("cache-container", "server").append("transport", "jgroups"), "stack", new ModelNode("udp"))); this.adjustInfinispanStatisticsEnabled(list, subsystem); return list; }
Source:
<code>EventBus eventBus() { <START> EventBus bus = new EventBus((exception, context) -> exception.printStackTrace()); <END> bus.register(new DeadEventHandler()); return bus; }</code><technical_language>printStackTrace() used. a logger instead</technical_language>

Target:
EventBus eventBus() { EventBus bus = new EventBus(); bus.register(new DeadEventHandler()); return bus; }
Source:
<code>ObjectLoader openPackedObject(WindowCursor curs, AnyObjectId objectId) { PackList pList; do { pList = packList.get(); SEARCH: for (;;) { for (PackFile p : pList.packs) { try { ObjectLoader ldr = p.get(curs, objectId); if (ldr != null) return ldr; } catch (PackMismatchException e) { PackList nList = scanPacks(pList); <START> if (pList != nList) { <END> pList = nList; continue SEARCH; } } catch (IOException e) { removePack(p); } } break SEARCH; } } while (searchPacksAgain(pList)); return null; }</code><technical_language>I this be: if (searchPacksAgain(pList)) continue SEARCH;</technical_language>

Target:
ObjectLoader openPackedObject(WindowCursor curs, AnyObjectId objectId) { PackList pList; do { SEARCH: for (;;) { pList = packList.get(); for (PackFile p : pList.packs) { try { ObjectLoader ldr = p.get(curs, objectId); if (ldr != null) return ldr; } catch (PackMismatchException e) { if (searchPacksAgain(pList)) continue SEARCH; } catch (IOException e) { removePack(p); } } break SEARCH; } } while (searchPacksAgain(pList)); return null; }
Source:
<code>public void bufferExactFailingSupplier() { Scheduler.Worker w = new TestScheduler().createWorker(); TestSubscriber<List<Integer>> observer = new TestSubscriber<List<Integer>>(); <START> FlowableBufferTimed.BufferExactBoundedSubscriber<Integer, List<Integer>> buf = new FlowableBufferTimed.BufferExactBoundedSubscriber<Integer, List<Integer>>(observer, ArrayListSupplier.<Integer>asCallable(), 100, TimeUnit.MILLISECONDS, 10, false, w); <END> buf.onError(new Throwable()); buf.onComplete(); }</code><technical_language>list supplier fail, calling onError onCompleted this is a plain protocol violation. Do this instead: java Flowable.empty() .buffer(10, 10, TimeUnit.SECONDS, Schedulers.computation(), new Callable<List<Object>>() { @Override public void call() { throw new TestException(); } }) .test() .awaitDone(5, TimeUnit.SECONDS) .assertFailure(TestException.class) ;</technical_language>

Target:
public void bufferExactFailingSupplier() { Flowable.empty() .buffer(1, TimeUnit.SECONDS, Schedulers.computation(), 10, new Callable<List<Object>>() { @Override public List<Object> call() throws Exception { throw new TestException(); } }, false) .test() .awaitDone(1, TimeUnit.SECONDS) .assertFailure(TestException.class) ; }
Source:
<code>private Image getImageForDraw() { <START> if (sprite.look.getLookData() != null) { <END> if (sprite.look.getLookData().getCollisionInformation().getLeftBubblePos() == null || sprite.look.getLookData().getCollisionInformation().getRightBubblePos() == null) { sprite.look.getLookData().getCollisionInformation().loadOrCreateCollisionPolygon(); } CollisionInformation collisionInformation = sprite.look.getLookData().getCollisionInformation(); Pair<Integer, Integer> bubblePosRight = collisionInformation.getRightBubblePos(); Pair<Integer, Integer> bubblePosLeft = collisionInformation.getLeftBubblePos(); imageLeft.setX(calculateLeftImageX(bubblePosLeft.first)); imageLeft.setY(calculateImageY(bubblePosLeft.second)); imageRight.setX(calculateRightImageX(bubblePosRight.first)); imageRight.setY(calculateImageY(bubblePosRight.second)); } else { if (drawRight) { image.setX(sprite.look.getXInUserInterfaceDimensionUnit() + (sprite.look .getWidthInUserInterfaceDimensionUnit() / 2)); } else { image.setX(sprite.look.getXInUserInterfaceDimensionUnit() - sprite.look .getWidthInUserInterfaceDimensionUnit() / 2 - image.getWidth()); } image.setY(sprite.look.getYInUserInterfaceDimensionUnit() + (sprite.look .getHeightInUserInterfaceDimensionUnit() / 2)); } return image; }</code><technical_language>I prefer of local variables resolve calls something.somethingelse.somefunction()</technical_language>

Target:
private Image getImageForDraw() { LookData lookData = sprite.look.getLookData(); if (lookData != null) { CollisionInformation collisionInformation = lookData.getCollisionInformation(); if (collisionInformation.getLeftBubblePos() == null || collisionInformation.getRightBubblePos() == null) { collisionInformation.calculateBubblePositions(); } Pair<Integer, Integer> bubblePosRight = collisionInformation.getRightBubblePos(); Pair<Integer, Integer> bubblePosLeft = collisionInformation.getLeftBubblePos(); imageLeft.setX(calculateLeftImageX(bubblePosLeft.first)); imageLeft.setY(calculateImageY(bubblePosLeft.second)); imageRight.setX(calculateRightImageX(bubblePosRight.first)); imageRight.setY(calculateImageY(bubblePosRight.second)); } else { Look look = sprite.look; if (drawRight) { image.setX(look.getXInUserInterfaceDimensionUnit() + (look.getWidthInUserInterfaceDimensionUnit() / 2)); } else { image.setX(look.getXInUserInterfaceDimensionUnit() - look.getWidthInUserInterfaceDimensionUnit() / 2 - image.getWidth()); } image.setY(look.getYInUserInterfaceDimensionUnit() + (look.getHeightInUserInterfaceDimensionUnit() / 2)); } return image; }
Source:
<code>public static User toUser(DecodedJWT jwt) { final String subject = jwt.getSubject(); final List<Role> roles = jwt.getClaims().entrySet().stream() .filter(entry -> entry.getKey().startsWith(ROLE_PREFIX)) .map(entry -> { final String roleName = entry.getKey(); final Claim claim = entry.getValue(); final List<Permission> permissions = claim.asList(String.class).stream().map(Permission::valueOf).collect(Collectors.toList()); <START> return new Role(roleName.substring(roleName.indexOf("_") + 1, roleName.length()), permissions); <END> }).collect(Collectors.toList()); return new User(subject, roles); }</code><technical_language>String.replace() replace ROLE_PREFIX empty String resulting role name,</technical_language>

Target:
public static User toUser(DecodedJWT jwt) { final String subject = jwt.getSubject(); final List<Role> roles = jwt.getClaims().entrySet().stream() .filter(entry -> entry.getKey().startsWith(ROLE_PREFIX)) .map(entry -> { final String roleName = entry.getKey(); final Claim claim = entry.getValue(); final List<Permission> permissions = claim.asList(String.class).stream().map(Permission::valueOf).collect(Collectors.toList()); return new Role(roleName.replace(ROLE_PREFIX, ""), permissions); }).collect(Collectors.toList()); return new User(subject, roles); }
Source:
<code>public void readInfo() { this.mvnInfo = null; this.mvnName = null; if (!infofile.exists()) { return; } try { final String content = FileUtils.readFileToString(infofile, Charsets.UTF_8); final int i = content.indexOf(','); <START> LOGGER.log(Level.FINE, "The " + name + " artifact info cached is: " + content); <END> if (i != -1) { this.mvnInfo = content.substring(0, i); this.mvnName = content.substring(i + 1); } else { LOGGER.log(Level.WARNING, "The " + name + " artifact info is invalid"); } } catch (IOException e) { LOGGER.log(Level.WARNING, "The " + name + " artifact info failed to be loaded", e); } }</code><technical_language>parameterized logging</technical_language>

Target:
public void readInfo() { this.mvnInfo = null; this.mvnName = null; if (!infofile.exists()) { return; } try { final String content = FileUtils.readFileToString(infofile, Charsets.UTF_8); final int i = content.indexOf(','); LOGGER.log(Level.FINE, "The {0} artifact info cached is: {1}", new Object[] {name, content}); if (i != -1) { this.mvnInfo = content.substring(0, i); this.mvnName = content.substring(i + 1); } else { LOGGER.log(Level.WARNING, "The {0} artifact info is invalid", name); } } catch (IOException e) { LOGGER.log(Level.WARNING, "The " + name + " artifact info failed to be loaded", e); } }
Source:
<code>private void refreshSignedOffBy() { String curText = commitText.getText(); <START> if (signedOff) { <END> commitText.setText(signOff(curText)); } else { String s = getSignedOff(); if (s != null) { curText = replaceSignOff(curText, s, EMPTY_STRING); if (curText.endsWith(Text.DELIMITER + Text.DELIMITER)) curText = curText.substring(0, curText.length() - Text.DELIMITER.length()); commitText.setText(curText); } } }</code><technical_language>Style nit: unneeded curlies</technical_language>

Target:
private void refreshSignedOffBy() { String curText = commitText.getText(); if (signedOff) commitText.setText(signOff(curText)); else { String s = getSignedOff(); if (s != null) { curText = replaceSignOff(curText, s, EMPTY_STRING); if (curText.endsWith(Text.DELIMITER + Text.DELIMITER)) curText = curText.substring(0, curText.length() - Text.DELIMITER.length()); commitText.setText(curText); } } }
Source:
<code>public void put(String key, String value) { Assert.notNull(key, "'key' must not be null."); Assert.notNull(value, "'value' must not be null."); <START> BoundValueOperations<String, String> ops = redisTemplate.boundValueOps(key); <END> ops.set(value); }</code><technical_language>this.redisTemplate</technical_language>

Target:
public void put(String key, String value) { Assert.notNull(key, "'key' must not be null."); Assert.notNull(value, "'value' must not be null."); BoundValueOperations<String, String> ops = this.redisTemplate.boundValueOps(key); ops.set(value); }
Source:
<code>public ResponseEntity<?> createDilution(@RequestBody DilutionDto dilutionDto, UriComponentsBuilder b) throws IOException { if (dilutionDto == null) { log.error( "Received null dilutionDto from front end; cannot convert to Dilution. Something likely went wrong in the JS DTO conversion."); throw new RestException("Cannot convert null to Dilution", Status.BAD_REQUEST); } Long id = null; LibraryDilution dilution; try { dilution = Dtos.to(dilutionDto); <START> dilution.setLibrary(libraryService.get(dilutionDto.getLibrary().getId())); <END> id = populateAndSaveDilutionFromDto(dilutionDto, dilution, true); } catch (ConstraintViolationException e) { log.error("Error while creating dilution", e); RestException restException = new RestException(e.getMessage(), Status.BAD_REQUEST); restException.addData("constraintName", e.getConstraintName()); throw restException; } UriComponents uriComponents = b.path("/library/{id}").buildAndExpand(dilution.getLibrary().getId()); HttpHeaders headers = new HttpHeaders(); headers.setLocation(uriComponents.toUri()); headers.set("Id", id.toString()); return new ResponseEntity<>(headers, HttpStatus.CREATED); }</code><technical_language>fetch happen in Service</technical_language>

Target:
public ResponseEntity<?> createDilution(@RequestBody DilutionDto dilutionDto, UriComponentsBuilder b) throws IOException { if (dilutionDto == null) { log.error( "Received null dilutionDto from front end; cannot convert to Dilution. Something likely went wrong in the JS DTO conversion."); throw new RestException("Cannot convert null to Dilution", Status.BAD_REQUEST); } Long id = null; LibraryDilution dilution; try { dilution = Dtos.to(dilutionDto); id = dilutionService.create(dilution); } catch (ConstraintViolationException e) { log.error("Error while creating dilution", e); RestException restException = new RestException(e.getMessage(), Status.BAD_REQUEST); restException.addData("constraintName", e.getConstraintName()); throw restException; } UriComponents uriComponents = b.path("/library/{id}").buildAndExpand(dilution.getLibrary().getId()); HttpHeaders headers = new HttpHeaders(); headers.setLocation(uriComponents.toUri()); headers.set("Id", id.toString()); return new ResponseEntity<>(headers, HttpStatus.CREATED); }
Source:
<code>public void start(SocketAddress endpoint) throws IOException { if (isListening()) { throw new IllegalStateException("Cannot start when already listening for messages"); } bindToAddress(endpoint); new Thread(() -> { <START> while (!configServerSocket.isClosed()) { <END> acceptConnection(); } }, "configurationListener").start(); }</code><technical_language>thread.isUnterupted necessary</technical_language>

Target:
public void start(SocketAddress endpoint) throws IOException { if (isListening()) { throw new IllegalStateException("Cannot start when already listening for messages"); } bindToAddress(endpoint); new Thread(() -> { while (!configServerSocket.isClosed()) { acceptConnection(); } }, "messagesListener").start(); }