auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public String describeFlow(Flow flow) { String result; try { FlowConfiguration configuration = flow.getFlowConfiguration(); <START> flow.getName(); <END> FlowMetaDataImpl flowMetaData = new FlowMetaDataImpl(); flowMetaData.setName(flow.getName()); flowMetaData.setConsumer(describeFlowElement(flowMetaData, configuration.getConsumerFlowElement())); if(flow instanceof ConfiguredResource) { flowMetaData.setConfigurationId(((ConfiguredResource) flow).getConfiguredResourceId()); } ObjectMapper mapper = new ObjectMapper(); result = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(flowMetaData); } catch (Exception e) { throw new RuntimeException("Exception has occurred creating flow meta data json!", e); } return result; }</code><technical_language>need call flow.getName() assigning a value</technical_language>

Target:
public String describeFlow(Flow flow) { String result; try { FlowConfiguration configuration = flow.getFlowConfiguration(); FlowMetaDataImpl flowMetaData = new FlowMetaDataImpl(); flowMetaData.setName(flow.getName()); flowMetaData.setConsumer(describeFlowElement(flowMetaData, configuration.getConsumerFlowElement())); if(flow instanceof ConfiguredResource) { flowMetaData.setConfigurationId(((ConfiguredResource) flow).getConfiguredResourceId()); } result = this.mapper.writerWithDefaultPrettyPrinter().writeValueAsString(flowMetaData); } catch (Exception e) { throw new RuntimeException("Exception has occurred creating flow meta data json!", e); } return result; }
Source:
<code>public Aggregation getAggregations() { if (jsonObject != null) { JsonObject aggregationsMap; if (jsonObject.has("aggregations")) { aggregationsMap = (JsonObject) jsonObject.get("aggregations"); } else if (jsonObject.has("aggs")) { aggregationsMap = (JsonObject) jsonObject.get("aggs"); } else { return new Aggregation("aggs", new JsonObject()); } return new Aggregation("aggs", aggregationsMap); } return new Aggregation("aggs", new JsonObject()); <START> } <END></code><technical_language>multiple exit points, refactoring (something like) more easy read: if (jsonObject != null) { if (jsonObject.has("aggregations")) { return new Aggregation(jsonObject.getAsJsonObject("aggregations")); } else if (jsonObject.has("aggs")) { return new Aggregation(jsonObject.getAsJsonObject("aggs")); } } return new Aggregation(new JsonObject()); Other points: - getAsJsonObject instead of casting - "aggs" passed Aggregation a magic function, suggest creating a single argument constructor for Aggregation name is determined in single point</technical_language>

Target:
public Aggregation getAggregations() { final String rootAggrgationName = "aggs"; if (jsonObject == null) return new Aggregation(rootAggrgationName, new JsonObject()); if (jsonObject.has("aggregations")) return new Aggregation(rootAggrgationName, jsonObject.getAsJsonObject("aggregations")); if (jsonObject.has("aggs")) return new Aggregation(rootAggrgationName, jsonObject.getAsJsonObject("aggs")); return new Aggregation(rootAggrgationName, new JsonObject()); }
Source:
<code>private Socket enableTLSOnSocket(final Socket socket) { <START> if ((socket instanceof SSLSocket)) { <END> ((SSLSocket) socket).setEnabledProtocols(new String[]{"TLSv1.1", "TLSv1.2"}); } return socket; }</code><technical_language>need for double (( ))</technical_language>

Target:
private Socket enableTLSOnSocket(final Socket socket) { if (socket instanceof SSLSocket) { ((SSLSocket) socket).setEnabledProtocols(new String[]{"TLSv1.1", "TLSv1.2"}); } return socket; }
Source:
<code>Decorator(String container, EnvVars envHost, String ws, String toolName, VersionNumber dockerVersion) { this.container = container; this.envHost = Util.mapToEnv(envHost); this.ws = ws; this.toolName = toolName; <START> this.hasEnv = dockerVersion.isOlderThan(new VersionNumber("1.13.0")); <END> this.hasWorkdir = !dockerVersion.isOlderThan(new VersionNumber("17.12")); }</code><technical_language>Wait, --env 1.12.x, this removed of 1.13.0? forget a !? BTW I find !a.isOlderThan(b) a bit confusing. a.compareTo(b) >= 0 clearer</technical_language>

Target:
Decorator(String container, EnvVars envHost, String ws, String toolName, VersionNumber dockerVersion) { this.container = container; this.envHost = Util.mapToEnv(envHost); this.ws = ws; this.toolName = toolName; this.hasEnv = dockerVersion != null && dockerVersion.compareTo(new VersionNumber("1.13.0")) >= 0; this.hasWorkdir = dockerVersion != null && dockerVersion.compareTo(new VersionNumber("17.12")) >= 0; }
Source:
<code>protected boolean pageValid() { setErrorMessage(null); if (!isNameValid(nametext.getText().trim())) { return false; } if (resolvingError) { <START> setErrorMessage(WizardMessages.TargetBasedApiBaselineWizardPage_SomeTargetsCouldNotBeResolved); <END> } if(targetsViewer.getCheckedElements().length != 1) { setErrorMessage(WizardMessages.ApiProfileWizardPage_select_target); reloadbutton.setEnabled(false); return false; } if (fProfile != null) { if (fProfile.getApiComponents().length == 0) { setErrorMessage(WizardMessages.ApiProfileWizardPage_2); return false; } IStatus status = fProfile.getExecutionEnvironmentStatus(); if (status.getSeverity() == IStatus.ERROR) { setErrorMessage(status.getMessage()); return false; } ITargetDefinition selected = getSelectedTargetDefinition(); if (selected != null && !ApiModelFactory.isUpToDateWithTarget(fProfile, selected)) { setErrorMessage(WizardMessages.ApiProfileWizardPage_location_needs_reset); return false; } } else { setErrorMessage(WizardMessages.ApiProfileWizardPage_location_needs_reset); return false; } return true; }</code><technical_language>Agreed. I logging error(s) is enough</technical_language>

