auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public static String escapeStringLiteral(final String s) { if (s == null) { <START> return DruidExpression.nullLiteral(); <END> } else { boolean isPlainAscii = true; final StringBuilder builder = new StringBuilder("'"); for (int i = 0; i < s.length(); i++) { final char c = s.charAt(i); if (Character.isLetterOrDigit(c) || c == ' ') { builder.append(c); if (c > 127) { isPlainAscii = false; } } else { builder.append("\\").append(BaseEncoding.base16().encode(Chars.toByteArray(c))); isPlainAscii = false; } } builder.append("'"); return isPlainAscii ? builder.toString() : "U&" + builder.toString(); } }</code><technical_language>This right function use; Calcites.escapeStringLiteral is meant for escaping strings end in SQL statements, DruidExpression.nullLiteral is meant for creating literals for Druid expressions. I checked out usages of Calcites.escapeStringLiteral calls a null value, I simplest solution is add a null check for s throw NPE if null</technical_language>

Target:
public static String escapeStringLiteral(final String s) { Preconditions.checkNotNull(s); if (s == null) { return "''"; } else { boolean isPlainAscii = true; final StringBuilder builder = new StringBuilder("'"); for (int i = 0; i < s.length(); i++) { final char c = s.charAt(i); if (Character.isLetterOrDigit(c) || c == ' ') { builder.append(c); if (c > 127) { isPlainAscii = false; } } else { builder.append("\\").append(BaseEncoding.base16().encode(Chars.toByteArray(c))); isPlainAscii = false; } } builder.append("'"); return isPlainAscii ? builder.toString() : "U&" + builder.toString(); } }
Source:
<code>public synchronized void outputNewImage(String filename) { <START> if (imageRenderer == null) { <END> LOGGER.severe("No image renderer has been set. " + "Use setRenderer() method in order to be able to output images."); throw new NoRendererException(); } switch (layoutPolicy) { case COMPUTED_IN_LAYOUT_RUNNER: layoutPipeIn.pump(); break; case COMPUTED_ONCE_AT_NEW_IMAGE: if (layout != null) layout.compute(); break; case COMPUTED_FULLY_AT_NEW_IMAGE: stabilizeLayout(layout.getStabilizationLimit()); break; default: break; } if (clearImageBeforeOutput || gg.getNodeCount() == 0) { imageRenderer.clear(0x00000000); } if (gg.getNodeCount() > 0) { if (autofit) { gg.computeBounds(); Point3 lo = gg.getMinPos(); Point3 hi = gg.getMaxPos(); imageRenderer.getGraphRenderer().getCamera().setBounds(lo.x, lo.y, lo.z, hi.x, hi.y, hi.z); } imageRenderer.render(0, 0, resolution.getWidth(), resolution.getHeight()); } BufferedImage image = imageRenderer.getRenderedImage(); for (Filter action : filters) action.apply(image); image.flush(); try { writeImage(image, filename); printProgress(); } catch (IOException e) { LOGGER.log(Level.WARNING, "Failed to write image", e); } }</code><technical_language>I wish a more gracious check for renderer. add extra step checks org.graphstream.ui system property? If is set org.graphstream.ui.javafx.util.Display conclude FX rendered</technical_language>

Target:
public synchronized void outputNewImage(String filename) { switch (layoutPolicy) { case COMPUTED_IN_LAYOUT_RUNNER: layoutPipeIn.pump(); break; case COMPUTED_ONCE_AT_NEW_IMAGE: if (layout != null) layout.compute(); break; case COMPUTED_FULLY_AT_NEW_IMAGE: stabilizeLayout(layout.getStabilizationLimit()); break; default: break; } if (clearImageBeforeOutput || gg.getNodeCount() == 0) { clearImage(0x00000000); } if (gg.getNodeCount() > 0) { if (autofit) { gg.computeBounds(); Point3 lo = gg.getMinPos(); Point3 hi = gg.getMaxPos(); getCamera().setBounds(lo.x, lo.y, lo.z, hi.x, hi.y, hi.z); } render(); } BufferedImage image = getRenderedImage(); for (Filter action : filters) action.apply(image); image.flush(); try { writeImage(image, filename); printProgress(); } catch (IOException e) { LOGGER.log(Level.WARNING, "Failed to write image", e); } }
Source:
<code>private void updateImageInformation(Tool tool, Tag newTag, Tag oldTag) { if (oldTag.getImages().isEmpty()) { oldTag.getImages().addAll(getImageInformationForTag(tool, newTag).getImages()); } else { Iterator<Image> iterator = oldTag.getImages().iterator(); Iterator<Image> iterator2 = newTag.getImages().iterator(); while (iterator.hasNext()) { Image oldImage = iterator.next(); while (iterator2.hasNext()) { Image newImage = iterator2.next(); <START> if (oldImage.getImageID() != newImage.getImageID()) { <END> oldTag.getImages().remove(oldImage); oldTag.getImages().addAll(getImageInformationForTag(tool, newTag).getImages()); } } } } }</code><technical_language>need equals instead of !=. If is a possibility of imageId null (I is), Object.equals</technical_language>

Target:
private void updateImageInformation(Tool tool, Tag newTag, Tag oldTag) { if (oldTag.getImages().isEmpty()) { oldTag.getImages().addAll(getImagesForTag(tool, newTag)); } else { oldTag.getImages().removeAll(oldTag.getImages()); oldTag.getImages().addAll(newTag.getImages()); } }
Source:
<code>private void createNewTraceNameGroup(Composite parent) { Font font = parent.getFont(); Composite folderGroup = new Composite(parent, SWT.NONE); GridLayout layout = new GridLayout(); layout.numColumns = 2; folderGroup.setLayout(layout); folderGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); GridData data = new GridData(GridData.FILL_HORIZONTAL); <START> data.widthHint = IDialogConstants.ENTRY_FIELD_WIDTH; <END> String name = fFolder.getName(); Label newTaceLabel = new Label(folderGroup, SWT.NONE); newTaceLabel.setFont(font); newTaceLabel.setText(Messages.RenameFolderDialog_FolderNewName); fNewFolderNameText = new Text(folderGroup, SWT.BORDER); data = new GridData(GridData.FILL_HORIZONTAL); data.widthHint = IDialogConstants.ENTRY_FIELD_WIDTH; fNewFolderNameText.setLayoutData(data); fNewFolderNameText.setFont(font); fNewFolderNameText.setFocus(); fNewFolderNameText.setText(name); fNewFolderNameText.setSelection(0, name.length()); fNewFolderNameText.addListener(SWT.Modify, new Listener() { @Override public void handleEvent(Event event) { validateNewFolderName(); } }); }</code><technical_language>Unused instance</technical_language>

