auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public @NonNull TmfModelResponse<@NonNull List<@NonNull ITimeGraphRowModel>> fetchRowModel(@NonNull SelectionTimeQueryFilter filter, @Nullable IProgressMonitor monitor) { IGraphWorker graphWorker = getCurrent(); if (graphWorker == null) { return new TmfModelResponse<>(null, Status.COMPLETED, CommonStatusMessage.COMPLETED); } Pair<HorizontalLinksVisitor, VerticalLinksVisitor> visitors = fHorizontalVisitorCache.getIfPresent(graphWorker); if (visitors == null) { return new TmfModelResponse<>(null, Status.COMPLETED, CommonStatusMessage.COMPLETED); } <START> HorizontalLinksVisitor visitor = visitors.getFirst(); <END> List<@NonNull ITimeGraphRowModel> rowModels = new ArrayList<>(); for (Long id : filter.getSelectedItems()) { Collection<ITimeGraphState> states = visitor.fStates.asMap().get(id); if (states != null) { List<ITimeGraphState> filteredStates = new ArrayList<>(); for (ITimeGraphState state : states) { if (overlaps(state.getStartTime(), state.getDuration(), filter.getTimesRequested())) { filteredStates.add(state); } } rowModels.add(new TimeGraphRowModel(id, filteredStates)); } } return new TmfModelResponse<>(rowModels, Status.COMPLETED, CommonStatusMessage.COMPLETED); }</code><technical_language>visitor.fHorizontal a small private class more readable</technical_language>

Target:
public @NonNull TmfModelResponse<@NonNull List<@NonNull ITimeGraphRowModel>> fetchRowModel(@NonNull SelectionTimeQueryFilter filter, @Nullable IProgressMonitor monitor) { IGraphWorker graphWorker = getCurrent(); if (graphWorker == null) { return new TmfModelResponse<>(null, Status.COMPLETED, CommonStatusMessage.COMPLETED); } CriticalPathVisitor visitor = fHorizontalVisitorCache.getIfPresent(graphWorker); if (visitor == null) { return new TmfModelResponse<>(null, Status.COMPLETED, CommonStatusMessage.COMPLETED); } List<@NonNull ITimeGraphRowModel> rowModels = new ArrayList<>(); for (Long id : filter.getSelectedItems()) { Collection<ITimeGraphState> states = visitor.fStates.asMap().get(id); if (states != null) { List<ITimeGraphState> filteredStates = new ArrayList<>(); for (ITimeGraphState state : states) { if (overlaps(state.getStartTime(), state.getDuration(), filter.getTimesRequested())) { filteredStates.add(state); } } rowModels.add(new TimeGraphRowModel(id, filteredStates)); } } return new TmfModelResponse<>(rowModels, Status.COMPLETED, CommonStatusMessage.COMPLETED); }
Source:
<code>public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Point point = (Point) o; <START> if (Double.compare(point.x, x) != 0) return false; <END> return Double.compare(point.y, y) == 0; }</code><technical_language>want consider want exact comparison for double values, i.e., willing allow differ some epsilon considered equal for purposes. equality criterion want use, early evaluation care of keeping number of comparisons down: return (Double.compare(point.x, x) == 0) && (Double.compare(point.y, y) == 0);</technical_language>

Target:
public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof Point)) { return false; } Point other = (Point) o; return (Double.compare(other.x, x) == 0 && Double.compare(other.y, y) == 0); }
Source:
<code>public void stop() throws MuleException { <START> LinkedList<Service> servicesWithSpecialStoppingOrder = new LinkedList<>(); <END> for (Service service : services) { if (service.getName().equals(SCHEDULER_SERVICE_ARTIFACT_ID)) { servicesWithSpecialStoppingOrder.addLast(service); } else if (service.getName().contains(HTTP_SERVICE_ARTIFACT_PREFIX)) { servicesWithSpecialStoppingOrder.addFirst(service); } else { doStopService(service); } } for (Service service : servicesWithSpecialStoppingOrder) { doStopService(service); } }</code><technical_language>new ArrayList<>(2) simply variables</technical_language>

Target:
public void stop() throws MuleException { Service schedulerService = null, httpService = null; for (Service service : services) { if (service.getName().equals(SCHEDULER_SERVICE_ARTIFACT_ID)) { schedulerService = service; } else if (service.getName().contains(HTTP_SERVICE_ARTIFACT_PREFIX)) { httpService = service; } else { doStopService(service); } } if (httpService != null) { doStopService(httpService); } if (schedulerService != null) { doStopService(schedulerService); } }
Source:
<code><START> public static synchronized String getUniqueId(String name) { <END> return getUniqueId(name, 256); }</code><technical_language>Remove synchronized keyword this method move method below</technical_language>

Target:
public static String getUniqueId(String name) { return getUniqueId(name, 256); }
Source:
<code>public void filterResponse(HttpResponse response, HttpMessageContents contents, HttpMessageInfo messageInfo) { if (!active) return; responses.add(new Response(messageInfo.getUrl(), response.getStatus().code(), response.getStatus().reasonPhrase(), toMap(response.headers()), contents.getContentType(), contents.getTextContents() )); if (response.getStatus().code() < 200 || response.getStatus().code() >= 300) return; String fileName = getFileName(response); if (fileName == null) return; File file = downloader.prepareTargetFile(config, fileName); try { FileUtils.writeByteArrayToFile(file, contents.getBinaryContents()); downloadedFiles.add(file); } catch (IOException e) { <START> log.error("Failed to save downloaded file to " + file.getAbsolutePath() + <END> " for url " + messageInfo.getUrl(), e); } }</code><technical_language>Format</technical_language>