Target:
protected boolean pageValid() { setErrorMessage(null); if (!isNameValid(nametext.getText().trim())) { return false; } if(targetsViewer.getCheckedElements().length != 1) { setErrorMessage(WizardMessages.ApiProfileWizardPage_select_target); reloadbutton.setEnabled(false); return false; } if (fProfile != null) { if (fProfile.getApiComponents().length == 0) { setErrorMessage(WizardMessages.ApiProfileWizardPage_2); return false; } IStatus status = fProfile.getExecutionEnvironmentStatus(); if (status.getSeverity() == IStatus.ERROR) { setErrorMessage(status.getMessage()); return false; } ITargetDefinition selected = getSelectedTargetDefinition(); if (selected != null && !ApiModelFactory.isUpToDateWithTarget(fProfile, selected)) { setErrorMessage(WizardMessages.ApiProfileWizardPage_location_needs_reset); return false; } } else { setErrorMessage(WizardMessages.ApiProfileWizardPage_location_needs_reset); return false; } return true; }
Source:
<code>private void loadConstants(ServletContext servletContext) { WebConstants.BUILD_TIMESTAMP = servletContext.getInitParameter("build.timestamp"); <START> WebConstants.WEBAPP_NAME = getContextPath(servletContext); <END> WebConstants.MODULE_REPOSITORY_URL = servletContext.getInitParameter("module.repository.url"); }</code><technical_language>please dont remove this</technical_language>

Target:
private void loadConstants(ServletContext servletContext) { WebConstants.BUILD_TIMESTAMP = servletContext.getInitParameter("build.timestamp"); WebConstants.WEBAPP_NAME = getContextPath(servletContext); WebConstants.MODULE_REPOSITORY_URL = servletContext.getInitParameter("module.repository.url"); if (!"openmrs".equalsIgnoreCase(WebConstants.WEBAPP_NAME)) { OpenmrsConstants.KEY_OPENMRS_APPLICATION_DATA_DIRECTORY = WebConstants.WEBAPP_NAME + "_APPLICATION_DATA_DIRECTORY"; } }
Source:
<code>public boolean supports(Class c) { <START> return CohortMembership.class.isAssignableFrom(c); <END> }</code><technical_language>This cohort class</technical_language>

Target:
public boolean supports(Class c) { return Cohort.class.isAssignableFrom(c); }
Source:
<code>public Optional<String> namespace() { <START> return Optional.of("H2 namespace"); <END> }</code><technical_language>spaces OK in namespace strings</technical_language>

Target:
public Optional<String> namespace() { return Optional.empty(); }
Source:
<code>private void getOrCreateFirewalls(GoogleComputeEngineTemplateOptions templateOptions, Network network, FirewallTagNamingConvention naming) { String projectName = userProject.get(); Set<AtomicReference<Operation>> operations = Sets.newHashSet(); for (Integer port : templateOptions.getInboundPorts()) { String name = naming.name(port); ImmutableSet<Firewall.Rule> rules = ImmutableSet.of(Firewall.Rule.permitTcpRule(port), Firewall.Rule.permitUdpRule(port)); <START> FirewallOptions firewallOptions = new FirewallOptions() <END> .name(name) .network(network.getSelfLink()) .allowedRules(rules) .sourceTags(templateOptions.getTags()) .sourceRanges(of(DEFAULT_INTERNAL_NETWORK_RANGE, EXTERIOR_RANGE)) .targetTags(ImmutableSet.of(name)); Firewall firewall = api.getFirewallApiForProject(projectName).get(firewallOptions.getName()); if (firewall == null) { AtomicReference<Operation> operation = new AtomicReference<Operation>(api.getFirewallApiForProject(projectName).createInNetwork( firewallOptions.getName(), network.getSelfLink(), firewallOptions)); operations.add(operation); } } for (AtomicReference<Operation> operation : operations) { retry(operationDonePredicate, operationCompleteCheckTimeout, operationCompleteCheckInterval, MILLISECONDS).apply(operation); checkState(!operation.get().getHttpError().isPresent(),"Could not create firewall, operation failed" + operation); } }</code><technical_language>Wait if (firewall == null) bit building options</technical_language>

Target:
private void getOrCreateFirewalls(GoogleComputeEngineTemplateOptions templateOptions, Network network, FirewallTagNamingConvention naming) { String projectName = userProject.get(); FirewallApi firewallApi = api.getFirewallApiForProject(projectName); Set<AtomicReference<Operation>> operations = Sets.newHashSet(); for (Integer port : templateOptions.getInboundPorts()) { String name = naming.name(port); Firewall firewall = firewallApi.get(name); if (firewall == null) { ImmutableSet<Firewall.Rule> rules = ImmutableSet.of(Firewall.Rule.permitTcpRule(port), Firewall.Rule.permitUdpRule(port)); FirewallOptions firewallOptions = new FirewallOptions() .name(name) .network(network.getSelfLink()) .allowedRules(rules) .sourceTags(templateOptions.getTags()) .sourceRanges(of(DEFAULT_INTERNAL_NETWORK_RANGE, EXTERIOR_RANGE)) .targetTags(ImmutableSet.of(name)); AtomicReference<Operation> operation = new AtomicReference<Operation>(firewallApi.createInNetwork( firewallOptions.getName(), network.getSelfLink(), firewallOptions)); operations.add(operation); } } for (AtomicReference<Operation> operation : operations) { retry(operationDonePredicate, operationCompleteCheckTimeout, operationCompleteCheckInterval, MILLISECONDS).apply(operation); checkState(!operation.get().getHttpError().isPresent(),"Could not create firewall, operation failed" + operation); } }
Source:
<code>public void reconnect(int clientID, String clientName) throws RemoteException { <START> amountOfPingsReceived++; <END> try { if (!connectedPlayers.containsKey(clientID)) { connectedPlayers.put(clientID, (ClientInterface) Naming.lookup(clientName)); } } catch (NotBoundException e) { e.printStackTrace(); } catch (MalformedURLException e) { e.printStackTrace(); } }</code><technical_language>for connect holds</technical_language>