Target:
private void createNewTraceNameGroup(Composite parent) { Font font = parent.getFont(); Composite folderGroup = new Composite(parent, SWT.NONE); GridLayout layout = new GridLayout(); layout.numColumns = 2; folderGroup.setLayout(layout); folderGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); String name = fFolder.getName(); Label newTaceLabel = new Label(folderGroup, SWT.NONE); newTaceLabel.setFont(font); newTaceLabel.setText(Messages.RenameFolderDialog_FolderNewName); fNewFolderNameText = new Text(folderGroup, SWT.BORDER); GridData data = new GridData(GridData.FILL_HORIZONTAL); data.widthHint = IDialogConstants.ENTRY_FIELD_WIDTH; fNewFolderNameText.setLayoutData(data); fNewFolderNameText.setFont(font); fNewFolderNameText.setFocus(); fNewFolderNameText.setText(name); fNewFolderNameText.setSelection(0, name.length()); fNewFolderNameText.addListener(SWT.Modify, new Listener() { @Override public void handleEvent(Event event) { validateNewFolderName(); } }); }
Source:
<code><START> public static Object last(Object[] array) { <END> if (array.length == 0) { return null; } return array[array.length - 1]; }</code><technical_language>throw exception signal empty array</technical_language>

Target:
public static Object last(Object[] array) { if (array.length == 0) { throw new NoSuchElementException("Empty array"); } return array[array.length - 1]; }
Source:
<code>private void addMaintenanceFailedReason(List<String> failedMessages) { Guid rootCommandGuid = commandsRepository.getCommandEntity(getCommandId()).getRootCommandId(); CommandBase<T> rootCommand = commandCoordinatorUtil.retrieveCommand(rootCommandGuid); String messageToDisplay = failedMessages.get(0); rootCommand.addCustomValue("Message", messageToDisplay); <START> auditLogDirector.log(rootCommand, AuditLogType.VDS_MAINTENANCE_FAILED_REASON, messageToDisplay); <END> }</code><technical_language>do similar MigrateVmCommand private void addMaintenanceFailedReason() { addCustomValue("Message",backend.getErrorsTranslator().translateErrorText(getReturnValue().getValidationMessages())); auditLogDirector.log(this,AuditLogType.VDS_MAINTENANCE_FAILED_REASON); }</technical_language>

Target:
private void addMaintenanceFailedReason(List<String> failedMessages) { Guid rootCommandGuid = commandsRepository.getCommandEntity(getCommandId()).getRootCommandId(); CommandBase<T> rootCommand = commandCoordinatorUtil.retrieveCommand(rootCommandGuid); String messageToDisplay = failedMessages.get(0); addCustomValue("Message", messageToDisplay); auditLogDirector.log(this, AuditLogType.VDS_MAINTENANCE_FAILED_REASON, messageToDisplay); }
Source:
<code>private void initListBoxEditors() { dataCenterEditor = new ListModelListBoxEditor<StoragePool>(new NullSafeRenderer<StoragePool>() { @Override public String renderNullSafe(StoragePool object) { return object.getName(); } }); cpuEditor = new ListModelListBoxEditor<ServerCpu>(new NullSafeRenderer<ServerCpu>() { @Override public String renderNullSafe(ServerCpu object) { return object.getCpuName(); } }); versionEditor = new ListModelListBoxEditor<Version>(new NullSafeRenderer<Version>() { @Override public String renderNullSafe(Version object) { return object.toString(); } }); architectureEditor = new ListModelListBoxEditor<ArchitectureType>(new NullSafeRenderer<ArchitectureType>() { @Override public String renderNullSafe(ArchitectureType object) { return object.toString(); } }); clusterPolicyEditor = new ListModelListBoxEditor<ClusterPolicy>(new NullSafeRenderer<ClusterPolicy>() { @Override public String renderNullSafe(ClusterPolicy object) { return object.getName(); } }); <START> architectureEditor.setVisible(ApplicationModeHelper.isModeSupported(ApplicationMode.VirtOnly)); <END> }</code><technical_language>do this in ClusterModel itself</technical_language>

Target:
private void initListBoxEditors() { dataCenterEditor = new ListModelListBoxEditor<StoragePool>(new NullSafeRenderer<StoragePool>() { @Override public String renderNullSafe(StoragePool object) { return object.getName(); } }); cpuEditor = new ListModelListBoxEditor<ServerCpu>(new NullSafeRenderer<ServerCpu>() { @Override public String renderNullSafe(ServerCpu object) { return object.getCpuName(); } }); versionEditor = new ListModelListBoxEditor<Version>(new NullSafeRenderer<Version>() { @Override public String renderNullSafe(Version object) { return object.toString(); } }); architectureEditor = new ListModelListBoxEditor<ArchitectureType>(new NullSafeRenderer<ArchitectureType>() { @Override public String renderNullSafe(ArchitectureType object) { return object.toString(); } }); clusterPolicyEditor = new ListModelListBoxEditor<ClusterPolicy>(new NullSafeRenderer<ClusterPolicy>() { @Override public String renderNullSafe(ClusterPolicy object) { return object.getName(); } }); }
Source:
<code>protected Map<String, Pair<String, String>> getExclusiveLocks() { Map<String, Pair<String, String>> locks = new HashMap<String, Pair<String, String>>(); <START> locks.put(getStorageDomain().getId().toString(), LockMessagesMatchUtil.STORAGE); <END> locks.put(getParameters().getStorageServerConnection().getconnection(), LockMessagesMatchUtil.STORAGE_CONNECTION); locks.put(oldConnection.getconnection(), LockMessagesMatchUtil.STORAGE_CONNECTION); return locks; }</code><technical_language>getStorageDomain() null NPE</technical_language>