Target:
public void filterResponse(HttpResponse response, HttpMessageContents contents, HttpMessageInfo messageInfo) { if (!active) return; responses.add(new Response(messageInfo.getUrl(), response.getStatus().code(), response.getStatus().reasonPhrase(), toMap(response.headers()), contents.getContentType(), contents.getTextContents() )); if (response.getStatus().code() < 200 || response.getStatus().code() >= 300) return; String fileName = getFileName(response); if (fileName == null) return; File file = downloader.prepareTargetFile(config, fileName); try { FileUtils.writeByteArrayToFile(file, contents.getBinaryContents()); downloadedFiles.add(file); } catch (IOException e) { log.error("Failed to save downloaded file to for url {}", file.getAbsolutePath(), messageInfo.getUrl(), e); } }
Source:
<code>private String createWFSTMessage(JSONObject jsonPayload) throws ActionException { <START> ByteArrayOutputStream baos = new ByteArrayOutputStream(); <END> try { Feature feature = getFeature(jsonPayload); FeatureWFSTRequestBuilder.insertFeature(baos, feature); } catch (XMLStreamException e) { LOG.error(e, "Failed to create WFS-T request"); throw new ActionException("Failed to create WFS-T request", e); } catch (JSONException e) { LOG.error(e, "JSON processing error"); throw new ActionException("JSON processing error", e); } catch (FactoryException e) { LOG.error(e, "Failed to create WFS-T request (crs)"); throw new ActionException("Failed to create WFS-T request (crs)", e); } return baos.toString(); }</code><technical_language>move ByteArrayOutputStream return clause try-catch block</technical_language>

Target:
private String createWFSTMessage(JSONObject jsonPayload) throws ActionException { try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); Feature feature = getFeature(jsonPayload); FeatureWFSTRequestBuilder.insertFeature(baos, feature); return baos.toString(); } catch (XMLStreamException e) { LOG.error(e, "Failed to create WFS-T request"); throw new ActionException("Failed to create WFS-T request", e); } catch (JSONException e) { LOG.error(e, "JSON processing error"); throw new ActionException("JSON processing error", e); } catch (FactoryException e) { LOG.error(e, "Failed to create WFS-T request (crs)"); throw new ActionException("Failed to create WFS-T request (crs)", e); } }
Source:
<code>public static java.nio.file.Path createMavenRepo() throws Exception { <START> java.nio.file.Path mavenRepoPathsitory = java.nio.file.Paths.get(System.getProperty("user.home"), ".m2/repository"); <END> if (!java.nio.file.Files.exists(mavenRepoPathsitory)) { logger.info("Creating a m2_repo into " + mavenRepoPathsitory); if (!java.nio.file.Files.exists(java.nio.file.Files.createDirectories(mavenRepoPathsitory))) { logger.error("Folder not writable to create Maven repo{}", mavenRepoPathsitory); throw new Exception("Folder not writable to create Maven repo:" + mavenRepoPathsitory); } } return mavenRepoPathsitory; }</code><technical_language>mavenRepoPathsitory unintended consequence of bulk rename :)</technical_language>

Target:
public static java.nio.file.Path createMavenRepo() throws Exception { java.nio.file.Path mavenRepoPath = java.nio.file.Paths.get(System.getProperty("user.home"), ".m2/repository"); if (!java.nio.file.Files.exists(mavenRepoPath)) { logger.info("Creating a m2_repo into " + mavenRepoPath); if (!java.nio.file.Files.exists(java.nio.file.Files.createDirectories(mavenRepoPath))) { logger.error("Folder not writable to create Maven repo{}", mavenRepoPath); throw new Exception("Folder not writable to create Maven repo:" + mavenRepoPath); } } return mavenRepoPath; }
Source:
<code>public List<String> getTags(String prefix) throws FeedbackException { String query = "{\n" + " \"size\": 0,\n" + " \"aggs\": {\n" + " \"terms\": {\n" + " \"terms\": {\n" + " \"field\": \"tags\",\n" + <START> " \"include\": \"" + prefix + ".*\"\n" + <END> " }\n" + " }\n" + " }\n" + "}"; Search.Builder builder = new Search.Builder(query).addType(TYPE); Search search = builder.build(); SearchResult result; try { result = client.execute(search); } catch (IOException e) { throw new FeedbackException("Failed to execute Tags search", e); } if (result == null) { return Collections.emptyList(); } final MetricAggregation aggregations = result.getAggregations(); if (aggregations == null) { return Collections.emptyList(); } final TermsAggregation terms = aggregations.getTermsAggregation("terms"); if (terms == null) { return Collections.emptyList(); } return terms.getBuckets().stream().map(TermsAggregation.Entry::getKey).collect(Collectors.toList()); }</code><technical_language>ensure prefix is properly escaped? query break if contains a " now</technical_language>

Target:
public List<String> getTags(String prefix) throws FeedbackException { String query = "{\n" + " \"size\": 0,\n" + " \"aggs\": {\n" + " \"terms\": {\n" + " \"terms\": {\n" + " \"field\": \"tags\",\n" + " \"include\": \"" + gson.toJson(prefix) + ".*\"\n" + " }\n" + " }\n" + " }\n" + "}"; Search.Builder builder = new Search.Builder(query).addType(TYPE); Search search = builder.build(); SearchResult result; try { result = client.execute(search); } catch (IOException e) { throw new FeedbackException("Failed to execute Tags search", e); } if (result == null) { return Collections.emptyList(); } final MetricAggregation aggregations = result.getAggregations(); if (aggregations == null) { return Collections.emptyList(); } final TermsAggregation terms = aggregations.getTermsAggregation("terms"); if (terms == null) { return Collections.emptyList(); } return terms.getBuckets().stream().map(TermsAggregation.Entry::getKey).collect(Collectors.toList()); }
Source:
<code>void insert(GroupInfo info) { Comparator<GroupInfo> c = new Comparator<GroupInfo>() { @Override public int compare(GroupInfo a, GroupInfo b) { int cmp = nullToEmpty(a.name()).compareTo(nullToEmpty(b.name())); if (cmp != 0) { return cmp; } return a.getGroupUUID().compareTo(b.getGroupUUID()); } public String nullToEmpty(String str) { return str == null ? "" : str; } }; <START> int insertPosition = table.getRowCount(); <END> for (int row = 1; row < table.getRowCount(); row++) { final GroupInfo i = getRowItem(row); if (i != null) { if (c.compare(info, i) == 0) { return; } if (c.compare(info, i) < 0) { insertPosition = row; break; } } } table.insertRow(insertPosition); applyDataRowStyle(insertPosition); populate(insertPosition, info); }</code><technical_language>of insertPosition of row loop finishes. remove insertPosition variable</technical_language>