Target:
public void reconnect(int clientID, String clientName) throws RemoteException { clientAmountOfMessagesReceived++; try { if (!connectedPlayers.containsKey(clientID)) { connectedPlayers.put(clientID, (ClientInterface) Naming.lookup(clientName)); } } catch (NotBoundException e) { e.printStackTrace(); } catch (MalformedURLException e) { e.printStackTrace(); } }
Source:
<code>private boolean validateStorage() { List<DiskImage> vmDisksList = <START> getSnappableVmDisks(); <END> vmDisksList = ImagesHandler.getDisksDummiesForStorageAllocations(vmDisksList); List<DiskImage> allDisks = new ArrayList<>(vmDisksList); List<DiskImage> memoryDisksList = null; if (getParameters().isSaveMemory()) { memoryDisksList = MemoryUtils.createDiskDummies(getVm().getTotalMemorySizeInBytes(), MemoryUtils.METADATA_SIZE_IN_BYTES); if (Guid.Empty.equals(getStorageDomainIdForVmMemory(memoryDisksList))) { return failCanDoAction(EngineMessage.ACTION_TYPE_FAILED_NO_SUITABLE_DOMAIN_FOUND); } allDisks.addAll(memoryDisksList); } MultipleStorageDomainsValidator sdValidator = createMultipleStorageDomainsValidator(allDisks); if (!validate(sdValidator.allDomainsExistAndActive()) || !validate(sdValidator.allDomainsWithinThresholds()) || !validateCinder()) { return false; } if (memoryDisksList == null) { return validate(sdValidator.allDomainsHaveSpaceForNewDisks(vmDisksList)); } return validate(sdValidator.allDomainsHaveSpaceForAllDisks(vmDisksList, memoryDisksList)); }</code><technical_language>problem is caused this call, introduced in change I9f42f387781425d16f53a0e8a34d859365808ec0 checked disks relevant for snapshot this patch, in addition LSM bug this vm disks checked if chosen for snapshot. fine restoring behavior previous I9f42f387781425d16f53a0e8a34d859365808ec0 solve issues. check LSM disks delete code performs check LiveMigrateVmDisksCOmmand</technical_language>

Target:
private boolean validateStorage() { List<DiskImage> vmDisksList = getDisksListForChecks(); vmDisksList = ImagesHandler.getDisksDummiesForStorageAllocations(vmDisksList); List<DiskImage> allDisks = new ArrayList<>(vmDisksList); List<DiskImage> memoryDisksList = null; if (getParameters().isSaveMemory()) { memoryDisksList = MemoryUtils.createDiskDummies(getVm().getTotalMemorySizeInBytes(), MemoryUtils.METADATA_SIZE_IN_BYTES); if (Guid.Empty.equals(getStorageDomainIdForVmMemory(memoryDisksList))) { return failCanDoAction(EngineMessage.ACTION_TYPE_FAILED_NO_SUITABLE_DOMAIN_FOUND); } allDisks.addAll(memoryDisksList); } MultipleStorageDomainsValidator sdValidator = createMultipleStorageDomainsValidator(allDisks); if (!validate(sdValidator.allDomainsExistAndActive()) || !validate(sdValidator.allDomainsWithinThresholds()) || !validateCinder()) { return false; } if (memoryDisksList == null) { return validate(sdValidator.allDomainsHaveSpaceForNewDisks(vmDisksList)); } return validate(sdValidator.allDomainsHaveSpaceForAllDisks(vmDisksList, memoryDisksList)); }
Source:
<code>private void handleCaptureRetry(ChargeCaptureMessage captureMessage) throws QueueException { ChargeEntity charge = chargeDao.findByExternalId(captureMessage.getChargeId()) .orElseThrow(() -> new QueueException("Invalid message on capture retry " + captureMessage.getChargeId())); <START> boolean shouldRetry = chargeDao.countCaptureRetriesForCharge(charge.getId()) >= maximumCaptureRetries; <END> if (shouldRetry) { captureQueue.scheduleMessageForRetry(captureMessage); } else { cardCaptureService.markChargeAsCaptureError(captureMessage.getChargeId()); captureQueue.markMessageAsProcessed(captureMessage); } }</code><technical_language>this <= some unit tests cover scenarios</technical_language>

Target:
private void handleCaptureRetry(ChargeCaptureMessage captureMessage) throws QueueException { int numberOfChargeRetries = chargeDao.countCaptureRetriesForChargeExternalId(captureMessage.getChargeId()); boolean shouldRetry = numberOfChargeRetries <= maximumCaptureRetries; if (shouldRetry) { captureQueue.scheduleMessageForRetry(captureMessage); } else { cardCaptureService.markChargeAsCaptureError(captureMessage.getChargeId()); captureQueue.markMessageAsProcessed(captureMessage); } }
Source:
<code>public void fail(Tuple input) { <START> if(stormIdName != null && input.contains(stormIdName)) { <END> String stormId = input.getStringByField(stormIdName); Monitor.getMonitor().endLatency(pair(input), boltService, stormIdName, stormId, new Throwable(boltService + " failed to process tuple") ); } else { Monitor.getMonitor().endLatency(pair(input), boltService, new Throwable(boltService + " failed to process tuple")); } super.fail(input); }</code><technical_language>Java keyword null</technical_language>

Target:
public void fail(Tuple input) { if(stormIdName.isPresent() && input.contains(stormIdName.get())) { String stormId = input.getStringByField(stormIdName.get()); Monitor.getMonitor().endLatency(pair(input), boltService, stormIdName.get(), stormId, new Throwable(boltService + " failed to process tuple") ); } else { Monitor.getMonitor().endLatency(pair(input), boltService, new Throwable(boltService + " failed to process tuple")); } super.fail(input); }
Source:
<code><START> public View getView(final String name) throws CmdLineException { <END> ViewGroup group = Jenkins.getActiveInstance(); View view = null; final StringTokenizer tok = new StringTokenizer(name, "/"); while(tok.hasMoreTokens()) { String viewName = tok.nextToken(); view = group.getView(viewName); if (view == null) throw new IllegalArgumentException(String.format( "No view named %s inside view %s", viewName, group.getDisplayName() )); view.checkPermission(View.READ); if (view instanceof ViewGroup) { group = (ViewGroup) view; } else if (tok.hasMoreTokens()) { throw new IllegalStateException(view.getViewName() + " view can not contain views"); } } return view; }</code><technical_language>CmdLineException is unused in method. [1] break source compatibility binary one. remove it? [1] <LINK_0></technical_language>