Target:
protected Map<String, Pair<String, String>> getExclusiveLocks() { Map<String, Pair<String, String>> locks = new HashMap<String, Pair<String, String>>(); domains = getStorageDomainsByConnId(getParameters().getStorageServerConnection().getid()); if(!domains.isEmpty() && domains.size() == 1) { setStorageDomain(domains.get(0)); locks.put(getStorageDomain().getId().toString(), LockMessagesMatchUtil.STORAGE); } locks.put(getParameters().getStorageServerConnection().getconnection(), LockMessagesMatchUtil.STORAGE_CONNECTION); return locks; }
Source:
<code>private Comparable convert(AttributeType entryAttributeType, Comparable entryAttributeValue, Comparable givenAttributeValue) { Class<?> entryAttributeClass = entryAttributeValue != null ? entryAttributeValue.getClass() : null; if (entryAttributeType == AttributeType.ENUM) { return entryAttributeType.getConverter().convert(givenAttributeValue); } else { if (entryAttributeClass != null && entryAttributeClass.isAssignableFrom(givenAttributeValue.getClass())) { return givenAttributeValue; } else if (entryAttributeType != null) { return entryAttributeType.getConverter().convert(givenAttributeValue); } else { <START> TypeConverter tc = inferTypeConverter(entryAttributeClass); <END> if (tc != null) { return tc.convert(givenAttributeValue); } throw new QueryException("Unknown attribute type: " + givenAttributeValue.getClass().getName() + " for attribute: " + attributeName); } } }</code><technical_language>understanding, new date types registered in ReflectionHelper.getAttributeType, this custom type inference avoided indexes pick proper type well</technical_language>

Target:
private Comparable convert(AttributeType entryAttributeType, Comparable entryAttributeValue, Comparable givenAttributeValue) { Class<?> entryAttributeClass = entryAttributeValue != null ? entryAttributeValue.getClass() : null; if (entryAttributeType == AttributeType.ENUM) { return entryAttributeType.getConverter().convert(givenAttributeValue); } else { if (entryAttributeClass != null && entryAttributeClass.isAssignableFrom(givenAttributeValue.getClass())) { return givenAttributeValue; } else if (entryAttributeType != null) { return entryAttributeType.getConverter().convert(givenAttributeValue); } else { throw new QueryException("Unknown attribute type: " + givenAttributeValue.getClass().getName() + " for attribute: " + attributeName); } } }
Source:
<code>protected AggregateStateRecord newStorageRecord() { List<AggregateEventRecord> records = sequenceFor(id); List<Event> expectedEvents = records.stream() .map(TO_EVENT) <START> .collect(Collectors.toList()); <END> AggregateStateRecord record = AggregateStateRecord .newBuilder() .addAllEvent(expectedEvents) .build(); return record; }</code><technical_language>Please add a static import for toList()</technical_language>

Target:
protected AggregateStateRecord newStorageRecord() { List<AggregateEventRecord> records = sequenceFor(id); List<Event> expectedEvents = records.stream() .map(TO_EVENT) .collect(toList()); AggregateStateRecord record = AggregateStateRecord .newBuilder() .addAllEvent(expectedEvents) .build(); return record; }
Source:
<code>public boolean read() throws IOException { if (!hasReceive()) { <START> createNetworkReceive(); <END> metrics.transmissionRoundTripTime.update(time.milliseconds() - sendCompleteTime); } long startTimeMs = time.milliseconds(); long bytesRead = networkReceive.getReceivedBytes().readFrom(socketChannel); long readTimeMs = time.milliseconds() - startTimeMs; logger.trace("Bytes read " + bytesRead + " from using key Time: {}", socketChannel.socket().getRemoteSocketAddress(), getConnectionId(), readTimeMs); if (bytesRead > 0) { metrics.transmissionReceiveTime.update(readTimeMs); metrics.transmissionReceiveSize.update(bytesRead); } return networkReceive.getReceivedBytes().isReadComplete(); }</code><technical_language>prefer a return for explicitly set</technical_language>

Target:
public boolean read() throws IOException { if (!hasReceive()) { initializeNetworkReceive(); metrics.transmissionRoundTripTime.update(time.milliseconds() - sendCompleteTime); } long startTimeMs = time.milliseconds(); long bytesRead = networkReceive.getReceivedBytes().readFrom(socketChannel); long readTimeMs = time.milliseconds() - startTimeMs; logger.trace("Bytes read " + bytesRead + " from using key Time: {}", socketChannel.socket().getRemoteSocketAddress(), getConnectionId(), readTimeMs); if (bytesRead > 0) { metrics.transmissionReceiveTime.update(readTimeMs); metrics.transmissionReceiveSize.update(bytesRead); } return networkReceive.getReceivedBytes().isReadComplete(); }
Source:
<code>protected Map<String, GroupInfo> createGroupInfos() { HashMap<String, GroupInfo> groupInfos = new HashMap<>(); groupInfos.put("aggregate_report_max", createMaxGroupInfo()); LatencyValueSelector valueSelector = new LatencyValueSelector(false); StaticSeriesSelector seriesSelector = new StaticSeriesSelector(); String seriesName = String.format(PERCENTILE_FORMAT, Integer.valueOf(95)); seriesSelector.setSeriesName(seriesName); <START> groupInfos.put(PERCENTILE_PROPERTY, END> createPercentileGroupInfo(PERCENTILE_PROPERTY, 95, seriesName,valueSelector,seriesSelector)); return groupInfos; }</code><technical_language>I $NON-NLS-1$ is required here, String literals</technical_language>

Target:
protected Map<String, GroupInfo> createGroupInfos() { HashMap<String, GroupInfo> groupInfos = new HashMap<>(); groupInfos.put("aggregate_report_max", createMaxGroupInfo()); LatencyValueSelector valueSelector = new LatencyValueSelector(false); StaticSeriesSelector seriesSelector = new StaticSeriesSelector(); String seriesName = String.format(PERCENTILE_FORMAT, Integer.valueOf(95)); seriesSelector.setSeriesName(seriesName); groupInfos.put(PERCENTILE_PROPERTY, createPercentileGroupInfo(PERCENTILE_PROPERTY, seriesName,valueSelector,seriesSelector)); return groupInfos; }
Source:
<code>public void checkHandlingOfFactoryNames() { createFactoryFromWorkspaceWithProject(FACTORY_NAME_EXIST); openNewFactoryPage(); createFactoryPage.clickOnWorkspaceFromList(PROJECT_WS_NAME); createFactoryPage.typeFactoryName(""); createFactoryPage.waitErrorMessageNotVisible(); assertTrue(createFactoryPage.isCreateFactoryButtonEnabled()); createFactoryPage.typeFactoryName(generate("", 2)); createFactoryPage.waitErrorMessage(TOO_SHORT_NAME_MESAAGE); assertFalse(createFactoryPage.isCreateFactoryButtonEnabled()); createFactoryPage.typeFactoryName(MIN_FACTORY_NAME); createFactoryPage.waitErrorMessageNotVisible(); assertTrue(createFactoryPage.isCreateFactoryButtonEnabled()); createFactoryPage.typeFactoryName(SPECIAL_SYMBOLS_NAME); createFactoryPage.waitErrorMessage(SPECIAL_SYMBOLS_ERROR_MESSAGE); assertFalse(createFactoryPage.isCreateFactoryButtonEnabled()); createFactoryPage.typeFactoryName(generate("", 21)); createFactoryPage.waitErrorMessage(TOO_LONG_NAME_MESSAGE); assertFalse(createFactoryPage.isCreateFactoryButtonEnabled()); createFactoryPage.typeFactoryName(MAX_FACTORY_NAME); createFactoryPage.waitErrorMessageNotVisible(); assertTrue(createFactoryPage.isCreateFactoryButtonEnabled()); createFactoryPage.typeFactoryName(FACTORY_NAME_EXIST); createFactoryPage.waitErrorMessage(EXIST_NAME_ERROR_MESSAGE); <START> assertTrue(createFactoryPage.isCreateFactoryButtonEnabled()); <END> }</code><technical_language>assertFalse fixing test</technical_language>