Target:
void insert(GroupInfo info) { Comparator<GroupInfo> c = new Comparator<GroupInfo>() { @Override public int compare(GroupInfo a, GroupInfo b) { int cmp = nullToEmpty(a.name()).compareTo(nullToEmpty(b.name())); if (cmp != 0) { return cmp; } return a.getGroupUUID().compareTo(b.getGroupUUID()); } public String nullToEmpty(String str) { return str == null ? "" : str; } }; int insertPosition; for (insertPosition = 1; insertPosition < table.getRowCount(); insertPosition++) { final GroupInfo i = getRowItem(insertPosition); if (i != null) { if (c.compare(info, i) == 0) { return; } if (c.compare(info, i) < 0) { break; } } } table.insertRow(insertPosition); applyDataRowStyle(insertPosition); populate(insertPosition, info); }
Source:
<code>protected String buildValidationErrorMessageForSingleError(ErrorMessage errorMessage) { String errorMessageString = configurationService.getPropertyValueAsString(errorMessage.getErrorKey()); if (StringUtils.isBlank(errorMessageString)) { throw new RuntimeException("Cannot find error message for key: " + errorMessage.getErrorKey()); } <START> Object[] messageParameters = (Object[]) errorMessage.getMessageParameters(); <END> if (messageParameters != null && messageParameters.length > 0) { return MessageFormat.format(errorMessageString, messageParameters); } else { return errorMessageString; } }</code><technical_language>Is cast Object[] String[] needed? Also, is "!ObjectUtils.IsNull(messageParameters)" preferred "!= null" for array of objects</technical_language>

Target:
protected String buildValidationErrorMessageForSingleError(ErrorMessage errorMessage) { String errorMessageString = configurationService.getPropertyValueAsString(errorMessage.getErrorKey()); if (StringUtils.isBlank(errorMessageString)) { throw new RuntimeException("Cannot find error message for key: " + errorMessage.getErrorKey()); } String[] messageParameters = errorMessage.getMessageParameters(); if (ArrayUtils.isNotEmpty(messageParameters)) { return MessageFormat.format(errorMessageString, messageParameters); } else { return errorMessageString; } }
Source:
<code>public void connect() { if (fState == TargetNodeState.DISCONNECTED) { try { setTargetNodeState(TargetNodeState.CONNECTING); <START> Thread th= new Thread() { <END> @Override public void run() { try { fRemoteProxy.connect(new NullProgressMonitor()); handleConnected(); } catch (Exception e) { Activator.getDefault().logError(Messages.TraceControl_ConnectionFailure + " (" + getName() + "). \n", e); handleDisconnected(); } } }; th.start(); } catch (Exception e) { setTargetNodeState(TargetNodeState.DISCONNECTED); Activator.getDefault().logError(Messages.TraceControl_ConnectionFailure + " (" + getName() + "). \n", e); } } }</code><technical_language>done a job instead of regular thread. progress feedback event if a running progress bar</technical_language>

Target:
public void connect() { if (fState == TargetNodeState.DISCONNECTED) { try { setTargetNodeState(TargetNodeState.CONNECTING); Job job = new Job(format(Messages.TraceControl_OpenConnectionTo, getName())) { @Override protected IStatus run(IProgressMonitor monitor) { try { fRemoteProxy.connect(monitor); return Status.OK_STATUS; } catch (Exception e) { return new Status(IStatus.ERROR, Activator.PLUGIN_ID, Messages.TraceControl_ConnectionFailure, e); } } }; job.addJobChangeListener(new JobChangeAdapter() { @Override public void done(IJobChangeEvent event) { IStatus status = event.getResult(); if (status.isOK()) { handleConnected(); } else { handleDisconnected(); if (status.getSeverity() != IStatus.CANCEL) { Activator.getDefault().getLog().log(status); } } } }); job.schedule(); } catch (Exception e) { setTargetNodeState(TargetNodeState.DISCONNECTED); Activator.getDefault().logError(Messages.TraceControl_ConnectionFailure + " (" + getName() + "). \n", e); } } }
Source:
<code>public boolean isActive() { <START> long diff = this.state.startTime - System.currentTimeMillis(); <END> boolean isActive = this.state.isActive && (!this.state.isPaused) && (diff <= 0); if (!isActive) { LOGGER.info("[Ramp Is Isolated] (isActive = {}, isPause = {}, timeDiff = {}", this.state.isActive, this.state.isPaused, diff); } return isActive; }</code><technical_language>more easy understand timeDiff instead of diff</technical_language>

Target:
public boolean isActive() { long timeDiff = this.state.startTime - System.currentTimeMillis(); boolean isActive = this.state.isActive && (!this.state.isPaused) && (timeDiff <= 0); if (!isActive) { LOGGER.info("[Ramp Is Isolated] (isActive = {}, isPause = {}, timeDiff = {}", this.state.isActive, this.state.isPaused, timeDiff); } return isActive; }
Source:
<code>public void requestEmailSignInTwiceReturnsSameToken() { doReturn("something").when(cacheProvider).getString(CACHE_KEY); doReturn(account).when(accountDao).getAccount(any()); service.requestEmailSignIn(SIGN_IN_REQUEST_WITH_EMAIL); verify(cacheProvider, never()).setString(any(), any(), anyInt()); <START> verify(sendMailService).sendEmail(any()); <END> }</code><technical_language>Is worth adding ArgumentCaptor verify email passed sendMailService.sendEmail() contains token expect</technical_language>

Target:
public void requestEmailSignInTwiceReturnsSameToken() throws Exception { doReturn("something").when(cacheProvider).getString(CACHE_KEY); doReturn(account).when(accountDao).getAccount(any()); service.requestEmailSignIn(SIGN_IN_REQUEST_WITH_EMAIL); verify(cacheProvider, never()).setString(any(), any(), anyInt()); verify(sendMailService).sendEmail(providerCaptor.capture()); MimeTypeEmailProvider provider = providerCaptor.getValue(); assertEquals(RECIPIENT_EMAIL, provider.getMimeTypeEmail().getRecipientAddresses().get(0)); assertEquals(SUPPORT_EMAIL, provider.getPlainSenderEmail()); String bodyString = (String)provider.getMimeTypeEmail().getMessageParts().get(0).getContent(); assertEquals("something", bodyString); }
Source:
<code>public void saveEncounter_shouldUpdateExistingEncounterWhenAChildObsIsEdited() throws Exception { executeDataSet(ENC_OBS_HIERARCHY_DATA_XML); EncounterService es = Context.getEncounterService(); ObsService os = Context.getObsService(); Encounter enc = es.getEncounter(100); Obs o = os.getObs(101); o.setValueText("Obs value updated"); es.saveEncounter(enc); <START> Context.evictFromSession(enc); <END> Context.flushSession(); enc = es.getEncounter(100); Set<Obs> obsAtTopLevelUpdated = enc.getObsAtTopLevel(true); Obs oParent = os.getObs(100); final Obs editedObs = os.getObs(101); Obs o2 = os.getObs(102); Obs o3 = getNewVersionOfEditedObs(oParent,editedObs); assertEquals(1,obsAtTopLevelUpdated.size()); assertEquals(3, oParent.getGroupMembers(true).size()); assertTrue(editedObs.getVoided()); assertFalse(oParent.getVoided()); assertFalse(o2.getVoided()); assertNotNull(o3); assertFalse(o3.getVoided()); assertEquals("Obs value updated", o3.getValueText()); }</code><technical_language>evict, flush clear session</technical_language>