Target:
public View getView(final String name) { ViewGroup group = Jenkins.getActiveInstance(); View view = null; final StringTokenizer tok = new StringTokenizer(name, "/"); while(tok.hasMoreTokens()) { String viewName = tok.nextToken(); view = group.getView(viewName); if (view == null) throw new IllegalArgumentException(String.format( "No view named %s inside view %s", viewName, group.getDisplayName() )); view.checkPermission(View.READ); if (view instanceof ViewGroup) { group = (ViewGroup) view; } else if (tok.hasMoreTokens()) { throw new IllegalStateException(view.getViewName() + " view can not contain views"); } } return view; }
Source:
<code>private ImmutableList<ProducerRecord<DivolteIdentifier,AvroRecordBuffer>> sendBatch(final List<ProducerRecord<DivolteIdentifier, AvroRecordBuffer>> batch) throws InterruptedException { final List<Future<RecordMetadata>> sendResults = batch.stream() .map(producer::send) .collect(Collectors.toList()); final ImmutableList.Builder<ProducerRecord<DivolteIdentifier, AvroRecordBuffer>> remaining = ImmutableList.builder(); final int batchSize = batch.size(); for (int i = 0; i < batchSize; ++i) { final Future<RecordMetadata> result = sendResults.get(i); try { final RecordMetadata metadata = result.get(); if (logger.isTraceEnabled()) { final ProducerRecord<DivolteIdentifier, AvroRecordBuffer> record = batch.get(i); <START> logger.trace("Finished sending event (partyId={}) to Kafka: topic/partition/offset = {}/{}/{}", <END> record.value(), metadata.topic(), metadata.partition(), metadata.offset()); } } catch (final ExecutionException e) { final Throwable cause = e.getCause(); final ProducerRecord<DivolteIdentifier, AvroRecordBuffer> record = batch.get(i); if (cause instanceof RetriableException) { if (logger.isDebugEnabled()) { logger.debug("Transient error sending event (partyId=" + record.key() + ") to Kafka. Will retry.", cause); } remaining.add(record); } else { logger.error("Error sending event (partyId=" + record.key() + ") to Kafka. Abandoning batch.", cause); } } } return remaining.build(); }</code><technical_language>trace level elsewhere. if is supported logging implementations</technical_language>

Target:
private ImmutableList<ProducerRecord<DivolteIdentifier,AvroRecordBuffer>> sendBatch(final List<ProducerRecord<DivolteIdentifier, AvroRecordBuffer>> batch) throws InterruptedException { final List<Future<RecordMetadata>> sendResults = batch.stream() .map(producer::send) .collect(Collectors.toList()); final ImmutableList.Builder<ProducerRecord<DivolteIdentifier, AvroRecordBuffer>> remaining = ImmutableList.builder(); final int batchSize = batch.size(); for (int i = 0; i < batchSize; ++i) { final Future<RecordMetadata> result = sendResults.get(i); try { final RecordMetadata metadata = result.get(); if (logger.isDebugEnabled()) { final ProducerRecord<DivolteIdentifier, AvroRecordBuffer> record = batch.get(i); logger.debug("Finished sending event (partyId={}) to Kafka: topic/partition/offset = {}/{}/{}", record.value(), metadata.topic(), metadata.partition(), metadata.offset()); } } catch (final ExecutionException e) { final Throwable cause = e.getCause(); final ProducerRecord<DivolteIdentifier, AvroRecordBuffer> record = batch.get(i); if (cause instanceof RetriableException) { if (logger.isDebugEnabled()) { logger.debug("Transient error sending event (partyId=" + record.key() + ") to Kafka. Will retry.", cause); } remaining.add(record); } else { logger.error("Error sending event (partyId=" + record.key() + ") to Kafka. Abandoning batch.", cause); } } } return remaining.build(); }
Source:
<code>public GroupRest getAdminGroup(@Nullable HttpServletRequest request, UUID collectionId, @Nullable Pageable optionalPageable, Projection projection) { try { Context context = obtainContext(); Collection collection = collectionService.find(context, collectionId); if (collection == null) { throw new ResourceNotFoundException("No such collection: " + collectionId); } <START> Group administrators = collection.getAdministrators(); <END> if (!authorizeService.isAdmin(context) && !authorizeService.authorizeActionBoolean(context, collection, Constants.ADMIN, true)) { throw new AccessDeniedException("The current user was not allowed to retrieve the AdminGroup for" + " collection: " + collectionId); } if (administrators == null) { return null; } return converter.toRest(administrators, projection); } catch (SQLException e) { throw new RuntimeException(e); } }</code><technical_language>This line moved if statement below. reason load Group if access it</technical_language>

Target:
public GroupRest getAdminGroup(@Nullable HttpServletRequest request, UUID collectionId, @Nullable Pageable optionalPageable, Projection projection) { try { Context context = obtainContext(); Collection collection = collectionService.find(context, collectionId); if (collection == null) { throw new ResourceNotFoundException("No such collection: " + collectionId); } try { AuthorizeUtil.authorizeManageAdminGroup(context, collection); } catch (AuthorizeException e) { throw new AccessDeniedException("The current user was not allowed to retrieve the AdminGroup for" + " collection: " + collectionId); } Group administrators = collection.getAdministrators(); if (administrators == null) { return null; } return converter.toRest(administrators, projection); } catch (SQLException e) { throw new RuntimeException(e); } }
Source:
<code>private void refreshClusterHeavyWeightData(VDSGroup cluster) { VDS upServer = getClusterUtils().getRandomUpServer(cluster.getId()); if (upServer == null) { log.debug("No server UP in cluster '{}'. Can't refresh it's data at this point.", cluster.getName()); return; } for (GlusterVolumeEntity volume : getVolumeDao().getByClusterId(cluster.getId())) { log.debug("Refreshing brick statuses for volume '{}' of cluster '{}'", volume.getName(), cluster.getName()); if (volume.isOnline()) { acquireLock(cluster.getId()); try { refreshVolumeDetails(upServer, volume); } catch (Exception e) { log.error("Error while refreshing brick statuses for volume '{}' of cluster '{}': {}", volume.getName(), cluster.getName(), e.getMessage()); log.debug("Exception", e); } finally { releaseLock(cluster.getId()); } runVdsCommand(VDSCommandType.OverrideGlusterVolumeSnapshotSchedule, <START> new GlusterVolumeActionVDSParameters(upServer.getId(), volume.getName(), false)); <END> } } }</code><technical_language>Another do this - set isGlusterCliBasedSchedulingOn flag true metavolume deletion is detected. This avoid calling this 5 minutes. current way, is called for online volume</technical_language>