Target:
public void checkHandlingOfFactoryNames() { createFactoryFromWorkspaceWithProject(FACTORY_NAME_EXIST); openNewFactoryPage(); createFactoryPage.clickOnWorkspaceFromList(PROJECT_WS_NAME); createFactoryPage.typeFactoryName(""); createFactoryPage.waitErrorMessageNotVisible(); assertTrue(createFactoryPage.isCreateFactoryButtonEnabled()); createFactoryPage.typeFactoryName(generate("", 2)); createFactoryPage.waitErrorMessage(TOO_SHORT_NAME_MESAAGE); assertFalse(createFactoryPage.isCreateFactoryButtonEnabled()); createFactoryPage.typeFactoryName(MIN_FACTORY_NAME); createFactoryPage.waitErrorMessageNotVisible(); assertTrue(createFactoryPage.isCreateFactoryButtonEnabled()); createFactoryPage.typeFactoryName(SPECIAL_SYMBOLS_NAME); createFactoryPage.waitErrorMessage(SPECIAL_SYMBOLS_ERROR_MESSAGE); assertFalse(createFactoryPage.isCreateFactoryButtonEnabled()); createFactoryPage.typeFactoryName(generate("", 21)); createFactoryPage.waitErrorMessage(TOO_LONG_NAME_MESSAGE); assertFalse(createFactoryPage.isCreateFactoryButtonEnabled()); createFactoryPage.typeFactoryName(MAX_FACTORY_NAME); createFactoryPage.waitErrorMessageNotVisible(); assertTrue(createFactoryPage.isCreateFactoryButtonEnabled()); createFactoryPage.typeFactoryName(FACTORY_NAME_EXIST); createFactoryPage.waitErrorMessage(EXIST_NAME_ERROR_MESSAGE); assertFalse(createFactoryPage.isCreateFactoryButtonEnabled()); }
Source:
<code>public String toString() { StringBuilder builder = new StringBuilder(50); builder.append("search type: "); builder.append(getSearchTypeValue()); builder.append(", search pattern: ["); builder.append(getSearchPattern()); <START> builder.append("], case sensitive? "); <END> builder.append(getCaseSensitive()); builder.append(" [from: "); builder.append(getSearchFrom()); builder.append(", max: "); builder.append(getMaxCount()); builder.append("] "); builder.append(super.toString()); return builder.toString(); }</code><technical_language>consistency of classes, I suggest remove "?" string well. thanks</technical_language>

Target:
public String toString() { StringBuilder builder = new StringBuilder(50); builder.append("search type: "); builder.append(getSearchTypeValue()); builder.append(", search pattern: ["); builder.append(getSearchPattern()); builder.append("], case sensitive: "); builder.append(getCaseSensitive()); builder.append(" [from: "); builder.append(getSearchFrom()); builder.append(", max: "); builder.append(getMaxCount()); builder.append("] "); builder.append(super.toString()); return builder.toString(); }
Source:
<code>public static boolean isChunkUpload(Map<String, Object> args) throws RestServiceException { <START> return getHeader(args, Headers.CHUNK_UPLOAD_SESSION, false) != null; <END> }</code><technical_language>reuse x-ambry-chunk-upload (instead of session)</technical_language>

Target:
public static boolean isChunkUpload(Map<String, Object> args) throws RestServiceException { return getHeader(args, Headers.CHUNK_UPLOAD, false) != null; }
Source:
<code>private Value(String string) { ValueType t = ValueType.STRING; double d = 0; long l = 0; Object o = string; try { d = l = Long.parseLong(string); o = l; t = ValueType.LONG; } catch (NumberFormatException e) { try { o = d = Double.parseDouble(string); t = ValueType.DOUBLE; } catch (NumberFormatException e2) { } } if (string.contains(",") && t == ValueType.STRING) { t = ValueType.LIST; String[] rawValues = string.split(","); List<Value> processedValues = new ArrayList<>(rawValues.length); for (String rawValue : rawValues) { <START> processedValues.add(new Value(rawValue.trim())); <END> } o = processedValues; } type = t; doubleValue = d; longValue = l; objectValue = o; }</code><technical_language>If eventually find out need string, trimming lose whitespaces (you re-join elements). Also, single element lists detected. add a method try convert list appropriate</technical_language>

Target:
private Value(String string) { ValueType t = ValueType.STRING; double d = 0; long l = 0; Object o = string; try { d = l = Long.parseLong(string); o = l; t = ValueType.LONG; } catch (NumberFormatException e) { try { o = d = Double.parseDouble(string); t = ValueType.DOUBLE; } catch (NumberFormatException e2) { } } type = t; doubleValue = d; longValue = l; objectValue = o; }
Source:
<code>public void visitCallExpression(CallExpressionTree tree) { <START> ExpressionTree callee = tree.callee(); <END> if (callee.is(Tree.Kind.IDENTIFIER_REFERENCE)) { SyntaxToken token = ((IdentifierTree)callee).identifierToken(); if ("Function".equals(token.text()) && tree.arguments() != null && ! tree.arguments().parameters().isEmpty()) { addIssue(new PreciseIssue(this, new IssueLocation(callee, callee, MESSAGE))); } } super.visitCallExpression(tree); }</code><technical_language>@ivandalbosco Code of this method duplicates block line 61 refactored</technical_language>