Target:
public void saveEncounter_shouldUpdateExistingEncounterWhenAChildObsIsEdited() throws Exception { executeDataSet(ENC_OBS_HIERARCHY_DATA_XML); EncounterService es = Context.getEncounterService(); ObsService os = Context.getObsService(); Encounter enc = es.getEncounter(100); Obs o = os.getObs(101); o.setValueText("Obs value updated"); es.saveEncounter(enc); Context.flushSession(); Context.clearSession(); enc = es.getEncounter(100); Set<Obs> obsAtTopLevelUpdated = enc.getObsAtTopLevel(true); Obs oParent = os.getObs(100); final Obs editedObs = os.getObs(101); Obs o2 = os.getObs(102); Obs o3 = getNewVersionOfEditedObs(oParent,editedObs); assertEquals(1,obsAtTopLevelUpdated.size()); assertEquals(3, oParent.getGroupMembers(true).size()); assertTrue(editedObs.getVoided()); assertFalse(oParent.getVoided()); assertFalse(o2.getVoided()); assertNotNull(o3); assertFalse(o3.getVoided()); assertEquals("Obs value updated", o3.getValueText()); }
Source:
<code>public void updateBodySetInvalidAttachments() throws Exception { MutableDocumentRevision update = saved.mutableCopy(); update.body = bodyTwo; String attachmentName = "doesnt_exist_attachment"; File f = TestUtils.loadFixture("fixture/"+ attachmentName); Attachment att = new UnsavedFileAttachment(f, "text/plain"); update.attachments.put(attachmentName, att); BasicDocumentRevision updated = null; try { updated = datastore.updateDocumentFromRevision(update); Assert.fail("Expected AttachmentException; not thrown"); <START> } catch (AttachmentException ioe) { <END> ; } Assert.assertNull("Updated DocumentRevision is not null", updated); BasicDocumentRevision retrieved = this.datastore.getDocument(saved.getId()); Assert.assertEquals("Document should not be updated", retrieved.getRevision(), saved.getRevision()); Assert.assertEquals("Revision should have 0 attachments", 0, retrieved.getAttachments().size()); }</code><technical_language>Rename variable</technical_language>

Target:
public void updateBodySetInvalidAttachments() throws Exception { MutableDocumentRevision update = saved.mutableCopy(); update.body = bodyTwo; String attachmentName = "doesnt_exist_attachment"; File f = TestUtils.loadFixture("fixture/"+ attachmentName); Attachment att = new UnsavedFileAttachment(f, "text/plain"); update.attachments.put(attachmentName, att); BasicDocumentRevision updated = null; try { updated = datastore.updateDocumentFromRevision(update); Assert.fail("Expected AttachmentException; not thrown"); } catch (AttachmentException e) { ; } Assert.assertNull("Updated DocumentRevision is not null", updated); BasicDocumentRevision retrieved = this.datastore.getDocument(saved.getId()); Assert.assertEquals("Document should not be updated", retrieved.getRevision(), saved.getRevision()); Assert.assertEquals("Revision should have 0 attachments", 0, retrieved.getAttachments().size()); }
Source:
<code>private void glusterPeerProbe(Guid upServerId, String newServerName) { VDSReturnValue returnValue = runVdsCommand( VDSCommandType.GlusterHostAdd, new GlusterHostAddVDSParameters(upServerId, newServerName)); <START> setSucceeded(returnValue.getSucceeded()); <END> if (!getSucceeded()) { getReturnValue().getFault().setError(returnValue.getVdsError().getCode()); getReturnValue().getFault().setMessage(returnValue.getVdsError().getMessage()); AuditLogDirector.log(new AuditLogableBase(upServerId), AuditLogType.GLUSTER_HOST_ADD_FAILED); return; } }</code><technical_language>please dont set commands succeeded here, is set true end of command</technical_language>

Target:
private void glusterPeerProbe(Guid upServerId, String newServerName) { VDSReturnValue returnValue = runVdsCommand( VDSCommandType.GlusterHostAdd, new GlusterHostAddVDSParameters(upServerId, newServerName)); if (!returnValue.getSucceeded()) { getReturnValue().getFault().setError(returnValue.getVdsError().getCode()); getReturnValue().getFault().setMessage(returnValue.getVdsError().getMessage()); AuditLogDirector.log(new AuditLogableBase(getVdsId()), AuditLogType.GLUSTER_HOST_ADD_FAILED); return; } }
Source:
<code>public GetFirmwareVersionAsyncResponse getFirmwareVersion( @OrganisationIdentification final String organisationIdentification, @RequestPayload final GetFirmwareVersionRequest request, @MessagePriority final String messagePriority, @ScheduleTime final String scheduleTime) throws OsgpException { LOGGER.info("GetFirmwareVersion Request received from organisation for device {}.", organisationIdentification, request.getDeviceIdentification()); final GetFirmwareVersionAsyncResponse response = new com.alliander.osgp.adapter.ws.schema.smartmetering.configuration.ObjectFactory() .createGetFirmwareVersionAsyncResponse(); try { final String correlationUid = this.configurationService.enqueueGetFirmwareRequest( organisationIdentification, request.getDeviceIdentification(), MessagePriorityEnum.getMessagePriority(messagePriority), this.configurationMapper.map(scheduleTime, Long.class)); response.setCorrelationUid(correlationUid); response.setDeviceIdentification(request.getDeviceIdentification()); <START> } catch (final MethodConstraintViolationException e) { <END> LOGGER.error("exception", e); throw new FunctionalException(FunctionalExceptionType.VALIDATION_ERROR, ComponentType.WS_CORE, new ValidationException(e.getConstraintViolations())); } catch (final Exception e) { this.handleException(e); } return response; }</code><technical_language>Do introduce a deprecated class code</technical_language>