Target:
private void refreshClusterHeavyWeightData(VDSGroup cluster) { VDS upServer = getClusterUtils().getRandomUpServer(cluster.getId()); if (upServer == null) { log.debug("No server UP in cluster '{}'. Can't refresh it's data at this point.", cluster.getName()); return; } for (GlusterVolumeEntity volume : getVolumeDao().getByClusterId(cluster.getId())) { log.debug("Refreshing brick statuses for volume '{}' of cluster '{}'", volume.getName(), cluster.getName()); if (volume.isOnline()) { acquireLock(cluster.getId()); try { refreshVolumeDetails(upServer, volume); } catch (Exception e) { log.error("Error while refreshing brick statuses for volume '{}' of cluster '{}': {}", volume.getName(), cluster.getName(), e.getMessage()); log.debug("Exception", e); } finally { releaseLock(cluster.getId()); } } } }
Source:
<code>void setConnected(boolean cancelFuture) { if (state == State.CLOSED) { return; } final boolean notifyAvailability; final Future<?> futureToCancel; synchronized (lock) { if (state == State.CLOSED) { return; } futureToCancel = cancelFuture ? future : null; notifyAvailability = (state != State.CONNECTED); if (LOGGER.isDebugEnabled()) { LOGGER.debug( "Solr({}): available", <START> core, <END> (notifyAvailability ? SolrClientAdapter.GOING : SolrClientAdapter.REMAINING)); } this.apiClient = realClient; this.unavailableClient = null; this.state = State.CONNECTED; this.future = null; lock.notifyAll(); } try { finalizeStateChange(notifyAvailability, futureToCancel, null, true); } catch (IOException e) { } }</code><technical_language>Do need this check here? if == previous.get(), is unlikely, logic work fine afaict</technical_language>

Target:
void setConnected(boolean cancelFuture) { if (state == State.CLOSED) { return; } final boolean notifyAvailability; final Future<?> futureToCancel; synchronized (lock) { if (state == State.CLOSED) { return; } futureToCancel = cancelFuture ? future : null; notifyAvailability = shouldNotifyOfAvailability(); this.apiClient = realClient; this.unavailableClient = null; this.state = State.CONNECTED; this.future = null; lock.notifyAll(); } finalizeStateChangeWhileSwallowingIOExceptions(notifyAvailability, futureToCancel, null); }
Source:
<code><START> public Number getPid() { <END> return this.pid; }</code><technical_language>Number -> Integer</technical_language>

Target:
public Long getPid() { return this.pid; }
Source:
<code><START> public String toString() { <END> ToStringBuilder builder = new ToStringBuilder(this); builder.append("details", details); builder.append("errors", errors); builder.append("failures", failures); builder.append("file", file); builder.append("skipped", skipped); builder.append("tests", tests); builder.append("time", time); return builder.toString(); }</code><technical_language>@inverno drop it</technical_language>

Target:
public String toString() { ToStringBuilder builder = new ToStringBuilder(this); builder.append("errors", errors); builder.append("failures", failures); builder.append("file", file); builder.append("skipped", skipped); builder.append("tests", tests); builder.append("testDuration", testDuration); return builder.toString(); }
Source:
<code>private ITreeContentProvider getTypesContentProvider(TypedElement typedElement, IStaticContentProvider contentProvider) { return new UMLSwitch<ITreeContentProvider>() { @Override public ITreeContentProvider defaultCase(EObject object) { return new EncapsulatedContentProvider(EmptyContentProvider.instance); } @Override public ITreeContentProvider caseTypedElement(TypedElement object) { <START> if (object instanceof Port) { return new PortTypeContentProvider(contentProvider); } <END> return new EncapsulatedContentProvider(contentProvider); } @Override public ITreeContentProvider caseParameter(Parameter object) { return new ParameterTypeContentProvider(contentProvider); } }.doSwitch(typedElement); }</code><technical_language>This casePort(Port) method of switch, similar Parameter case</technical_language>

Target:
private ITreeContentProvider getTypesContentProvider(TypedElement typedElement, IStaticContentProvider contentProvider) { return new UMLSwitch<ITreeContentProvider>() { @Override public ITreeContentProvider defaultCase(EObject object) { return new EncapsulatedContentProvider(EmptyContentProvider.instance); } @Override public ITreeContentProvider caseTypedElement(TypedElement object) { return new EncapsulatedContentProvider(contentProvider); } @Override public ITreeContentProvider casePort(Port object) { return new PortTypeContentProvider(contentProvider); } @Override public ITreeContentProvider caseParameter(Parameter object) { return new ParameterTypeContentProvider(contentProvider); } }.doSwitch(typedElement); }
Source:
<code>protected void createTableWidget(final EObject sourceElement, final EStructuralFeature feature, final Collection<?> rows) { final Table table = createTable(sourceElement, feature, rows); <START> if (table == null) { <END> displayError("Cannot initialize the table"); return; } nattableManager = NattableModelManagerFactory.INSTANCE.createNatTableModelManager(table, new EObjectSelectionExtractor()); natTableWidget = nattableManager.createNattable(self, SWT.NONE, null); if (nattableManager instanceof TreeNattableModelManager) { if (null != rows && !rows.isEmpty()) { final RowHideShowLayer layer = nattableManager.getBodyLayerStack().getRowHideShowLayer(); for (int cpt = 0; cpt < rows.size(); cpt++) { natTableWidget.doCommand(new RowHideCommand(layer, 0)); } } ((TreeNattableModelManager) nattableManager).doCollapseExpandAction(CollapseAndExpandActionsEnum.EXPAND_ALL, null); } self.addDisposeListener(getDisposeListener()); natTableWidget.setBackground(self.getBackground()); GridData data = new GridData(SWT.FILL, SWT.FILL, true, true); data.minimumHeight = natTableWidget.getPreferredHeight()-(rows.size()*70); self.setLayoutData(data); natTableWidget.layout(); self.layout(); }</code><technical_language>constant variable</technical_language>