Target:
public void visitCallExpression(CallExpressionTree tree) { if (isNonEmptyFunctionConstructor(tree.callee(), tree.arguments())) { addIssue(tree.callee(), MESSAGE); } super.visitCallExpression(tree); }
Source:
<code>public boolean prepare() throws Exception { if (!prepared) { prepared = true; super.prepare(); ProjectLauncher launcher = getProjectLauncher(); if (controlPort > 0) { launcher.getRunProperties() .put(TESTER_CONTROLPORT, "" + controlPort); if (host != null) launcher.getRunProperties() .put(TESTER_HOST, "" + host); } else if (port > 0) { launcher.getRunProperties() .put(TESTER_PORT, "" + port); if (host != null) launcher.getRunProperties() .put(TESTER_HOST, "" + host); } launcher.getRunProperties() .put(TESTER_UNRESOLVED, getProject().getProperty(Constants.TESTUNRESOLVED, "true")); launcher.getRunProperties() .put(TESTER_DIR, getReportDir().getAbsolutePath()); launcher.getRunProperties() .put(TESTER_CONTINUOUS, "" + getContinuous()); if (getProject().is(Constants.RUNTRACE)) launcher.getRunProperties() .put(TESTER_TRACE, "true"); Collection<String> testnames = getTests(); if (testnames.size() > 0) { launcher.getRunProperties() <START> .put(TESTER_NAMES, Processor.join(testnames.stream() <END> .map(ProjectTesterImpl::maybeQuote) .collect(Collectors.toList()))); } launcher.addRunBundle(me.getFile() .getAbsolutePath()); launcher.prepare(); } return true; }</code><technical_language>busy stream/map list a list join a string. straight java .put(TESTER_NAMES, testnames.stream() .map(ProjectTesterImpl::maybeQuote) .collect(Collectors.joining(",")));</technical_language>

Target:
public boolean prepare() throws Exception { if (!prepared) { prepared = true; super.prepare(); ProjectLauncher launcher = getProjectLauncher(); if (controlPort > 0) { launcher.getRunProperties() .put(TESTER_CONTROLPORT, "" + controlPort); if (host != null) launcher.getRunProperties() .put(TESTER_HOST, "" + host); } else if (port > 0) { launcher.getRunProperties() .put(TESTER_PORT, "" + port); if (host != null) launcher.getRunProperties() .put(TESTER_HOST, "" + host); } launcher.getRunProperties() .put(TESTER_UNRESOLVED, getProject().getProperty(Constants.TESTUNRESOLVED, "true")); launcher.getRunProperties() .put(TESTER_DIR, getReportDir().getAbsolutePath()); launcher.getRunProperties() .put(TESTER_CONTINUOUS, "" + getContinuous()); if (getProject().is(Constants.RUNTRACE)) launcher.getRunProperties() .put(TESTER_TRACE, "true"); Collection<String> testnames = getTests(); if (testnames.size() > 0) { launcher.getRunProperties() .put(TESTER_NAMES, testnames.stream() .map(ProjectTesterImpl::maybeQuote) .collect(Collectors.joining(","))); } launcher.addRunBundle(me.getFile() .getAbsolutePath()); launcher.prepare(); } return true; }
Source:
<code>public <T> T toObject(ParameterizedTypeReference<T> type) { Assert.notNull(type, "Target type must not be null!"); <START> final String url = traverseToFinalUrl(true); <END> return operations.exchange(url, GET, prepareRequest(headers), type).getBody(); }</code><technical_language>need final</technical_language>

Target:
public <T> T toObject(ParameterizedTypeReference<T> type) { Assert.notNull(type, "Target type must not be null!"); return operations.exchange(traverseToFinalUrl(true), GET, prepareRequest(headers), type).getBody(); }
Source:
<code>public synchronized MetricCollector init(HiveConf conf) { if (!isInited) { <START> maxSize = MetastoreConf.getLongVar(conf, MetastoreConf.ConfVars.REPL_METRICS_CACHE_MAXSIZE); <END> isInited = true; } return instance; }</code><technical_language>This in HS2 process, in HMS, reason conf is in MetastoreConf in HiveConf</technical_language>

Target:
public synchronized MetricCollector init(HiveConf conf) { if (!isInited) { maxSize = getMaxSize(conf); isInited = true; } return instance; }
Source:
<code>protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mMapView = findViewById(R.id.mapView); ArcGISMap map = new ArcGISMap(Basemap.Type.STREETS, 48.354406, -99.998267, 2); mMapView.setMap(map); mButton = findViewById(R.id.applyRenderer); <START> final ArcGISMapImageLayer imageLayer = new ArcGISMapImageLayer("<LINK_0>"); <END> imageLayer.addDoneLoadingListener(new Runnable() { @Override public void run() { if(imageLayer.getLoadStatus() == LoadStatus.LOADED){ mMapView.setViewpointGeometryAsync(imageLayer.getFullExtent()); SublayerList sublayers = imageLayer.getSublayers(); countiesSublayer = (ArcGISMapImageSublayer) sublayers.get(2); } else { Toast.makeText(MainActivity.this,"ERROR:Layer did not load",Toast.LENGTH_LONG).show(); } } }); map.getOperationalLayers().add(imageLayer); final ClassBreaksRenderer classBreaksRenderer = createPopulationClassBreaksRenderer(); mButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { countiesSublayer.setRenderer(classBreaksRenderer) ; } }); }</code><technical_language>extract url a string resource</technical_language>

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mMapView = findViewById(R.id.mapView); ArcGISMap map = new ArcGISMap(Basemap.Type.STREETS, 48.354406, -99.998267, 2); mMapView.setMap(map); Button renderButton = findViewById(R.id.applyRenderer); final ArcGISMapImageLayer imageLayer = new ArcGISMapImageLayer(getString(R.string.census_map_server)); imageLayer.addDoneLoadingListener(() -> { if(imageLayer.getLoadStatus() == LoadStatus.LOADED){ mMapView.setViewpointGeometryAsync(imageLayer.getFullExtent()); SublayerList sublayers = imageLayer.getSublayers(); countiesSublayer = (ArcGISMapImageSublayer) sublayers.get(2); } else { Log.e(TAG,imageLayer.getLoadError().getMessage()); } }); map.getOperationalLayers().add(imageLayer); final ClassBreaksRenderer classBreaksRenderer = createPopulationClassBreaksRenderer(); renderButton.setOnClickListener(v -> countiesSublayer.setRenderer(classBreaksRenderer)); }
Source:
<code>public static String convertXMLSourceToString(Source source) { StringWriter stringWriter = null; String xmlString; try { <START> stringWriter = new StringWriter(); <END> StreamResult xmlOutput = new StreamResult(stringWriter); TransformerFactory transformerFactory = TransformerFactory.newInstance(); transformerFactory.setAttribute("indent-number", 4); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.transform(source, xmlOutput); xmlString = xmlOutput.getWriter().toString(); } catch (TransformerException e) { logger.error("Exception occurred while converting doc to string: ", e); throw new RuntimeException("Exception occurred while converting doc to string: ", e); } finally { if (stringWriter != null) { try { stringWriter.close(); } catch (IOException ignored) { } } } return xmlString; }</code><technical_language>auto closable pattern here</technical_language>