Target:
public GetFirmwareVersionAsyncResponse getFirmwareVersion( @OrganisationIdentification final String organisationIdentification, @RequestPayload final GetFirmwareVersionRequest request, @MessagePriority final String messagePriority, @ScheduleTime final String scheduleTime) throws OsgpException { LOGGER.info("GetFirmwareVersion Request received from organisation for device {}.", organisationIdentification, request.getDeviceIdentification()); final GetFirmwareVersionAsyncResponse response = new com.alliander.osgp.adapter.ws.schema.smartmetering.configuration.ObjectFactory() .createGetFirmwareVersionAsyncResponse(); try { final String correlationUid = this.configurationService.enqueueGetFirmwareRequest( organisationIdentification, request.getDeviceIdentification(), MessagePriorityEnum.getMessagePriority(messagePriority), this.configurationMapper.map(scheduleTime, Long.class)); response.setCorrelationUid(correlationUid); response.setDeviceIdentification(request.getDeviceIdentification()); } catch (final Exception e) { this.handleException(e); } return response; }
Source:
<code>public void sendSmallEventsFullBatchPartitionKey() { final EventDataBatch batch = new EventDataBatch(ClientConstants.MAX_MESSAGE_LENGTH_BYTES, null, PARTITION_KEY, contextProvider, <START> new TracerProvider(Collections.emptyList()), null, null); <END> int count = 0; while (batch.tryAdd(createData())) { if (count % 100 == 0) { logger.verbose("Batch size: {}", batch.getCount()); } count++; } StepVerifier.create(producer.send(batch.getEvents())) .verifyComplete(); }</code><technical_language>Instead of null, null.. getFullyQualifiedDomainName() getEventHubName() ? properties set in IntegrationTestBase</technical_language>

Target:
public void sendSmallEventsFullBatchPartitionKey() { final EventDataBatch batch = new EventDataBatch(ClientConstants.MAX_MESSAGE_LENGTH_BYTES, null, PARTITION_KEY, contextProvider, new TracerProvider(Collections.emptyList()), getFullyQualifiedDomainName(), getEventHubName()); int count = 0; while (batch.tryAdd(createData())) { if (count % 100 == 0) { logger.verbose("Batch size: {}", batch.getCount()); } count++; } StepVerifier.create(producer.send(batch.getEvents())) .verifyComplete(); }
Source:
<code><START> public void shouldPublishUsingOkHttpClientUsingSSL() { <END> SSLContextSupplier sslSupplier = getSslContextSupplier(); HermesClient client = hermesClient(new OkHttpSender(sslSupplier.get())).withURI(topicURI_SSL).build(); runTestSuiteForHermesClient(client); }</code><technical_language>http2, ssl? i keeping 2 separate tests check ssl http2 (or naming is bad)</technical_language>

Target:
public void shouldPublishUsingOkHttpClientUsingSSL() { HermesClient client = hermesClient(new OkHttpHermesSender(getOkHttpClientWithSslContextConfigured())).withURI(sslTopicUri).build(); runTestSuiteForHermesClient(client); }
Source:
<code>private Map<Class<?>, Integer> getGlobalAlternativeMap() { if (cachedAlternativeMap == null || dirty) { Map<Class<?>, Integer> map = new HashMap<Class<?>, Integer>(); <START> for (ListIterator<Item> iterator = alternatives.listIterator(); iterator.hasNext(); ) { <END> Item item = iterator.next(); map.put(item.getJavaClass(), item.getPriority()); } cachedAlternativeMap = ImmutableMap.copyOf(map); } return cachedAlternativeMap; }</code><technical_language>I is need ListIterator anymore..</technical_language>

Target:
private Map<Class<?>, Integer> getGlobalAlternativeMap() { if (cachedAlternativeMap == null || dirty) { Map<Class<?>, Integer> map = new HashMap<Class<?>, Integer>(); for (Item item : alternatives) { map.put(item.getJavaClass(), item.getPriority()); } cachedAlternativeMap = ImmutableMap.copyOf(map); } return cachedAlternativeMap; }
Source:
<code>public void put(ResourceRecordSet<?> rrset) { checkNotNull(rrset, "rrset was null"); checkArgument(!rrset.records().isEmpty(), "rrset was empty %s", rrset); List<Map<String, Object>> recordsLeftToCreate = new ArrayList<Map<String, Object>>(rrset.records()); for (Record record : api.recordsByNameAndType(domainId, rrset.name(), rrset.type())) { Map<String, Object> rdata = toRDataMap(record); if (recordsLeftToCreate.contains(rdata)) { recordsLeftToCreate.remove(rdata); if (rrset.ttl() != null) { <START> if (rrset.ttl().equals(record.ttl)) { <END> continue; } awaitComplete(api.updateRecord(domainId, record.id, rrset.ttl(), record.getData())); } } else { awaitComplete(api.deleteRecord(domainId, record.id)); } } int ttlToApply = rrset.ttl() != null ? rrset.ttl() : DEFAULT_TTL; for (Map<String, Object> rdata : recordsLeftToCreate) { Map<String, Object> mutableRData = new LinkedHashMap<String, Object>(rdata); Integer priority = getPriority(mutableRData); String data = join(' ', mutableRData.values().toArray()); if (priority == null) { awaitComplete(api.createRecord(domainId, rrset.name(), rrset.type(), ttlToApply, data)); } else { awaitComplete(api.createRecordWithPriority( domainId, rrset.name(), rrset.type(), ttlToApply, data, priority)); } } }</code><technical_language>safer Util.equal()</technical_language>