Target:
protected void createTableWidget(final EObject sourceElement, final EStructuralFeature feature, final Collection<?> rows) { final Table table = createTable(sourceElement, feature, rows); if (null == table) { displayError("Cannot initialize the table"); return; } nattableManager = NattableModelManagerFactory.INSTANCE.createNatTableModelManager(table, new EObjectSelectionExtractor()); natTableWidget = nattableManager.createNattable(self, SWT.NONE, null); if (nattableManager instanceof TreeNattableModelManager) { if (null != rows && !rows.isEmpty()) { final RowHideShowLayer layer = nattableManager.getBodyLayerStack().getRowHideShowLayer(); for (int cpt = 0; cpt < rows.size(); cpt++) { natTableWidget.doCommand(new RowHideCommand(layer, 0)); } } ((TreeNattableModelManager) nattableManager).doCollapseExpandAction(CollapseAndExpandActionsEnum.EXPAND_ALL, null); } self.addDisposeListener(getDisposeListener()); natTableWidget.setBackground(self.getBackground()); GridData data = new GridData(SWT.FILL, SWT.FILL, true, true); data.minimumHeight = natTableWidget.getPreferredHeight()-(rows.size()*70); self.setLayoutData(data); natTableWidget.layout(); self.layout(); }
Source:
<code>public Map<SystemRole, String> getChangedRestrictedRoles(AuthorizationConfigDto configuration) throws IOException { Map<SystemRole, String> changed = new HashMap<>(); Map<String, SystemRole> restricted = SystemRole.getRestricted(); for (RoleDto role : configuration.getRoles()) { <START> if (restricted.containsKey(role.getName())) <END> { SystemRole systemRole = restricted.get(role.getName()); String hash = ""; try (ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos)) { oos.writeObject(role); MultipleDigestOutputStream mdos = new MultipleDigestOutputStream(baos); mdos.write(baos.toByteArray()); hash = mdos.getMessageDigestAsHexadecimalString(EncryptionAlgorithmsEnum.MD5.getAlgorithm()); } catch (NoSuchAlgorithmException e) { throw new IOException(e); } if (!hash.equalsIgnoreCase(systemRole.getHash())) { changed.put(systemRole, String.format("Restricted system role %s has been removed", systemRole)); } restricted.remove(role.getName()); } } for (SystemRole systemRole : restricted.values()) { changed.put(systemRole, String.format("Restricted system role%s %s has been removed" , restricted.size() > 1 ? "s" : "" , String.join(", ", restricted.keySet()))); } return changed; }</code><technical_language>reduce code complexity below: java if (!restricted.containsKey(role.getName())) { continue; }</technical_language>

Target:
public Set<SystemRole> getChangedRestrictedRoles(AuthorizationConfigDto configuration) throws IOException { Set<SystemRole> changed = new HashSet<>(); Map<String, SystemRole> restricted = SystemRole.getRestricted(); for (RoleDto role : configuration.getRoles()) { if (!restricted.containsKey(role.getName())) { continue; } SystemRole systemRole = restricted.get(role.getName()); String hash = null; try { hash = MessageDigestUtils.calculateChecksum(role); } catch (NoSuchAlgorithmException e) { throw new IOException(e); } if (!hash.equalsIgnoreCase(systemRole.getHash())) { changed.add(systemRole); } restricted.remove(role.getName()); } changed.addAll(restricted.values()); return changed; }
Source:
<code>public static BlobUrlParts parse(String url) { try { return parse(new URL(url)); } catch (MalformedURLException e) { <START> throw new IllegalArgumentException("Please double check the URL format. URL: " + url); <END> } }</code><technical_language>Error message "Invalid URL format. URL: " + url</technical_language>

Target:
public static BlobUrlParts parse(String url) { try { return parse(new URL(url)); } catch (MalformedURLException e) { throw new IllegalArgumentException("Invalid URL format. URL: " + url); } }
Source:
<code>public Collection<Container> getContainersByServerInstance(final String serverTemplateId, final String serverInstanceId) { final ServerTemplate serverTemplate = loadServerTemplate(serverTemplateId); for (final ServerInstanceKey serverInstance : serverTemplate.getServerInstanceKeys()) { if (serverInstance.getServerInstanceId().equals(serverInstanceId)) { return getContainers(serverInstance); <START> } <END> } return Collections.emptyList(); }</code><technical_language>long touching this code, this a nice, clean stream-based one-liner</technical_language>

Target:
public Collection<Container> getContainersByServerInstance(final String serverTemplateId, final String serverInstanceId) { final ServerTemplate serverTemplate = loadServerTemplate(serverTemplateId); return serverTemplate.getServerInstanceKeys().stream() .filter(serverInstanceKey -> serverInstanceKey.getServerInstanceId().equalsIgnoreCase(serverInstanceId)) .findFirst() .map(this::getContainers) .orElse(Collections.emptyList()); }
Source:
<code>public static void putDefaultsIfAbsent(Properties conf) { { putIfAbsent(conf, "LdapServers", ""); putIfAbsent(conf, "LDAPServerPort", "389"); putIfAbsent(conf, "AdUserName", ""); putIfAbsent(conf, "AdUserPassword", ""); putIfAbsent(conf, "LDAPSecurityAuthentication", "GSSAPI"); putIfAbsent(conf, "AuthenticationMethod" , "LDAP"); putIfAbsent(conf, "LDAPProviderTypes" , ""); putIfAbsent(conf, "LDAPQueryTimeout", "30"); putIfAbsent(conf, "DomainName", ""); putIfAbsent(conf, "SASL_QOP", "auth-conf"); putIfAbsent(conf, "LDAPConnectTimeout", "30"); putIfAbsent(conf, "MaxLDAPQueryPartsNumber", "100"); putIfAbsent(conf, "LDAPOperationTimeout", "30"); putIfAbsent(conf, "LdapQueryPageSize", "1000"); <START> } <END> }</code><technical_language>hmmmm.... properties resource in exact format load iterate</technical_language>