Target:
public static String convertXMLSourceToString(Source source) { try (StringWriter stringWriter = new StringWriter()) { StreamResult xmlOutput = new StreamResult(stringWriter); TransformerFactory transformerFactory = TransformerFactory.newInstance(); transformerFactory.setAttribute("indent-number", 4); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.transform(source, xmlOutput); return xmlOutput.getWriter().toString(); } catch (TransformerException e) { logger.error("Exception occurred while converting doc to string: ", e); throw new RuntimeException("Exception occurred while converting doc to string: ", e); } catch (IOException e) { logger.error("Exception occurred while closing the StringWriter: ", e); throw new RuntimeException("Exception occurred while closing the StringWriter: ", e); } }
Source:
<code>StringRepresentation getInstanceCurrentStatesRepresentation(String clusterName, String instanceName) throws JsonGenerationException, JsonMappingException, IOException { ZkClient zkClient = (ZkClient) getContext().getAttributes().get(RestAdminApplication.ZKCLIENT); ; String instanceSessionId = ClusterRepresentationUtil.getInstanceSessionId(zkClient, clusterName, instanceName); String message = ClusterRepresentationUtil <START> .getMultiInstancePropertyNameListsAsString(zkClient, clusterName, instanceName, <END> Arrays.asList(PropertyType.CURRENTSTATES, PropertyType.TASKCURRENTSTATES), instanceSessionId); StringRepresentation representation = new StringRepresentation(message, MediaType.APPLICATION_JSON); return representation; }</code><technical_language>This is fine, I guess deprecate older one</technical_language>

Target:
StringRepresentation getInstanceCurrentStatesRepresentation(String clusterName, String instanceName) throws JsonGenerationException, JsonMappingException, IOException { ZkClient zkClient = (ZkClient) getContext().getAttributes().get(RestAdminApplication.ZKCLIENT); ; String instanceSessionId = ClusterRepresentationUtil.getInstanceSessionId(zkClient, clusterName, instanceName); String message = ClusterRepresentationUtil .getInstancePropertyNameListAsString(zkClient, clusterName, instanceName, PropertyType.CURRENTSTATES, instanceSessionId, MediaType.APPLICATION_JSON); StringRepresentation representation = new StringRepresentation(message, MediaType.APPLICATION_JSON); return representation; }
Source:
<code>public List<HueLamp> getLampsById(List<String> ids) { List<HueLamp> lamps = new ArrayList<>(); <START> ids.forEach(id -> lamps.add(hueFacade.getAvailableLamps().get(id))); <END> return lamps; }</code><technical_language>I guess stream, map, collect here</technical_language>

Target:
public Set<HueLamp> getLampsById(List<String> ids) { return ids.stream() .map(id -> hueFacade.getAvailableLamps().get(id)) .collect(Collectors.toSet()); }
Source:
<code>public static void main(String[] args) { TextAnalyticsApiKeyCredential credential = new TextAnalyticsApiKeyCredential("{api_key}"); TextAnalyticsAsyncClient client = new TextAnalyticsClientBuilder() .apiKey(credential) .endpoint("{endpoint}") .buildAsyncClient(); String text = "My cat might need to see a veterinarian."; client.extractKeyPhrases(text).subscribe( keyPhrase -> System.out.printf("Recognized phrases: %s.%n", keyPhrase), error -> System.err.println("There was an error extracting key phrases of the text." + error), () -> System.out.println("Key phrases extracted.")); credential.updateCredential("{valid_api_key}"); <START> System.out.println("Recognized phrases:"); <END> client.extractKeyPhrases(text).subscribe( keyPhrase -> System.out.printf("%s.%n", keyPhrase), error -> System.err.println("There was an error extracting key phrases of the text." + error), () -> System.out.println("Key phrases extracted.")); try { TimeUnit.SECONDS.sleep(5); } catch (InterruptedException ignored) { } }</code><technical_language>nit: Extracted phrases, match rest</technical_language>

Target:
public static void main(String[] args) { TextAnalyticsApiKeyCredential credential = new TextAnalyticsApiKeyCredential("{api_key}"); TextAnalyticsAsyncClient client = new TextAnalyticsClientBuilder() .apiKey(credential) .endpoint("{endpoint}") .buildAsyncClient(); String text = "My cat might need to see a veterinarian."; System.out.println("Extracted phrases:"); client.extractKeyPhrases(text).subscribe( keyPhrase -> System.out.printf("%s.%n", keyPhrase), error -> System.err.println("There was an error extracting key phrases of the text." + error), () -> System.out.println("Key phrases extracted.")); credential.updateCredential("{valid_api_key}"); System.out.println("Extracted phrases:"); client.extractKeyPhrases(text).subscribe( keyPhrase -> System.out.printf("%s.%n", keyPhrase), error -> System.err.println("There was an error extracting key phrases of the text." + error), () -> System.out.println("Key phrases extracted.")); try { TimeUnit.SECONDS.sleep(5); } catch (InterruptedException ignored) { } }
Source:
<code>public static PhoenixExecutor createExecutor(Map<String, Object> jdbcProps) throws Exception { Util.validateJDBCProperties(jdbcProps, Lists.newArrayList("jdbcDriverClass", "jdbcUrl")); String driverClassName = (String) jdbcProps.get("jdbcDriverClass"); log.info("jdbc driver class: [{}]", driverClassName); Class.forName(driverClassName); String jdbcUrl = (String) jdbcProps.get("jdbcUrl"); log.info("jdbc url is: ", jdbcUrl); int queryTimeOutInSecs = -1; if(jdbcProps.containsKey("queryTimeoutInSecs")) { int timeout = (Integer) jdbcProps.get("queryTimeoutInSecs"); if(timeout < 0) { throw new IllegalArgumentException("queryTimeoutInSecs property can not be negative"); } } HikariConfig hikariConfig = new HikariConfig(); hikariConfig.setJdbcUrl(jdbcUrl); JdbcClient jdbcClient = new JdbcClient(jdbcUrl); log.info("creating tables"); String createPath = "phoenix/create_tables.sql"; <START> jdbcClient.runScript(createPath); <END> final HikariCPConnectionBuilder connectionBuilder = new HikariCPConnectionBuilder(hikariConfig); final ExecutionConfig executionConfig = new ExecutionConfig(queryTimeOutInSecs); CacheBuilder cacheBuilder = null; if(jdbcProps.containsKey("cacheSize")) { cacheBuilder = CacheBuilder.newBuilder().maximumSize((Integer)jdbcProps.get("cacheSize")); } return new PhoenixExecutor(executionConfig, connectionBuilder, cacheBuilder); }</code><technical_language>move this out of here. lets start multiple IoTaS webservers running create tables part of server start is a good idea. Lets part of shell script add another method ./bin/iotas setup</technical_language>