Target:
public void put(ResourceRecordSet<?> rrset) { checkNotNull(rrset, "rrset was null"); checkArgument(!rrset.records().isEmpty(), "rrset was empty %s", rrset); List<Map<String, Object>> recordsLeftToCreate = new ArrayList<Map<String, Object>>(rrset.records()); for (Record record : api.recordsByNameAndType(domainId, rrset.name(), rrset.type())) { Map<String, Object> rdata = toRDataMap(record); if (recordsLeftToCreate.contains(rdata)) { recordsLeftToCreate.remove(rdata); if (rrset.ttl() != null) { if (Util.equal(rrset.ttl(), record.ttl)) { continue; } awaitComplete(api.updateRecord(domainId, record.id, rrset.ttl(), record.data())); } } else { awaitComplete(api.deleteRecord(domainId, record.id)); } } int ttlToApply = rrset.ttl() != null ? rrset.ttl() : DEFAULT_TTL; for (Map<String, Object> rdata : recordsLeftToCreate) { Map<String, Object> mutableRData = new LinkedHashMap<String, Object>(rdata); Integer priority = getPriority(mutableRData); String data = join(' ', mutableRData.values().toArray()); if (priority == null) { awaitComplete(api.createRecord(domainId, rrset.name(), rrset.type(), ttlToApply, data)); } else { awaitComplete(api.createRecordWithPriority( domainId, rrset.name(), rrset.type(), ttlToApply, data, priority)); } } }
Source:
<code>public MapValue<Statistic, Long> statistics() { <START> return new SpongeMapValue<Statistic, Long>(Keys.STATISTICS, Maps.<Statistic, Long>newLinkedHashMap(), getValue()); <END> }</code><technical_language>Casting necessary</technical_language>

Target:
public MapValue<Statistic, Long> statistics() { return new SpongeMapValue<>(Keys.STATISTICS, Maps.newLinkedHashMap(), getValue()); }
Source:
<code>protected abstract UUID sendRequest(ManagementClient client) throws TimeoutException; protected Optional<ManagementClient> getOrchestrator() { runtime.invalidateLayout(); Layout layout = new Layout(runtime.getLayoutView().getLayout()); List<String> availableLayoutServers = layout.getLayoutServers().stream() .filter(s -> !s.equals(nodeForWorkflow)) .collect(Collectors.toList()); if (availableLayoutServers.isEmpty()) { throw new WorkflowException("getOrchestrator: no available orchestrators " + layout); } Optional<ManagementClient> managementClient = Optional.empty(); <START> for (String endpoint : availableLayoutServers) { <END> BaseClient client = runtime.getLayoutView().getRuntimeLayout(layout) .getBaseClient(endpoint); if (client.pingSync()) { log.info("getOrchestrator: orchestrator selected {}, layout {}", endpoint, layout); managementClient = Optional.of(runtime.getLayoutView().getRuntimeLayout(layout) .getManagementClient(endpoint)); } } return managementClient; }</code><technical_language>want change logic select target node orchestrator? of availableLayoutServers</technical_language>

Target:
protected abstract UUID sendRequest(ManagementClient client) throws TimeoutException; protected Optional<ManagementClient> getOrchestrator() { runtime.invalidateLayout(); Layout layout = new Layout(runtime.getLayoutView().getLayout()); List<String> availableLayoutServers = layout.getLayoutServers().stream() .filter(s -> !s.equals(nodeForWorkflow)) .collect(Collectors.toList()); if (availableLayoutServers.isEmpty()) { throw new WorkflowException("getOrchestrator: no available orchestrators " + layout); } Optional<ManagementClient> managementClient = Optional.empty(); for (String endpoint : availableLayoutServers) { BaseClient client = runtime.getLayoutView().getRuntimeLayout(layout) .getBaseClient(endpoint); if (client.pingSync()) { log.info("getOrchestrator: orchestrator selected {}, layout {}", endpoint, layout); managementClient = Optional.of(runtime.getLayoutView().getRuntimeLayout(layout) .getManagementClient(endpoint)); break; } } return managementClient; }
Source:
<code>public static Client getClient(ClientConfig config, String[] servers, int port) throws Exception { config.setTopologyChangeAware(true); final Client client = ClientFactory.createClient(config); for (String server : servers) { try { client.createConnection(server.trim(), port); } catch (IOException e) { } } if (client.getConnectedHostList().isEmpty()) { <START> throw new Exception("Unable to connect to any servers"); <END> } return client; }</code><technical_language>Close client throw</technical_language>

Target:
public static Client getClient(ClientConfig config, String[] servers, int port) throws Exception { config.setTopologyChangeAware(true); final Client client = ClientFactory.createClient(config); for (String server : servers) { try { client.createConnection(server.trim(), port); } catch (IOException e) { } } if (client.getConnectedHostList().isEmpty()) { try { client.close(); } catch (Exception ignore) throw new Exception("Unable to connect to any servers"); } return client; }
Source:
<code>public int getLatestPacketFailRate() { int failure = 0; int sent = 0; int received = 0; int size = mTcpStats.size(); for (int i = 0; i < size; i++) { final long key = mTcpStats.keyAt(i); failure += (mTcpStats.get(key).lostCount + mTcpStats.get(key).retransmitCount); sent += mTcpStats.get(key).sentCount; received += mTcpStats.get(key).receivedCount; } <START> updateSentSinceLastRecv(sent, <END> received); if (getSentSinceLastRecv() < getMinPacketsThreshold()) return 0; final int rate = ((sent != 0) ? (failure * 100 / sent) : 0); log("getLatestPacketFailRate:" + rate); return rate; }</code><technical_language>getLatestPacketFailRate is named a getter this essential side effects called multiple times. If called multiple times counts wrong, this is especially bad this is called isDataStallSuspected is a public method called outside. In OOP terms, issue is caller this implementation detail, if multiple callers synchronize externally. I right fix this is completely remove mTcpStats array do updating end of pollSocketsInfo. This getter side effects</technical_language>

Target:
public int getLatestPacketFailRate() { if (!mDependencies.isTcpInfoParsingSupported()) return 0; if (getSentSinceLastRecv() < getMinPacketsThreshold()) return 0; return mLatestPacketFailRate; }
Source:
<code><START> public SQLExecEnvironment withModel(String model) <END> { if (model == null) { return this; } Connection connection = null; try { Properties p = new Properties(); p.put("model", "inline:" + model); connection = DriverManager.getConnection("jdbc:calcite:", p); CalciteConnection conn = connection.unwrap(CalciteConnection.class); this.schema = conn.getRootSchema().getSubSchema(connection.getSchema()); } catch (SQLException e) { throw new RuntimeException(e); } finally { try { connection.close(); } catch (Exception e) { e.printStackTrace(); } } return this; }</code><technical_language>withModel(File modelFile) well</technical_language>