Target:
public static void putDefaultsIfAbsent(Properties conf) { { Properties defaults = new Properties(); try { defaults.load(Utils.class.getResourceAsStream("/builtin/defaults.properties")); for (Map.Entry<Object, Object> entry : defaults.entrySet()) { putIfAbsent(conf, (String) entry.getKey(), (String) entry.getValue()); } } catch (IOException e) { throw new RuntimeException(e); } } }
Source:
<code>public void onPreReceive(final ReceivePack arg0, final Collection<ReceiveCommand> commands) { parseCommands(commands); if (newChange != null && newChange.getResult() == ReceiveCommand.Result.NOT_ATTEMPTED) { createNewChanges(); } doReplaces(); <START> if(!errors.isEmpty()) { <END> for (Map.Entry<Error, List<String>> error : errors.entrySet()) { rp.sendMessage(buildError(error.getKey(), error.getValue())); } rp.sendMessage(COMMAND_REJECTION_MESSAGE_FOOTER); } }</code><technical_language>style-nit space (</technical_language>

Target:
public void onPreReceive(final ReceivePack arg0, final Collection<ReceiveCommand> commands) { parseCommands(commands); if (newChange != null && newChange.getResult() == ReceiveCommand.Result.NOT_ATTEMPTED) { createNewChanges(); } doReplaces(); if (!errors.isEmpty()) { for (Map.Entry<Error, List<String>> error : errors.entrySet()) { rp.sendMessage(buildError(error.getKey(), error.getValue())); } rp.sendMessage(String.format("User: %s", displayName(currentUser))); rp.sendMessage(COMMAND_REJECTION_MESSAGE_FOOTER); } }
Source:
<code>private static String createPortsToPayloadString(Cartridge cartridge) { StringBuilder portMapBuilder = new StringBuilder(); PortMapping[] portMappings = cartridge.getPortMappings(); if (cartridge.getPortMappings()[0] == null) { return null; } for (PortMapping portMapping : portMappings) { <START> portMapBuilder.append(portMapping.getPort()).append("|"); <END> } String portMappingString = portMapBuilder.toString().replaceAll("\\|$", ""); return portMappingString; }</code><technical_language>move character '|' a constant</technical_language>

Target:
private static String createPortsToPayloadString(Cartridge cartridge) { StringBuilder portMapBuilder = new StringBuilder(); PortMapping[] portMappings = cartridge.getPortMappings(); if (cartridge.getPortMappings()[0] == null) { return null; } for (PortMapping portMapping : portMappings) { portMapBuilder.append(portMapping.getPort()).append(PORT_SEPARATOR); } String portMappingString = portMapBuilder.toString().replaceAll("\\|$", ""); return portMappingString; }
Source:
<code>public void smokeTestWith4Servers() { <START> getAuthenticationContext("wildfly-config-dynamic-ssl-test.xml").run(() -> { <END> try { SSLContext dynamicSSLContext = new DynamicSSLContext(); SSLSocketFactory dynamicSSLContextSocketFactory = dynamicSSLContext.getSocketFactory(); SSLSocket clientSslSocket1 = (SSLSocket) dynamicSSLContextSocketFactory.createSocket("localhost", 10001); clientSslSocket1.setUseClientMode(true); clientSslSocket1.setReuseAddress(true); checkOutputIsOK(clientSslSocket1); clientSslSocket1.close(); SSLSocket clientSslSocket2 = (SSLSocket) dynamicSSLContextSocketFactory.createSocket("localhost", 10002); clientSslSocket2.setReuseAddress(true); checkOutputIsOK(clientSslSocket2); clientSslSocket2.close(); SSLSocket clientSslSocket3 = (SSLSocket) dynamicSSLContextSocketFactory.createSocket("127.0.0.1", 10003); clientSslSocket3.setReuseAddress(true); checkOutputIsOK(clientSslSocket3); clientSslSocket3.close(); SSLSocket clientSslSocket4 = (SSLSocket) dynamicSSLContextSocketFactory.createSocket("localhost", 10000); clientSslSocket4.setReuseAddress(true); checkOutputIsOK(clientSslSocket4); clientSslSocket4.close(); } catch (Exception e) { e.printStackTrace(); Assert.fail(); } }); }</code><technical_language>I this is a POC wanted note for test classes dynamically generate certificates, keystores, truststores needed in order avoid test failures in future due certificates expiring. Elytron APIs generate (e.g., SelfSignedX509CertificateAndSigningKey)</technical_language>

Target:
public void smokeTestWith4Servers() throws NoSuchAlgorithmException { SSLContext dynamicSSLContext = new DynamicSSLContext(); SSLSocketFactory dynamicSSLContextSocketFactory = dynamicSSLContext.getSocketFactory(); getAuthenticationContext("wildfly-config-dynamic-ssl-test.xml").run(() -> { try { SSLSocket clientSslSocket1 = (SSLSocket) dynamicSSLContextSocketFactory.createSocket("localhost", 10001); clientSslSocket1.setUseClientMode(true); clientSslSocket1.setReuseAddress(true); checkOutputIsOK(clientSslSocket1); clientSslSocket1.close(); SSLSocket clientSslSocket2 = (SSLSocket) dynamicSSLContextSocketFactory.createSocket("localhost", 10002); clientSslSocket2.setReuseAddress(true); checkOutputIsOK(clientSslSocket2); clientSslSocket2.close(); SSLSocket clientSslSocket3 = (SSLSocket) dynamicSSLContextSocketFactory.createSocket("127.0.0.1", 10003); clientSslSocket3.setReuseAddress(true); checkOutputIsOK(clientSslSocket3); clientSslSocket3.close(); SSLSocket clientSslSocket4 = (SSLSocket) dynamicSSLContextSocketFactory.createSocket("localhost", 10000); clientSslSocket4.setReuseAddress(true); checkOutputIsOK(clientSslSocket4); clientSslSocket4.close(); } catch (Exception e) { Assert.fail(); } }); }
Source:
<code>private ParentWrapper getParentWrapper(ParentObject parentObject) { ParentWrapper parentWrapper = null; int numHelperItems = mHelperItemList.size(); for (int i = 0; i < numHelperItems; i++) { Object helperItem = mHelperItemList.get(i); if (helperItem instanceof ParentWrapper) { if (((ParentWrapper) helperItem).getParentObject().equals(parentObject)) { <START> parentWrapper = (ParentWrapper) helperItem; <END> } } } return parentWrapper; }</code><technical_language>return this point (and return null bottom if matched)</technical_language>

Target:
private ParentWrapper getParentWrapper(ParentObject parentObject) { int numHelperItems = mHelperItemList.size(); for (int i = 0; i < numHelperItems; i++) { Object helperItem = mHelperItemList.get(i); if (helperItem instanceof ParentWrapper) { if (((ParentWrapper) helperItem).getParentObject().equals(parentObject)) { return (ParentWrapper) helperItem; } } } return null; }
Source:
<code>private void checkErrorListener(ObservableValue<? extends Boolean> value, Boolean oldValue, Boolean newValue) { ObservableList<String> styleClass = this.getStyleClass(); if (newValue) { styleClass.removeAll("error"); styleClass.add("error"); } else { styleClass.removeAll("error"); <START> } <END> }</code><technical_language>restructure this if removeAll("error") add if newValue</technical_language>

Target:
private void checkErrorListener(ObservableValue<? extends Boolean> value, Boolean oldValue, Boolean newValue) { ObservableList<String> styleClass = this.getStyleClass(); styleClass.removeAll("error"); if (newValue) { styleClass.add("error"); } }
Source:
<code>protected boolean shouldAddToNotFoundCache( final ResourceStoreRequest request ) { boolean shouldAddToNFC = super.shouldAddToNotFoundCache( request ); if ( shouldAddToNFC ) { shouldAddToNFC = getProxyMode() == null || getProxyMode().shouldProxy(); if ( !shouldAddToNFC && getLogger().isDebugEnabled() ) { getLogger().debug( <START> String.format( "Repository '%s' is in proxy mode '%s', not adding path '%s' to NFC", <END> getId(), getProxyMode(), request.getRequestPath() ) ); } } return shouldAddToNFC; }</code><technical_language>Typo: repository is in proxy mode... "Proxy repository %s is allowed issue remote requests..."</technical_language>

Target:
protected boolean shouldAddToNotFoundCache( final ResourceStoreRequest request ) { boolean shouldAddToNFC = super.shouldAddToNotFoundCache( request ); if ( shouldAddToNFC ) { shouldAddToNFC = getProxyMode() == null || getProxyMode().shouldProxy(); if ( !shouldAddToNFC && getLogger().isDebugEnabled() ) { getLogger().debug( String.format( "Proxy repository '%s' is is not allowed to issue remote requests (%s), not adding path '%s' to NFC", getId(), getProxyMode(), request.getRequestPath() ) ); } } return shouldAddToNFC; }
Source:
<code>protected ParametersAction createParameters(GerritTriggeredEvent event, Job project) { List<ParameterValue> parameters = getDefaultParametersValues(project); setOrCreateParameters(event, project, parameters); try { Constructor<ParametersAction> constructor = ParametersAction.class.getConstructor(List.class, Collection.class); return constructor.newInstance(parameters, GerritTriggerParameters.getNamesSet()); } catch (NoSuchMethodException e) { <START> logger.debug("Running on an old core before safe parameters, we are safe.", e); <END> } catch (IllegalAccessException e) { logger.warn("Running on a core with safe parameters fix available, but not allowed to specify them", e); } catch (Exception e) { logger.warn("Running on a core with safe parameters fix available, but failed to provide them", e); } return new ParametersAction(parameters); }</code><technical_language>safe 2.3, 2.4 2.5</technical_language>

Target:
protected ParametersAction createParameters(GerritTriggeredEvent event, Job project) { List<ParameterValue> parameters = getDefaultParametersValues(project); setOrCreateParameters(event, project, parameters); try { Constructor<ParametersAction> constructor = ParametersAction.class.getConstructor(List.class, Collection.class); return constructor.newInstance(parameters, GerritTriggerParameters.getNamesSet()); } catch (NoSuchMethodException e) { ParametersActionInspection inspection = getParametersInspection(); if (inspection.isInspectionFailure()) { logger.warn("Failed to inspect ParametersAction to determine " + "if we can behave normally around SECURITY-170.\nSee " + "<LINK_0>" + " for information."); } else if (inspection.isHasSafeParameterConfig()) { StringBuilder txt = new StringBuilder( "Running on a core with SECURITY-170 fixed but no direct way for Gerrit Trigger" + " to self-specify safe parameters."); txt.append(" You should consider upgrading to a new Jenkins core version.\n"); if (inspection.isKeepUndefinedParameters()) { txt.append(".keepUndefinedParameters is set so the trigger should behave normally."); } else if (inspection.isSafeParametersSet()) { txt.append("All Gerrit related parameters are set in .safeParameters"); txt.append(" so the trigger should behave normally."); } else { txt.append("No overriding system properties appears to be set,"); txt.append(" your builds might not work as expected.\n"); txt.append("See <LINK_0>"); txt.append(" for information."); } logger.warn(txt.toString()); } else { logger.debug("Running on an old core before safe parameters, we should be safe.", e); } } catch (IllegalAccessException e) { logger.warn("Running on a core with safe parameters fix available, but not allowed to specify them", e); } catch (Exception e) { logger.warn("Running on a core with safe parameters fix available, but failed to provide them", e); } return new ParametersAction(parameters); }
Source:
<code>public void configurePipeline(PipelineConfigurer pipelineConfigurer) { <START> if (!config.containsMacro("port")) { <END> config.validate(); } }</code><technical_language>this is a strange. macro validations for other params config.validate. move check for port method too</technical_language>

Target:
public void configurePipeline(PipelineConfigurer pipelineConfigurer) { config.validate(); }