Target:
public static PhoenixExecutor createExecutor(Map<String, Object> jdbcProps) throws Exception { Util.validateJDBCProperties(jdbcProps, Lists.newArrayList("jdbcDriverClass", "jdbcUrl")); String driverClassName = (String) jdbcProps.get("jdbcDriverClass"); log.info("jdbc driver class: [{}]", driverClassName); Class.forName(driverClassName); String jdbcUrl = (String) jdbcProps.get("jdbcUrl"); log.info("jdbc url is: ", jdbcUrl); int queryTimeOutInSecs = -1; if(jdbcProps.containsKey("queryTimeoutInSecs")) { queryTimeOutInSecs = (Integer) jdbcProps.get("queryTimeoutInSecs"); if(queryTimeOutInSecs < 0) { throw new IllegalArgumentException("queryTimeoutInSecs property can not be negative"); } } HikariConfig hikariConfig = new HikariConfig(); hikariConfig.setJdbcUrl(jdbcUrl); JdbcClient jdbcClient = new JdbcClient(jdbcUrl); log.info("creating tables"); String createPath = "phoenix/create_tables.sql"; jdbcClient.runScript(createPath); final HikariCPConnectionBuilder connectionBuilder = new HikariCPConnectionBuilder(hikariConfig); final ExecutionConfig executionConfig = new ExecutionConfig(queryTimeOutInSecs); CacheBuilder cacheBuilder = null; if(jdbcProps.containsKey("cacheSize")) { cacheBuilder = CacheBuilder.newBuilder().maximumSize((Integer)jdbcProps.get("cacheSize")); } return new PhoenixExecutor(executionConfig, connectionBuilder, cacheBuilder); }
Source:
<code>public Map<String, List<String>> confusions() throws IOException { <START> Map<String, List<String>> res = new HashMap<>(); <END> for (CSVRecord record : parse(M2Resources.CONFUSIONS)) { String from = record.get("charFrom"); String to = record.get("charTo"); res.computeIfAbsent(from, x -> new ArrayList<>()).add(to); } return res; }</code><technical_language>Multimaps.newListMultimap return Multimaps.asMap(listMultiMap)</technical_language>

Target:
public Map<String, Collection<String>> confusions() throws IOException { Multimap<String, String> res = Multimaps.newListMultimap( new HashMap<>(), ArrayList::new); for (CSVRecord record : parse(M2Resources.CONFUSIONS)) { res.put(record.get("charFrom"), record.get("charTo")); } return Multimaps.asMap(res); }
Source:
<code>public void testSetUnaryTestsWhenUnaryTestsIsNotNull() { final ItemDefinition wb = mock(ItemDefinition.class); <START> ArgumentCaptor<UnaryTests> argument = ArgumentCaptor.forClass(UnaryTests.class); <END> final org.kie.dmn.model.api.ItemDefinition dmn = mock(org.kie.dmn.model.api.ItemDefinition.class); final org.kie.dmn.model.api.UnaryTests dmnAllowedValues = mock(org.kie.dmn.model.api.UnaryTests.class); when(dmn.getAllowedValues()).thenReturn(dmnAllowedValues); setUnaryTests(wb, dmn); verify(wb).setAllowedValues(any(UnaryTests.class)); verify(wb).setAllowedValues(argument.capture()); assertEquals(wb, argument.getValue().getParent()); }</code><technical_language>declare argument variable final</technical_language>

Target:
public void testSetUnaryTestsWhenUnaryTestsIsNotNull() { final ItemDefinition wb = mock(ItemDefinition.class); final ArgumentCaptor<UnaryTests> argument = ArgumentCaptor.forClass(UnaryTests.class); final org.kie.dmn.model.api.ItemDefinition dmn = mock(org.kie.dmn.model.api.ItemDefinition.class); final org.kie.dmn.model.api.UnaryTests dmnAllowedValues = mock(org.kie.dmn.model.api.UnaryTests.class); when(dmn.getAllowedValues()).thenReturn(dmnAllowedValues); setUnaryTests(wb, dmn); verify(wb).setAllowedValues(argument.capture()); assertEquals(wb, argument.getValue().getParent()); }
Source:
<code>public void customerClassLoaderFunction() throws IOException { try { Path rootDir = fakeFileSystem(EXAMPLE_FUNCTION); URLClassLoader customerClassLoader = new CustomerClassLoader( rootDir.resolve("user/path").toString(), rootDir.resolve("opt/java").toString(), ClassLoader.getSystemClassLoader()); List<String> res = strip("file:" + rootDir.toString(), customerClassLoader.getURLs()); Assertions.assertEquals(Arrays.asList( "/user/path/", "/user/path/lib/4.jar", "/user/path/lib/A.jar", "/user/path/lib/a.jar", "/user/path/lib/b.jar", "/user/path/lib/z.jar", "/user/path/lib/λ.jar"), res); } catch(Throwable t) { <START> if (!System.getProperty("sun.jnu.encoding").toLowerCase().contains("utf")){ <END> Assertions.assertTrue(t.getMessage().contains("Malformed input or input contains unmappable characters")); } else { throw t; } } }</code><technical_language>Is this property guaranteed set? if null</technical_language>