Target:
public SQLExecEnvironment withModel(String model) { if (model == null) { return this; } Properties p = new Properties(); p.put("model", "inline:" + model); try (Connection connection = DriverManager.getConnection("jdbc:calcite:", p)) { CalciteConnection conn = connection.unwrap(CalciteConnection.class); this.schema = conn.getRootSchema().getSubSchema(connection.getSchema()); } catch (SQLException e) { throw new RuntimeException(e); } return this; }
Source:
<code>public TypedSet(Type elementType, BlockBuilder blockBuilder, int expectedSize, String functionName) { checkArgument(expectedSize >= 0, "expectedSize must not be negative"); this.elementType = requireNonNull(elementType, "elementType must not be null"); this.elementBlock = requireNonNull(blockBuilder, "blockBuilder must not be null"); this.functionName = functionName; initialElementBlockOffset = elementBlock.getPositionCount(); initialElementBlockSizeInBytes = elementBlock.getSizeInBytes(); <START> <END> hashCapacity = arraySize(expectedSize, FILL_RATIO); this.maxFill = calculateMaxFill(hashCapacity); this.hashMask = hashCapacity - 1; blockPositionByHash = new IntArrayList(hashCapacity); blockPositionByHash.size(hashCapacity); for (int i = 0; i < hashCapacity; i++) { blockPositionByHash.set(i, EMPTY_SLOT); } this.containsNullElement = false; }</code><technical_language>I prefer add size = 0 initialization in constructor, required Java</technical_language>

Target:
public TypedSet(Type elementType, BlockBuilder blockBuilder, int expectedSize, String functionName) { checkArgument(expectedSize >= 0, "expectedSize must not be negative"); this.elementType = requireNonNull(elementType, "elementType must not be null"); this.elementBlock = requireNonNull(blockBuilder, "blockBuilder must not be null"); this.functionName = functionName; initialElementBlockOffset = elementBlock.getPositionCount(); initialElementBlockSizeInBytes = elementBlock.getSizeInBytes(); this.size = 0; this.hashCapacity = arraySize(expectedSize, FILL_RATIO); this.maxFill = calculateMaxFill(hashCapacity); this.hashMask = hashCapacity - 1; blockPositionByHash = new IntArrayList(hashCapacity); blockPositionByHash.size(hashCapacity); for (int i = 0; i < hashCapacity; i++) { blockPositionByHash.set(i, EMPTY_SLOT); } this.containsNullElement = false; }
Source:
<code>protected String getPagePhrase(SyntaxContainer syntax, String pageNumber) { String result = ""; <START> if (syntax.getMaxCount() < Integer.MAX_VALUE) { <END> Integer page = IntegerCompat.tryParse(pageNumber); if (page == null) { page = 1; } PagingType pagingType = getPagingType(); if (pagingType != null) { String pagingSyntax = Config.<String> getValue(ConfigValues.DBPagingSyntax); switch (pagingType) { case Range: result = StringFormat.format(pagingSyntax, (page - 1) * syntax.getMaxCount() + 1, page * syntax.getMaxCount()); break; case Offset: result = StringFormat.format(pagingSyntax, (page - 1) * syntax.getMaxCount() + 1, syntax.getMaxCount()); break; } } } return result; }</code><technical_language>I thought -1 means "get values", is in RESTAPI. changed</technical_language>

Target:
protected String getPagePhrase(SyntaxContainer syntax, String pageNumber) { String result = ""; Integer page = IntegerCompat.tryParse(pageNumber); if (page == null) { page = 1; } PagingType pagingType = getPagingType(); if (pagingType != null) { String pagingSyntax = Config.<String> getValue(ConfigValues.DBPagingSyntax); switch (pagingType) { case Range: result = StringFormat.format(pagingSyntax, BigInteger.valueOf((page - 1) * syntax.getMaxCount() + 1), BigInteger.valueOf(page * syntax.getMaxCount())); break; case Offset: result = StringFormat.format(pagingSyntax, BigInteger.valueOf((page - 1) * syntax.getMaxCount() + 1), syntax.getMaxCount()); break; } } return result; }
Source:
<code>private void reserveSeat(Seat seat, Long ticketId) { if (ticketId != null) { seatRepository.findByTicketId(ticketId).ifPresent(previousSeat -> previousSeat.setTicket(null)); <START> Ticket ticket = ticketRepository.findOne(ticketId); <END> if (!ticket.isValid()) { throw new InvalidTicketException("Unable to reserve seat for an invalid Ticket"); } if (seat.getTicket() != null && seat.getTicket().getOwner() != null) { mailService.sendSeatOverrideMail(seat.getTicket().getOwner()); } seat.setTicket(ticket); } else { seat.setTicket(null); } seat.setTaken(true); seatRepository.saveAndFlush(seat); }</code><technical_language>getTicketById() for proper exception handling</technical_language>

Target:
private void reserveSeat(Seat seat, Long ticketId) { if (ticketId != null) { seatRepository.findByTicketId(ticketId).ifPresent(previousSeat -> previousSeat.setTicket(null)); Ticket ticket = ticketService.getTicketById(ticketId); if (!ticket.isValid()) { throw new InvalidTicketException("Unable to reserve seat for an invalid Ticket"); } if (seat.getTicket() != null && seat.getTicket().getOwner() != null) { mailService.sendSeatOverrideMail(seat.getTicket().getOwner()); } seat.setTicket(ticket); } else { seat.setTicket(null); } seat.setTaken(true); seatRepository.saveAndFlush(seat); }
Source:
<code>public ConfigurationBuilder() { this.classLoader = new WeakReference<>(Thread.currentThread().getContextClassLoader()); this.connectionPool = new ConnectionPoolConfigurationBuilder(this); this.asyncExecutorFactory = new ExecutorFactoryConfigurationBuilder(this); this.security = new SecurityConfigurationBuilder(this); this.nearCache = new NearCacheConfigurationBuilder(this); <START> transaction = new TransactionConfigurationBuilder(this); <END> }</code><technical_language>for symmetry qualify field this. remove others :smile:</technical_language>