Target:
public void customerClassLoaderFunction() throws IOException { try { Path rootDir = fakeFileSystem(EXAMPLE_FUNCTION); URLClassLoader customerClassLoader = new CustomerClassLoader( rootDir.resolve("user/path").toString(), rootDir.resolve("opt/java").toString(), ClassLoader.getSystemClassLoader()); List<String> res = strip("file:" + rootDir.toString(), customerClassLoader.getURLs()); Assertions.assertEquals(Arrays.asList( "/user/path/", "/user/path/lib/4.jar", "/user/path/lib/A.jar", "/user/path/lib/a.jar", "/user/path/lib/b.jar", "/user/path/lib/z.jar", "/user/path/lib/λ.jar"), res); } catch(Throwable t) { String systemEncoding = System.getProperty("sun.jnu.encoding"); if (systemEncoding != null && !systemEncoding.toLowerCase().contains("utf")){ Assertions.assertTrue(t.getMessage().contains("Malformed input or input contains unmappable characters")); } else { throw t; } } }
Source:
<code>public void shouldRespondWith422_whenEmailIsGreaterThan254Chars() { String payload = toJson( Map.of("amount", 100, "reference", "Some ref", "description", "hi", "return_url", "<LINK_0>", <START> "email", "aVeryLongEaVeryLongEaVeryLongEaVeryLongEaVeryLongEaVeryLongEaVeryLongEaVeryLongEaVeryLongEaVeryLongEaVeryLongEaVeryLongEaVeryLongEaVeryLongEaVeryLongEaVeryLongEaVeryLongEaVeryLongEaVeryLongEaVeryLongE@aVeryLongEaVeryLongEaVeryLongEaVeryLongEaVeryLongEaVeryLongEaVeryLongEaVeryLongEaVeryLongEaVeryLongE.com")); <END> postPaymentResponse(payload) .statusCode(422) .contentType(JSON) .body("size()", is(3)) .body("field", is("email")) .body("code", is("P0102")) .body("description", is("Invalid attribute value: email. Must be less than or equal to 254 characters length")); }</code><technical_language>In Java 11 do " ".repeat(255); I a bit nicer</technical_language>

Target:
public void shouldRespondWith422_whenEmailIsGreaterThan254Chars() { String payload = toJson( Map.of("amount", 100, "reference", "Some ref", "description", "hi", "return_url", "<LINK_0>", "email", "aVeryLongEmail".repeat(20) + "@email.invalid")); postPaymentResponse(payload) .statusCode(422) .contentType(JSON) .body("size()", is(3)) .body("field", is("email")) .body("code", is("P0102")) .body("description", is("Invalid attribute value: email. Must be less than or equal to 254 characters length")); }
Source:
<code>protected Result check() throws Exception { Result result; <START> try (Handle handle = dbi.open()) { <END> result = executorService.submit(new Callable<Result>() { @Override public Result call() throws Exception { handle.execute(validationQuery); return Result.healthy(); } }).get(duration.getQuantity(), duration.getUnit()); } catch (Exception e) { result = Result.unhealthy("Unable to successfully run validation query in %s", duration); } return result; }</code><technical_language>this potentially block is a connection available</technical_language>

Target:
protected Result check() throws Exception { return timeBoundHealthCheck.check(new Callable<Result>() { @Override public Result call() throws Exception { try (Handle handle = dbi.open()) { handle.execute(validationQuery); return Result.healthy(); } } }); }
Source:
<code>public void sizeWhenReadingFilesystemThenIsCorrectNumberOfSchemaFiles() throws IOException { ClassPathResource resource = new ClassPathResource(this.schemaDocumentLocation); String[] schemas = resource.getFile().getParentFile().list((dir, name) -> name.endsWith(".xsd")); assertThat(schemas.length).isEqualTo(14) .withFailMessage("the count is equal to 12, if not then schemaDocument needs updating"); <START> } <END></code><technical_language>if fail message needs updating</technical_language>

Target:
public void sizeWhenReadingFilesystemThenIsCorrectNumberOfSchemaFiles() throws IOException { ClassPathResource resource = new ClassPathResource(this.schemaDocumentLocation); String[] schemas = resource.getFile().getParentFile().list((dir, name) -> name.endsWith(".xsd")); assertThat(schemas.length).isEqualTo(14) .withFailMessage("the count is equal to 14, if not then schemaDocument needs updating"); }
Source:
<code>public String title() { <START> return "Upload Dashboards"; <END> }</code><technical_language>Consider i18n for this title</technical_language>

Target:
public String title() { return i18n.uploadDashboardsTitle(); }
Source:
<code>public String printInvocations(Object mock) { Collection<Invocation> invocations = Mockito.mockingDetails(mock).getInvocations(); Collection<Stubbing> stubbings = Mockito.mockingDetails(mock).getStubbings(); if (invocations.isEmpty() && stubbings.isEmpty()) { return "No interactions and stubbings found for mock: " + mock; } <START> String out = ""; <END> int x = 1; for(Invocation i:invocations) { if (x == 1) { out += line("[Mockito] Interactions of: " + mock); } out += line(" " + x++ + ". " + i.toString()); out += line(" " + i.getLocation()); if (i.stubInfo() != null) { out += line(" - stubbed " + i.stubInfo().stubbedAt()); } } LinkedList<Stubbing> unused = ListUtil.filter(stubbings, new ListUtil.Filter<Stubbing>() { public boolean isOut(Stubbing s) { return s.wasUsed(); } }); if (unused.isEmpty()) { return out; } out += line("[Mockito] Unused stubbings of: " + mock); x = 1; for(Stubbing s:stubbings) { out += line(" " + x++ + ". " + s.getInvocation().toString()); out += line(" - stubbed " + s.getInvocation().getLocation()); } return out; }</code><technical_language>out StringBuilder instead of String</technical_language>

Target:
public String printInvocations(Object mock) { Collection<Invocation> invocations = Mockito.mockingDetails(mock).getInvocations(); Collection<Stubbing> stubbings = Mockito.mockingDetails(mock).getStubbings(); if (invocations.isEmpty() && stubbings.isEmpty()) { return "No interactions and stubbings found for mock: " + mock; } StringBuilder sb = new StringBuilder(); int x = 1; for(Invocation i:invocations) { if (x == 1) { sb.append("[Mockito] Interactions of: ").append(mock).append("\n"); } sb.append(" ").append(x++).append(". ").append(i.toString()).append("\n"); sb.append(" ").append(i.getLocation()).append("\n"); if (i.stubInfo() != null) { sb.append(" - stubbed ").append(i.stubInfo().stubbedAt()).append("\n"); } } LinkedList<Stubbing> unused = ListUtil.filter(stubbings, new ListUtil.Filter<Stubbing>() { public boolean isOut(Stubbing s) { return s.wasUsed(); } }); if (unused.isEmpty()) { return sb.toString(); } sb.append("[Mockito] Unused stubbings of: " + mock).append("\n"); x = 1; for(Stubbing s:stubbings) { sb.append(" ").append(x++).append(". ").append(s.getInvocation()).append("\n"); sb.append(" - stubbed ").append(s.getInvocation().getLocation()).append("\n"); } return sb.toString(); }