Target:
public ConfigurationBuilder() { this.classLoader = new WeakReference<>(Thread.currentThread().getContextClassLoader()); this.connectionPool = new ConnectionPoolConfigurationBuilder(this); this.asyncExecutorFactory = new ExecutorFactoryConfigurationBuilder(this); this.security = new SecurityConfigurationBuilder(this); this.nearCache = new NearCacheConfigurationBuilder(this); this.transaction = new TransactionConfigurationBuilder(this); }
Source:
<code>public ExprEval apply(List<Expr> args, Expr.ObjectBinding bindings) { if (args.size() != 3) { throw new IAE("Function[%s] needs 3 arguments", name()); } String base = NullHandling.nullToEmptyIfNeeded(args.get(0).eval(bindings).asString()); int len = args.get(1).eval(bindings).asInt(); <START> String pad = NullHandling.nullToEmptyIfNeeded(args.get(2).eval(bindings).asString()); <END> if (base == null || pad == null) { return ExprEval.of(null); } else { return ExprEval.of(len == 0 ? NullHandling.defaultStringValue() : StringUtils.lpad(base, len, pad)); } }</code><technical_language>this sense for pad? error if null</technical_language>

Target:
public ExprEval apply(List<Expr> args, Expr.ObjectBinding bindings) { if (args.size() != 3) { throw new IAE("Function[%s] needs 3 arguments", name()); } String base = args.get(0).eval(bindings).asString(); int len = args.get(1).eval(bindings).asInt(); String pad = args.get(2).eval(bindings).asString(); if (base == null || pad == null) { return ExprEval.of(null); } else { return ExprEval.of(len == 0 ? NullHandling.defaultStringValue() : StringUtils.lpad(base, len, pad)); } }
Source:
<code>private void open() { try { pin.open(); } catch (KuraGPIODeviceException | KuraUnavailableDeviceException | IOException e) { <START> logger.error("Exception GPIOService ", e); <END> } }</code><technical_language>is spelled "GPIOService Exception". Then, please a constant in order text 3 times code</technical_language>

Target:
private void open() { try { pin.open(); } catch (KuraGPIODeviceException | KuraUnavailableDeviceException | IOException e) { logger.error("Open Exception ", e); } }
Source:
<code>public CacheResource parse(ConfigResource parent, IdString id) throws AuthException, ResourceNotFoundException { final CurrentUser user = self.get(); if (user instanceof AnonymousUser) { throw new AuthException("Authentication required"); } else if(!(user.isIdentifiedUser())) { throw new ResourceNotFoundException(); } if (!user.getCapabilities().canViewCaches()) { throw new AuthException("not allowed to view caches"); } String cacheName = id.get(); String pluginName = "gerrit"; int i = <START> cacheName.indexOf('.'); <END> if (i != -1) { pluginName = cacheName.substring(0, i); cacheName = cacheName.length() > i + 1 ? cacheName.substring(i + 1) : ""; } Provider<Cache<?, ?>> cacheProvider = cacheMap.byPlugin(pluginName).get(cacheName); if (cacheProvider == null) { throw new ResourceNotFoundException(id); } return new CacheResource(pluginName, cacheName, cacheProvider); }</code><technical_language>if previous change changed output of plugin owned caches "plugin-cache", this reflected in this parse method well? do expect output list caches REST endpoint is "plugin-cache" input for flush REST endpoint is "plugin.cache"</technical_language>

Target:
public CacheResource parse(ConfigResource parent, IdString id) throws AuthException, ResourceNotFoundException { final CurrentUser user = self.get(); if (user instanceof AnonymousUser) { throw new AuthException("Authentication required"); } else if(!(user.isIdentifiedUser())) { throw new ResourceNotFoundException(); } if (!user.getCapabilities().canViewCaches()) { throw new AuthException("not allowed to view caches"); } String cacheName = id.get(); String pluginName = "gerrit"; int i = cacheName.indexOf('-'); if (i != -1) { pluginName = cacheName.substring(0, i); cacheName = cacheName.length() > i + 1 ? cacheName.substring(i + 1) : ""; } Provider<Cache<?, ?>> cacheProvider = cacheMap.byPlugin(pluginName).get(cacheName); if (cacheProvider == null) { throw new ResourceNotFoundException(id); } return new CacheResource(pluginName, cacheName, cacheProvider); }
Source:
<code>protected void activate(ComponentContext ctxt) { TOTPManagerImpl totpService = new TOTPManagerImpl(); Hashtable<String, String> props = new Hashtable<String, String>(); ctxt.getBundleContext().registerService(TOTPManager.class.getName(), totpService, props); if (log.isDebugEnabled()) { <START> log.info("TOTPServiceComponent bundle is activated"); <END> } }</code><technical_language>log.debug</technical_language>

Target:
protected void activate(ComponentContext ctxt) { TOTPManagerImpl totpService = new TOTPManagerImpl(); Hashtable<String, String> props = new Hashtable<String, String>(); ctxt.getBundleContext().registerService(TOTPManager.class.getName(), totpService, props); if (log.isDebugEnabled()) { log.debug("TOTPServiceComponent bundle is activated"); } }
Source:
<code>public Opt<Iterator<Identity>> enter(final Request req) throws IOException { final Iterator<String> flg = new RqHref.Base(req).href() .param(this.flag).iterator(); final Collection<Identity> users = new ArrayList<Identity>(1); if (flg.hasNext()) { final String value = flg.next(); for (final Map.Entry<Pattern, Pass> ent : this.passes.entrySet()) { if (ent.getKey().matcher(value).matches()) { final Opt<Iterator<Identity>> tmpIdentity = ent.getValue() .enter(req); <START> users.add(tmpIdentity.get().next()); <END> } } } return new Opt.Single<Iterator<Identity>>(users.iterator()); }</code><technical_language>@antonini I return soon user is (there one, line 105)</technical_language>

Target:
public Opt<Identity> enter(final Request req) throws IOException { final Iterator<String> flg = new RqHref.Base(req).href() .param(this.flag).iterator(); Opt<Identity> user = new Opt.Empty<Identity>(); if (flg.hasNext()) { final String value = flg.next(); for (final Map.Entry<Pattern, Pass> ent : this.passes.entrySet()) { if (ent.getKey().matcher(value).matches()) { user = ent.getValue().enter(req); break; } } } return user; }