auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code><START> public Bitstream setLogo(Context context, Community community, MultipartFile uploadfile) <END> throws IOException, AuthorizeException, SQLException { if (community.getLogo() != null) { throw new UnprocessableEntityException( "The community with the given uuid already has a logo: " + community.getID()); } Bitstream bitstream = cs.setLogo(context, community, uploadfile.getInputStream()); cs.update(context, community); bitstreamService.update(context, bitstream); return bitstream; }</code><technical_language>This return BitstreamRest, CollectionRestRepository.setLogo() method</technical_language>

Target:
public BitstreamRest setLogo(Context context, Community community, MultipartFile uploadfile) throws IOException, AuthorizeException, SQLException { if (community.getLogo() != null) { throw new UnprocessableEntityException( "The community with the given uuid already has a logo: " + community.getID()); } Bitstream bitstream = cs.setLogo(context, community, uploadfile.getInputStream()); cs.update(context, community); bitstreamService.update(context, bitstream); return bitstreamConverter.fromModel(context.reloadEntity(bitstream)); }
Source:
<code>void validate() { try { stopAllExpired(); checkActivityRecordValidity(); } catch (ServerException e) { <START> LOG.error(e.getLocalizedMessage(), e); <END> } }</code><technical_language>Is done a purpose error thrown activityDao.findExpired prevent launching checkActivityRecordValidity</technical_language>

Target:
void validate() { try { stopAllExpired(); } catch (ServerException e) { LOG.error(e.getLocalizedMessage(), e); } try { checkActivityRecordValidity(); } catch (ServerException e) { LOG.error(e.getLocalizedMessage(), e); } }
Source:
<code>public void writeTo(StreamOutput out) throws IOException { windowDefinition.writeTo(out); Symbols.toStream(standaloneWithInputs, out); out.writeVInt(windowFunctionContexts.size()); for (var windowFunctionContext : windowFunctionContexts) { Symbols.toStream(windowFunctionContext.function(), out); <START> if (out.getVersion().onOrAfter(Version.V_4_1_0)) { <END> Symbols.toStream(windowFunctionContext.filter(), out); } Symbols.toStream(windowFunctionContext.inputs(), out); } }</code><technical_language>here, checked of loop</technical_language>

Target:
public void writeTo(StreamOutput out) throws IOException { windowDefinition.writeTo(out); Symbols.toStream(standaloneWithInputs, out); out.writeVInt(windowFunctionContexts.size()); boolean onOrAfter4_1_0 = out.getVersion().onOrAfter(Version.V_4_1_0); for (var windowFunctionContext : windowFunctionContexts) { Symbols.toStream(windowFunctionContext.function(), out); if (onOrAfter4_1_0) { Symbols.toStream(windowFunctionContext.filter(), out); } Symbols.toStream(windowFunctionContext.inputs(), out); } }
Source:
<code>protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); <START> boolean handled = mIabHelper.handleActivityResult(requestCode, resultCode, data); <END> }</code><technical_language>handled variable is dropped</technical_language>

Target:
protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); mIabHelper.handleActivityResult(requestCode, resultCode, data); }
Source:
<code>private String getPassFromFile(String passFile) throws IOException { FileReader input = new FileReader(passFile); BufferedReader br = new BufferedReader(input); <START> return br.readLine(); <END> }</code><technical_language>java console facility: System.console().readLine() FYI - approach, care close resource: try { input.close(); br.close(); } catch (Exception e) { // Ignore } return br.readLine();</technical_language>

Target:
private String getPassFromFile(String passFile) throws IOException { FileReader input = new FileReader(passFile); BufferedReader br = new BufferedReader(input); String pass = br.readLine(); try { input.close(); br.close(); } catch (Exception e) { } return pass; }
Source:
<code>public String getAll(final User user, @RequestParam(value = "region", required = false) final String region, ModelMap model) { final Collection<? extends GrantedAuthority> authorities = getCurrentAuthorities(); <START> List<AgentInfo> agents = agentManagerService.getAllVisible(); <END> Collection<AgentInfo> filterAgentByCluster = Collections2.filter(agents, new Predicate<AgentInfo>() { @Override public boolean apply(AgentInfo agentInfo) { return filterAgentByCluster(region, agentInfo.getRegion()); } }); Collection<AgentInfo> filterAgentByUserAuthorityAndId = Collections2.filter(filterAgentByCluster, new Predicate<AgentInfo>() { @Override public boolean apply(AgentInfo agentInfo) { return filterAgentByUserAuthorityAndId(authorities, user.getUserId(), region, agentInfo.getRegion()); } }); model.addAttribute("agents", filterAgentByUserAuthorityAndId); model.addAttribute("region", region); model.addAttribute("regions", regionService.getAllVisibleRegionNames()); File agentPackage = null; if (isClustered()) { if (StringUtils.isNotBlank(region)) { final RegionInfo regionInfo = regionService.getOne(region); agentPackage = agentPackageService.createAgentPackage(region, regionInfo.getIp(), regionInfo.getControllerPort(), null); } } else { agentPackage = agentPackageService.createAgentPackage("", "", getConfig().getControllerPort(), null); } if (agentPackage != null) { model.addAttribute("downloadLink", "/agent/download/" + agentPackage.getName()); } return "agent/list"; }</code><technical_language>agents Collection<AgentInfo> agents here. If so, re-use agents variable in codes</technical_language>

Target:
public String getAll(final User user, @RequestParam(value = "region", required = false) final String region, ModelMap model) { final Collection<? extends GrantedAuthority> authorities = getCurrentAuthorities(); Collection<AgentInfo> agents = agentManagerService.getAllVisible(); agents = filter(agents, new Predicate<AgentInfo>() { @Override public boolean apply(AgentInfo agentInfo) { return filterAgentByCluster(region, agentInfo.getRegion()); } }); agents = filter(agents, new Predicate<AgentInfo>() { @Override public boolean apply(AgentInfo agentInfo) { return filterAgentByUserAuthorityAndId(authorities, user.getUserId(), region, agentInfo.getRegion()); } }); model.addAttribute("agents", agents); model.addAttribute("region", region); model.addAttribute("regions", regionService.getAllVisibleRegionNames()); File agentPackage = null; if (isClustered()) { if (StringUtils.isNotBlank(region)) { final RegionInfo regionInfo = regionService.getOne(region); agentPackage = agentPackageService.createAgentPackage(region, regionInfo.getIp(), regionInfo.getControllerPort(), null); } } else { agentPackage = agentPackageService.createAgentPackage("", "", getConfig().getControllerPort(), null); } if (agentPackage != null) { model.addAttribute("downloadLink", "/agent/download/" + agentPackage.getName()); } return "agent/list"; }
Source:
<code>private int computeSizeOnDisk(Object stateValue, long nodeStart) { int minSize = HTVarInt.getEncodedLengthLong(fStart - nodeStart) + HTVarInt.getEncodedLengthLong(fDuration) + Integer.BYTES + Byte.BYTES; if (stateValue == null) { return minSize; } else if (stateValue instanceof Integer) { return (minSize + Integer.BYTES); } else if (stateValue instanceof Long) { return (minSize + Long.BYTES); } else if (stateValue instanceof Double) { return (minSize + Double.BYTES); } else if (stateValue instanceof CustomStateValue) { return (minSize + Short.BYTES + ((CustomStateValue) stateValue).getSerializedSize()); } String str = null; if (stateValue instanceof String) { str = (String) stateValue; } else { <START> str = stateValue.toString(); <END> } if (str == null) { throw new IllegalStateException(); } int strLength = str.getBytes(CHARSET).length; if (strLength > Short.MAX_VALUE) { throw new IllegalArgumentException("String is too long to be stored in state system: " + str); } return (minSize + strLength + 3); }</code><technical_language>String.valueOf(stateValue)? null str, need for if-then-else, line</technical_language>

Target:
private int computeSizeOnDisk(Object stateValue, long nodeStart) { int minSize = HTVarInt.getEncodedLengthLong(fStart - nodeStart) + HTVarInt.getEncodedLengthLong(fDuration) + Integer.BYTES + Byte.BYTES; if (stateValue == null) { return minSize; } else if (stateValue instanceof Integer) { return (minSize + Integer.BYTES); } else if (stateValue instanceof Long) { return (minSize + Long.BYTES); } else if (stateValue instanceof Double) { return (minSize + Double.BYTES); } else if (stateValue instanceof CustomStateValue) { return (minSize + Short.BYTES + ((CustomStateValue) stateValue).getSerializedSize()); } String str = String.valueOf(stateValue); int strLength = str.getBytes(CHARSET).length; if (strLength > Short.MAX_VALUE) { throw new IllegalArgumentException("String is too long to be stored in state system: " + str); } return (minSize + strLength + 3); }
Source:
<code>protected void createSwarmSlave(Candidate target) throws IOException, InterruptedException, RetryException { HttpClient client = createHttpClient(new URL(target.url)); String labelStr = StringUtils.join(options.labels, ' '); String toolLocationsStr = StringUtils.join(options.toolLocations, ' '); PostMethod post = new PostMethod(target.url + "/plugin/swarm/createSlave?name=" + options.name + "&executors=" + options.executors + param("remoteFsRoot", options.remoteFsRoot.getAbsolutePath()) + param("description", options.description) + param("labels", labelStr) + param("toolLocations", toolLocationsStr) + "&secret=" + target.secret <START> + param("mode", options.mode.toUpperCase()) <END> + param("hash", hash) ); post.setDoAuthentication(true); Crumb csrfCrumb = getCsrfCrumb(client, target); if (csrfCrumb != null) { post.addRequestHeader(csrfCrumb.crumbRequestField, csrfCrumb.crumb); } int responseCode = client.executeMethod(post); if (responseCode != 200) { throw new RetryException( "Failed to create a slave on Jenkins CODE: " + responseCode); } String name = post.getResponseBodyAsString(); if (name == null) { this.name = options.name; return; } name = name.trim(); if (name.isEmpty()) { return; } this.name = name; }</code><technical_language>potential case issues in whacky locales... supply a defaultLocale</technical_language>

Target:
protected void createSwarmSlave(Candidate target) throws IOException, InterruptedException, RetryException { HttpClient client = createHttpClient(new URL(target.url)); String labelStr = StringUtils.join(options.labels, ' '); String toolLocationsStr = StringUtils.join(options.toolLocations, ' '); PostMethod post = new PostMethod(target.url + "/plugin/swarm/createSlave?name=" + options.name + "&executors=" + options.executors + param("remoteFsRoot", options.remoteFsRoot.getAbsolutePath()) + param("description", options.description) + param("labels", labelStr) + param("toolLocations", toolLocationsStr) + "&secret=" + target.secret + param("mode", options.mode.toUpperCase(Locale.ENGLISH)) + param("hash", hash) ); post.setDoAuthentication(true); Crumb csrfCrumb = getCsrfCrumb(client, target); if (csrfCrumb != null) { post.addRequestHeader(csrfCrumb.crumbRequestField, csrfCrumb.crumb); } int responseCode = client.executeMethod(post); if (responseCode != 200) { throw new RetryException(String.format("Failed to create a slave on Jenkins CODE: %s%n%s",responseCode, post.getResponseBodyAsString()) ); } Properties props = new Properties(); InputStream stream = post.getResponseBodyAsStream(); if (stream != null) { try { props.load(stream); } finally { stream.close(); } } String name = props.getProperty("name"); if (name == null) { this.name = options.name; return; } name = name.trim(); if (name.isEmpty()) { this.name = options.name; return; } this.name = name; }
Source:
<code>private void newRowConsumer(TelemetryTask telemetryRow) { final TableWriter.Row row = writer.newRow(); <START> row.putDate(0, telemetryRow.ts); <END> row.putShort(1, telemetryRow.event); row.append(); }</code><technical_language>ts appears in microseconds, putDate() expects millis</technical_language>

Target:
private void newRowConsumer(TelemetryTask telemetryRow) { final TableWriter.Row row = writer.newRow(); row.putDate(0, telemetryRow.ts); row.putShort(1, telemetryRow.event); row.putShort(2, telemetryRow.origin); row.append(); }
Source:
<code>public MarshalledEntry load(Object key) throws PersistenceException { V value = loadKey(key); if (value != null) { Duration expiry = Expiration.getExpiry(expiryPolicy, Expiration.Operation.CREATION); long now = ctx.getTimeService().wallClockTime(); if (expiry.isEternal()) { return ctx.getMarshalledEntryFactory().newMarshalledEntry(value, value, null); } else { <START> long created = now; <END> long exp = now + expiry.getTimeUnit().toMillis(expiry.getDurationAmount()); JCacheInternalMetadata meta = new JCacheInternalMetadata(created, exp); return ctx.getMarshalledEntryFactory().newMarshalledEntry(value, value, meta); } } return null; }</code><technical_language>nitpick: created variable is needed</technical_language>

Target:
public MarshalledEntry load(Object key) throws PersistenceException { V value = loadKey(key); if (value != null) { Duration expiry = Expiration.getExpiry(expiryPolicy, Expiration.Operation.CREATION); long now = ctx.getTimeService().wallClockTime(); if (expiry == null || expiry.isEternal()) { return ctx.getMarshalledEntryFactory().newMarshalledEntry(value, value, null); } else { long exp = now + expiry.getTimeUnit().toMillis(expiry.getDurationAmount()); JCacheInternalMetadata meta = new JCacheInternalMetadata(now, exp); return ctx.getMarshalledEntryFactory().newMarshalledEntry(value, value, meta); } } return null; }
Source:
<code>private void blockingCheckAndRethrow() { <START> if (this.currentTask != null) { this.checkAndRethrow(); } <END> }</code><technical_language>suggestion if (this.currentTask != null) checkAndRethrow();</technical_language>

Target:
private void blockingCheckAndRethrow() { if (this.currentTask != null) checkAndRethrow(); }
Source:
<code>public void theSetActivityCalendarRequestIsReceived() throws Throwable { <START> PROPERTIES_MAP.put(DEVICE_IDENTIFICATION_G_LABEL, this.deviceId.getDeviceIdG()); <END> PROPERTIES_MAP.put(ORGANISATION_IDENTIFICATION_LABEL, this.organisationId.getOrganisationId()); this.RequestRunner(PROPERTIES_MAP, TEST_CASE_NAME_REQUEST, TEST_CASE_XML, TEST_SUITE_XML); }</code><technical_language>SetActivityCalendar tested E-meter DEVICE_IDENTIFICATION_G_LABEL -> DEVICE_IDENTIFICATION_E_LABEL getDeviceIdG -> getDeviceIdE</technical_language>

Target:
public void theSetActivityCalendarRequestIsReceived() throws Throwable { PROPERTIES_MAP.put(DEVICE_IDENTIFICATION_E_LABEL, this.deviceId.getDeviceIdE()); PROPERTIES_MAP.put(ORGANISATION_IDENTIFICATION_LABEL, this.organisationId.getOrganisationId()); this.RequestRunner(PROPERTIES_MAP, TEST_CASE_NAME_REQUEST, TEST_CASE_XML, TEST_SUITE_XML); }
Source:
<code>public void comparesIndexSettingsAndReturnsEquality() { Index index = new Index(fieldNames, indexName, IndexType.TEXT); <START> Index index2 = new Index(fieldNames, indexName, IndexType.TEXT, new Tokenizer("simple")); <END> assertThat(index.equals(index2), is(true)); }</code><technical_language>Tokenizer.DEFAULT</technical_language>

Target:
public void comparesIndexSettingsAndReturnsEquality() { Index index = new Index(fieldNames, indexName, IndexType.TEXT); Index index2 = new Index(fieldNames, indexName, IndexType.TEXT, Tokenizer.DEFAULT); assertThat(index.equals(index2), is(true)); }
Source:
<code>public Optional<SubjectReference> bridge$resolveReferenceOptional() { if (this.impl$subjectReference == null) { <START> new SubjectSettingCallback(this).test(SpongeCommon.getGame().getServiceProvider().permissionService()); <END> } return Optional.ofNullable(this.impl$subjectReference); }</code><technical_language>callbacks this simplified a bipredicate (as a lambda I mean)</technical_language>

Target:
public Optional<SubjectReference> bridge$resolveReferenceOptional() { if (this.impl$subjectReference == null) { SubjectHelper.applySubject(this); } return Optional.ofNullable(this.impl$subjectReference); }
Source:
<code>private void addSnapshotToDB(Map<Guid, DiskImage> oldToNewImageMap, Snapshot snapshot) { VM oldVm = snapshotVmConfigurationHelper.getVmFromConfiguration(snapshot); List<DiskImage> newDiskImages = oldVm.getDiskList() .stream() .map(d -> oldToNewImageMap.get(d.getImageId())) .collect(Collectors.toList()); Guid newSnapshotId = Guid.newGuid(); <START> newDiskImages.forEach(di -> <END> { di.setVmSnapshotId(newSnapshotId); imageDao.update(di.getImage()); }); snapshotsManager.addSnapshot(newSnapshotId, snapshot.getDescription(), snapshot.getStatus(), snapshot.getType(), initClonedVm(oldVm), true, null, null, snapshot.getCreationDate(), newDiskImages, oldVm.getManagedVmDeviceMap(), getCompensationContext()); }</code><technical_language>diskImage</technical_language>

Target:
private void addSnapshotToDB(Map<Guid, DiskImage> oldToNewImageMap, Snapshot snapshot) { VM oldVm = snapshotVmConfigurationHelper.getVmFromConfiguration(snapshot); List<DiskImage> newDiskImages = oldVm.getDiskList() .stream() .map(d -> oldToNewImageMap.get(d.getImageId())) .collect(Collectors.toList()); Guid newSnapshotId = Guid.newGuid(); newDiskImages.forEach(diskImage -> { diskImage.setVmSnapshotId(newSnapshotId); imageDao.update(diskImage.getImage()); }); snapshotsManager.addSnapshot(newSnapshotId, snapshot.getDescription(), snapshot.getStatus(), snapshot.getType(), initClonedVm(oldVm), true, null, null, snapshot.getCreationDate(), newDiskImages, oldVm.getManagedVmDeviceMap(), getCompensationContext()); }
Source:
<code>@Override public boolean isBrowser() { return super.isBrowser() <START> && !getContext().toLowerCase().contains("NATIVE_APP".toLowerCase()); <END> }</code><technical_language>Apache's _StringUtils_ _StringUtils.containsIgnoreCase_ method</technical_language>

Target:
@Override public boolean isBrowser() { return super.isBrowser() && !containsIgnoreCase(getContext(), "NATIVE_APP"); }
Source:
<code>private void fillInExistingPVCs(KubernetesEnvironment k8sEnv, String workspaceId) throws InfrastructureException { k8sEnv .getPersistentVolumeClaims() .putAll( <START> factory <END> .create(workspaceId) .persistentVolumeClaims() .getByLabel(CHE_WORKSPACE_ID_LABEL, workspaceId) .stream() .peek(pvc -> pvc.getAdditionalProperties().put(CHE_PROVISIONED_PVC_PROPERTY, true)) .collect(toMap(pvc -> pvc.getMetadata().getName(), Function.identity()))); }</code><technical_language>Suggestion: split this statements for readability (otherwise mixing k8sEnv PVCS infrastructure PVCS java Map<String, PersistentVolumeClaim> pvcs = factory .create(workspaceId) .persistentVolumeClaims() .getByLabel(CHE_WORKSPACE_ID_LABEL, workspaceId) .stream() .peek(pvc -> pvc.getAdditionalProperties().put(CHE_PROVISIONED_PVC_PROPERTY, true)) .collect(toMap(pvc -> pvc.getMetadata().getName(), Function.identity()))); k8sEnv.getPersistentVolumeClaims().putAll(pvcs)</technical_language>

Target:
private void fillInExistingPVCs(KubernetesEnvironment k8sEnv, String workspaceId) throws InfrastructureException { Map<String, PersistentVolumeClaim> existingPVCs = factory .create(workspaceId) .persistentVolumeClaims() .getByLabel(CHE_WORKSPACE_ID_LABEL, workspaceId) .stream() .peek(pvc -> pvc.getAdditionalProperties().put(CHE_PROVISIONED_PVC_PROPERTY, true)) .collect(toMap(pvc -> pvc.getMetadata().getName(), Function.identity())); k8sEnv.getPersistentVolumeClaims().putAll(existingPVCs); }
Source:
<code>public boolean deployAPI(String apiId, String gatewayLabel) throws ArtifactSynchronizerException { if (gatewayArtifactSynchronizerProperties.isRetrieveFromStorageEnabled() && gatewayArtifactSynchronizerProperties.getGatewayLabels().contains(gatewayLabel)) { if (artifactRetriever != null) { try { String gatewayRuntimeArtifact = artifactRetriever.retrieveArtifact(apiId, gatewayLabel, APIConstants.GatewayArtifactSynchronizer.GATEWAY_INSTRUCTION_PUBLISH); if (gatewayRuntimeArtifact != null) { GatewayAPIDTO gatewayAPIDTO = new Gson().fromJson(gatewayRuntimeArtifact, GatewayAPIDTO.class); apiGatewayAdmin.deployAPI(gatewayAPIDTO); if (debugEnabled) { log.debug("API with " + apiId + " is deployed in gateway with the label of " + gatewayLabel); } return true; } else { String msg = "Error retrieving artifacts for API " + apiId + ". Storage returned null"; log.error(msg); throw new ArtifactSynchronizerException(msg); } } catch (IOException | ArtifactSynchronizerException e) { <START> String msg = "\"Error deploying \" + apiId + \" in Gateway\""; <END> log.error(msg, e); throw new ArtifactSynchronizerException(msg, e); } } else { String msg = "Artifact retriever not found"; log.error(msg); throw new ArtifactSynchronizerException(msg); } } return false; }</code><technical_language>Do need escapes</technical_language>

Target:
public boolean deployAPI(String apiId, String gatewayLabel) throws ArtifactSynchronizerException { if (gatewayArtifactSynchronizerProperties.isRetrieveFromStorageEnabled() && gatewayArtifactSynchronizerProperties.getGatewayLabels().contains(gatewayLabel)) { if (artifactRetriever != null) { try { String gatewayRuntimeArtifact = artifactRetriever.retrieveArtifact(apiId, gatewayLabel, APIConstants.GatewayArtifactSynchronizer.GATEWAY_INSTRUCTION_PUBLISH); if (gatewayRuntimeArtifact != null) { GatewayAPIDTO gatewayAPIDTO = new Gson().fromJson(gatewayRuntimeArtifact, GatewayAPIDTO.class); apiGatewayAdmin.deployAPI(gatewayAPIDTO); if (debugEnabled) { log.debug("API with " + apiId + " is deployed in gateway with the label of " + gatewayLabel); } return true; } else { String msg = "Error retrieving artifacts for API " + apiId + ". Storage returned null"; log.error(msg); throw new ArtifactSynchronizerException(msg); } } catch (IOException | ArtifactSynchronizerException e) { String msg = "Error deploying" + apiId + "in Gateway"; log.error(msg, e); throw new ArtifactSynchronizerException(msg, e); } } else { String msg = "Artifact retriever not found"; log.error(msg); throw new ArtifactSynchronizerException(msg); } } return false; }
Source:
<code>public void writeMixedBadCharacters() throws Exception { OutputStream output = new ByteArrayOutputStream(); write(output, Lists .newArrayList(createTestRepository(kind, firstUrl, labelPropertyKeyCharacters, labelPropertyValue))); String serialized = output.toString(); assertTrue( serialized.contains(("key=\"" + escapeXml(labelPropertyKeyCharacters) + "\"").replace("&apos;", "'"))); assertTrue(serialized.contains("value=\"" + escapeXml(labelPropertyValue) + "\"")); <START> assertEquals(serialized.lastIndexOf(labelPropertyValue), serialized.lastIndexOf(labelPropertyValue)); <END> }</code><technical_language>of firstIndexOf</technical_language>

Target:
public void writeMixedBadCharacters() throws Exception { OutputStream output = new ByteArrayOutputStream(); write(output, Lists .newArrayList(createTestRepository(kind, firstUrl, labelPropertyKeyCharacters, labelPropertyValue))); String serialized = output.toString(); assertTrue( serialized.contains(("key=\"" + escapeXml(labelPropertyKeyCharacters) + "\"").replace("&apos;", "'"))); assertTrue(serialized.contains("value=\"" + escapeXml(labelPropertyValue) + "\"")); assertEquals(serialized.lastIndexOf(labelPropertyValue), serialized.indexOf(labelPropertyValue)); }
Source:
<code>protected Class<?> findClass(final String className) throws ClassNotFoundException { final Set<ClassLoader> classLoaders = packageClassLoaderMap.get(getPackageName(className)); <START> if (classLoaders != null) { <END> for (final ClassLoader cl : classLoaders) { try { return Class.forName(className, true, cl); } catch (ClassNotFoundException e) { } } } throw new ClassNotFoundException(className); }</code><technical_language>Multimap returns empty collection if key is found, simplify this code removing != null test</technical_language>

Target:
protected Class<?> findClass(final String className) throws ClassNotFoundException { final Collection<ClassLoader> classLoaders = packageClassLoaderMap.get(getPackageName(className)); for (final ClassLoader cl : classLoaders) { try { return Class.forName(className, true, cl); } catch (ClassNotFoundException e) { } } throw new ClassNotFoundException(className); }
Source:
<code>public void privateField() throws NoSuchFieldException { MemberAccessor memberAccessor = MemberAccessorFactory.buildMemberAccessor( TestdataVisibilityModifierSolution.class.getDeclaredField("privateField"), MemberAccessorFactory.MemberAccessorType.FIELD_OR_GETTER_METHOD_WITH_SETTER, ProblemFactProperty.class); assertEquals("privateField", memberAccessor.getName()); assertEquals(String.class, memberAccessor.getType()); TestdataVisibilityModifierSolution s1 = new TestdataVisibilityModifierSolution("s1", "firstValue", "n/a", "n/a", "n/a", "n/a", "n/a"); assertSame("firstValue", memberAccessor.executeGetter(s1)); memberAccessor.executeSetter(s1, "secondValue"); <START> assertSame("secondValue", memberAccessor.executeGetter(s1)); <END> }</code><technical_language>Is guaranteed String literals represented String instance? I a result of JVM optimization I rely that. If correct, this changed assertEquals() java String v2 = "secondValue"; memberAccessor.executeSetter(s1, v2); assertSame(v2, memberAccessor.executeGetter(s1));</technical_language>

Target:
public void privateField() throws NoSuchFieldException { MemberAccessor memberAccessor = MemberAccessorFactory.buildMemberAccessor( TestdataVisibilityModifierSolution.class.getDeclaredField("privateField"), MemberAccessorFactory.MemberAccessorType.FIELD_OR_GETTER_METHOD_WITH_SETTER, ProblemFactProperty.class); assertInstanceOf(ReflectionFieldMemberAccessor.class, memberAccessor); assertEquals("privateField", memberAccessor.getName()); assertEquals(String.class, memberAccessor.getType()); TestdataVisibilityModifierSolution s1 = new TestdataVisibilityModifierSolution("s1", "firstValue", "n/a", "n/a", "n/a", "n/a", "n/a"); assertEquals("firstValue", memberAccessor.executeGetter(s1)); memberAccessor.executeSetter(s1, "secondValue"); assertEquals("secondValue", memberAccessor.executeGetter(s1)); }
Source:
<code>private String getUniqueId() { String unique = null; Connection conn = null; try { conn = TransactionLegacy.getStandaloneConnection(); <START> PreparedStatement pstmt = conn.prepareStatement("SELECT version,updated FROM version ORDER BY id ASC LIMIT 1"); <END> ResultSet rs = pstmt.executeQuery(); if (rs.next()) { unique = DigestUtils.sha256Hex(rs.getString(1) + rs.getString(2)); } else { s_logger.debug("No rows found in the version table. Unable to obtain unique ID for this environment"); } rs.close(); } catch (SQLException e) { s_logger.debug("Unable to get the unique ID of this environment: " + e.getMessage()); } finally { try { conn.close(); } catch (SQLException e) { } } s_logger.debug("Usage Report Unique ID is: " + unique); return unique; }</code><technical_language>Is this resource closed? Do want close resources in exception path well</technical_language>

Target:
protected String getUniqueId() { VersionVO version = null; String unique = null; try { List<VersionVO> versions = _versionDao.getAllVersions(); if (versions != null && !versions.isEmpty()) { version = versions.get(0); unique = DigestUtils.sha256Hex(version.getVersion() + dateFormat.format(version.getUpdated())); } else { s_logger.info("No rows found in the version table. Unable to obtain unique ID for this environment"); } s_logger.debug("Usage Report Unique ID is: " + unique); return unique; } catch (Exception e) { s_logger.error("Failed to fetch the UniqueID: " + e.getMessage()); return null; } }
Source:
<code>Role(String name, Pattern pattern, Set < Permission > permissions) { this.name = name; this.pattern = pattern; <START> if (permissions.remove(null)) { <END> LOGGER.warning("Found some null permission(s)"); } this.permissions.addAll(permissions); }</code><technical_language>Note remove permissions input collections. non-modifyable Set... A correct fix iterate permissions add non-Null this.permissions.add(). fine for is annotate collection arguments in target Java baseline</technical_language>

Target:
Role(String name, Pattern pattern, Set < Permission > permissions) { this.name = name; this.pattern = pattern; for(Permission perm : permissions) { if(perm == null ){ LOGGER.log(Level.WARNING, "Found some null permission(s) in role " + this.name, new IllegalStateException()); } else { this.permissions.add(perm); } } }
Source:
<code>private Object handleWriteManyOnPrimary(InvocationContext ctx, VisitableCommand command, Object rv) { WriteCommand cmd = (WriteCommand) command; int numKeys = cmd.getAffectedKeys().size(); InternalCacheValue[] values = new InternalCacheValue[numKeys]; int i = 0; ComposedCompletionStage composedCompletionStage = CompletionStages.composedCompletionStage(); for (Object key : cmd.getAffectedKeys()) { RepeatableReadEntry entry = (RepeatableReadEntry) ctx.lookupEntry(key); EntryVersion nextVersion = svm.incrementVersion(keyPartitioner.getSegment(key)); entry.setMetadata(addVersion(entry.getMetadata(), nextVersion)); if (cmd.loadType() == DONT_LOAD) { composedCompletionStage.dependsOn(commitSingleEntryIfNewer(entry, ctx, command)); } else { composedCompletionStage.dependsOn(commitSingleEntryIfNoChange(entry, ctx, command)); } values[i++] = new MetadataImmortalCacheValue(entry.getValue(), entry.getMetadata()); } composedCompletionStage.freeze(); if (cmd.loadType() == DONT_LOAD) { cmd.setFlagsBitSet(cmd.getFlagsBitSet() & ~FlagBitSets.IGNORE_RETURN_VALUES); if (CompletionStages.isComplete(composedCompletionStage)) { return manyWriteResponse(ctx, cmd, values); } return asyncValue(composedCompletionStage).thenApply(ctx, cmd, <START> (rCtx2, rCommand2, rv2) -> manyWriteResponse(rCtx2, cmd, values)); <END> } else { Object[] returnValue = {values, ((List) rv).toArray()}; if (CompletionStages.isComplete(composedCompletionStage)) { return manyWriteResponse(ctx, cmd, returnValue); } return asyncValue(composedCompletionStage).thenApply(ctx, cmd, (rCtx2, rCommand2, rv2) -> manyWriteResponse(ctx, cmd, returnValue)); } }</code><technical_language>I worth duplicating code avoid lambda... OTOH thenApply moved if statement</technical_language>

Target:
private Object handleWriteManyOnPrimary(InvocationContext ctx, VisitableCommand command, Object rv) { WriteCommand cmd = (WriteCommand) command; int numKeys = cmd.getAffectedKeys().size(); InternalCacheValue[] values = new InternalCacheValue[numKeys]; int i = 0; AggregateCompletionStage<Void> aggregateCompletionStage = CompletionStages.aggregateCompletionStage(); for (Object key : cmd.getAffectedKeys()) { RepeatableReadEntry entry = (RepeatableReadEntry) ctx.lookupEntry(key); EntryVersion nextVersion = svm.incrementVersion(keyPartitioner.getSegment(key)); entry.setMetadata(addVersion(entry.getMetadata(), nextVersion)); if (cmd.loadType() == DONT_LOAD) { aggregateCompletionStage.dependsOn(commitSingleEntryIfNewer(entry, ctx, command)); } else { aggregateCompletionStage.dependsOn(commitSingleEntryIfNoChange(entry, ctx, command)); } values[i++] = new MetadataImmortalCacheValue(entry.getValue(), entry.getMetadata()); } CompletionStage<Void> aggregatedStage = aggregateCompletionStage.freeze(); Object returnValue; if (cmd.loadType() == DONT_LOAD) { cmd.setFlagsBitSet(cmd.getFlagsBitSet() & ~FlagBitSets.IGNORE_RETURN_VALUES); returnValue = values; } else { returnValue = new Object[]{values, ((List) rv).toArray()}; } return asyncValue(aggregatedStage).thenApply(ctx, cmd, ((rCtx, rCommand, rv1) -> manyWriteResponse(rCtx, cmd, returnValue))); }
Source:
<code>public static void main(String[] args) throws Exception { final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment(); env.setDegreeOfParallelism(4); DataSet<String> text = env.fromElements("To be", "or not to be", "or to be still", "and certainly not to be not at all", "is that the question?"); DataSet<WC> tokenized = text.flatMap(new Tokenizer()); DataSet<WC> result = tokenized .groupBy(new KeySelector<WC, String>() { public String getKey(WC v) { return v.word; } }) <START> <END> .reduce(new ReduceFunction<WC>() { private Collection<DataSet<?>> i; @Override public void open(Configuration parameters) throws Exception { i = this.getRuntimeContext().getBroadcastVariable("lol"); } public WC reduce(WC value1, WC value2) { return new WC(value1.word, value1.count + value2.count); } }).withBroadcastSet(null, null); result.print(); env.execute(); }</code><technical_language>feels this class is accidentally changed in here..</technical_language>

Target:
public static void main(String[] args) throws Exception { final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment(); env.setDegreeOfParallelism(4); DataSet<String> text = env.fromElements("To be", "or not to be", "or to be still", "and certainly not to be not at all", "is that the question?"); DataSet<WC> tokenized = text.flatMap(new Tokenizer()); DataSet<WC> result = tokenized .groupBy(new KeySelector<WC, String>() { public String getKey(WC v) { return v.word; } }) .reduce(new ReduceFunction<WC>() { public WC reduce(WC value1, WC value2) { return new WC(value1.word, value1.count + value2.count); } }); result.print(); env.execute(); }
Source:
<code>public DefaultCompilationResponse(final Boolean successful, final List<String> mavenOutput, final Path workingDir, <START> final List<String> projectDependencies, <END> final String requestUUID) { this.successful = successful; if(mavenOutput != null) { this.mavenOutput = new ArrayList<>(mavenOutput); }else{ this.mavenOutput = Collections.emptyList(); } if(projectDependencies != null) { this.projectDependencies = new ArrayList<>(projectDependencies); }else{ this.projectDependencies = Collections.emptyList(); } this.workingDir = workingDir; this.requestUUID = requestUUID; }</code><technical_language>here. rewritten call constructor above: public DefaultCompilationResponse(final Boolean successful, final List<String> mavenOutput, final Path workingDir, final List<String> projectDependencies, final String requestUUID) { this(successful, mavenOutput, workingDir, Collections.emptyList(), projectDependencies, requestUUID); }</technical_language>

Target:
public DefaultCompilationResponse(final Boolean successful, final List<String> mavenOutput, final Path workingDir, final List<String> projectDependencies, final String requestUUID) { this(successful,mavenOutput,workingDir, Collections.emptyList(), projectDependencies, requestUUID); }
Source:
<code>public RollbackOptions update(UpdateOptions opt) throws PackageException { String key = getKey(opt); Entry entry = registry.get(key); if (entry == null) { entry = createEntry(key); } else if (!entry.hasBaseVersion() <START> && entry.getLastVersion(false) == null) { <END> if (updateBaseVersion(entry)) { log.warn("Registry repaired: JAR introduced without corresponding entry in the registry (copy task?) : " + key); } } Version v = entry.getVersion(opt.version); boolean newVersion = v == null; if (v == null) { v = entry.addVersion(new Version(opt.getVersion())); v.setPath(getVersionPath(opt)); } v.addPackage(opt); if (newVersion || opt.isSnapshotVersion()) { backupFile(opt.getFile(), v.getPath()); } Match<File> currentJar = findInstalledJar(key); UpdateOptions optToUpdate = shouldUpdate(key, opt, currentJar); if (optToUpdate != null) { File currentFile = currentJar != null ? currentJar.object : null; doUpdate(currentFile, optToUpdate); } return new RollbackOptions(key, opt); }</code><technical_language>if () need split lines</technical_language>

Target:
public RollbackOptions update(UpdateOptions opt) throws PackageException { String key = getKey(opt); Entry entry = registry.get(key); if (entry == null) { entry = createEntry(key); } else if (!entry.hasBaseVersion() && entry.getLastVersion(false) == null) { if (createBaseVersion(entry)) { log.warn("Registry repaired: JAR introduced without corresponding entry in the registry (copy task?) : " + key); } } Version v = entry.getVersion(opt.version); boolean newVersion = v == null; if (v == null) { v = entry.addVersion(new Version(opt.getVersion())); v.setPath(getVersionPath(opt)); } v.addPackage(opt); if (newVersion || opt.isSnapshotVersion()) { backupFile(opt.getFile(), v.getPath()); } Match<File> currentJar = findInstalledJar(key); UpdateOptions optToUpdate = shouldUpdate(key, opt, currentJar); if (optToUpdate != null) { File currentFile = currentJar != null ? currentJar.object : null; doUpdate(currentFile, optToUpdate); } return new RollbackOptions(key, opt); }
Source:
<code>public void onDisconnected() { LOG.info("ConsumerConnector shutting down"); try { scheduler.shutdown(); for (Map.Entry<String, List<FetcherRunnable>> entry : consumerThreadsMap.entrySet()) { for (FetcherRunnable fetcherThread : entry.getValue()) { try { fetcherThread.shutdown(); } catch (InterruptedException e) { LOG.warn(e.getMessage(), e); } } LOG.debug("Clear consumer=>fetcherthread map. KEY[" + entry.getKey() + "]"); <START> entry.getValue().clear(); <END> } for (Map.Entry<String, BlockingQueue<FetchedDataChunk>> entry : queues.entrySet()) { LOG.debug("Clear consumer=>queue map. KEY[" + entry.getKey() + "]"); entry.getValue().clear(); try { entry.getValue().put(SHUTDOWN_COMMAND); } catch (InterruptedException e) { LOG.warn(e.getMessage(), e); } } if (Consumer.config.isAutoCommit()) { commitOffsets(); } for (Map.Entry<String, Map<String, PartitionTopicInfo>> entry : allPartitions.entrySet()) { LOG.debug("Clear consumer=>partition map. KEY[" + entry.getKey() + "]"); entry.getValue().clear(); } consumerThreadsMap.clear(); queues.clear(); topicToConsumerMap.clear(); allPartitions.clear(); } catch (Exception e) { LOG.error("error during consumer connector shutdown", e); } LOG.info("ConsumerConnector shut down completed"); }</code><technical_language>if want remove information stored in map, remove entry instead of clear</technical_language>

Target:
public void onDisconnected() { LOG.info("ConsumerConnector shutting down"); try { scheduler.shutdown(); for (Map.Entry<String, List<FetcherRunnable>> entry : consumerThreadsMap.entrySet()) { for (FetcherRunnable fetcherThread : entry.getValue()) { try { fetcherThread.shutdown(); } catch (InterruptedException e) { LOG.warn(e.getMessage(), e); } } LOG.debug("Clear consumer=>fetcherthread map. KEY[" + entry.getKey() + "]"); } for (Map.Entry<String, BlockingQueue<FetchedDataChunk>> entry : queues.entrySet()) { LOG.debug("Clear consumer=>queue map. KEY[" + entry.getKey() + "]"); entry.getValue().clear(); try { entry.getValue().put(SHUTDOWN_COMMAND); } catch (InterruptedException e) { LOG.warn(e.getMessage(), e); } } consumerThreadsMap.clear(); queues.clear(); allPartitions.clear(); } catch (Exception e) { LOG.error("error during consumer connector shutdown", e); } LOG.info("ConsumerConnector shut down completed"); }
Source:
<code>public CommitValidationException(String reason) { super(reason); <START> this.messages = Collections.<CommitValidationMessage>emptyList(); <END> }</code><technical_language>[optional] write Collections.emptyList()</technical_language>

Target:
public CommitValidationException(String reason) { super(reason); this.messages = Collections.emptyList(); }
Source:
<code>public ResponseEntity<Map<String, Object>> handleTypeMismatchError(TypeMismatchException ex){ ErrorReason errorStatus = ErrorReason.WRONG_REQUEST_PARAMETER_ERROR; ErrorRepresentation.Builder builder = create(errorStatus, ex); builder.propertyName(ex.getPropertyName()); <START> String message = String.format("parameter can't have value '%s'", ex.getValue()); <END> builder.message(message); return createErrorResponse(builder, errorStatus); }</code><technical_language>give a more formal description, e.g.: incorrect parameter '%s'</technical_language>

Target:
public ResponseEntity<Map<String, Object>> handleTypeMismatchError(TypeMismatchException ex){ ErrorReason errorStatus = ErrorReason.WRONG_REQUEST_PARAMETER_ERROR; ErrorRepresentation.Builder builder = create(errorStatus, ex); builder.propertyName(ex.getPropertyName()); String message = String.format("incorrect parameter value '%s'", ex.getValue()); builder.message(message); return createErrorResponse(builder, errorStatus); }
Source:
<code>private String loadMostRecentArtifact(String location, String host, Integer port) { JSONObject json = getArtifactMetadata(location, host, port); if (json == null) { LOG.error("got null metadata"); return null; } <START> @SuppressWarnings("checkstyle:AbbreviationAsWordInName") <END> String downloadURI = (String) json.get("downloadUri"); if (downloadURI != null) { String returnValue = doGet(null, location, host, port); saveInArtifactoryCache(returnValue); return returnValue; } JSONArray msg = (JSONArray) json.get("children"); if (msg == null || msg.size() == 0) { LOG.error("Expected directory children not present"); return null; } JSONObject newest = (JSONObject) Collections.max(msg, new DirEntryCompare()); if (newest == null) { LOG.error("Failed to find most recent artifact uri in {}", location); return null; } String uri = (String) newest.get("uri"); if (uri == null) { LOG.error("Expected directory uri not present"); return null; } String returnValue = doGet(null, location + uri, host, port); saveInArtifactoryCache(returnValue); return returnValue; }</code><technical_language>rename</technical_language>

Target:
private String loadMostRecentArtifact(String location, String host, Integer port) { JSONObject json = getArtifactMetadata(location, host, port); if (json == null) { LOG.error("got null metadata"); return null; } String downloadUri = (String) json.get("downloadUri"); if (downloadUri != null) { String returnValue = doGet(null, location, host, port); saveInArtifactoryCache(returnValue); return returnValue; } JSONArray msg = (JSONArray) json.get("children"); if (msg == null || msg.size() == 0) { LOG.error("Expected directory children not present"); return null; } JSONObject newest = (JSONObject) Collections.max(msg, new DirEntryCompare()); if (newest == null) { LOG.error("Failed to find most recent artifact uri in {}", location); return null; } String uri = (String) newest.get("uri"); if (uri == null) { LOG.error("Expected directory uri not present"); return null; } String returnValue = doGet(null, location + uri, host, port); saveInArtifactoryCache(returnValue); return returnValue; }
Source:
<code>public void createConnectionTest() throws TimeoutException, Exception { <START> IntegrationTestRosterUtil.ensureBothAccountsAreSubscribedToEachOther(conOne, conTwo, timeout); <END> EntityBareJid userTwo = conTwo.getUser().asEntityBareJid(); final String messageBody = "Hello from the other side!"; Message message = conTwo.getStanzaFactory().buildMessageStanza() .to(userTwo) .setBody(messageBody) .build(); final SimpleResultSyncPoint messageReceived = new SimpleResultSyncPoint(); final StanzaListener stanzaListener = new StanzaListener() { @Override public void processStanza(Stanza stanza) { Message message = (Message) stanza; if (message.getBody().equals(messageBody)) { messageReceived.signal(); } } }; conTwo.addAsyncStanzaListener(stanzaListener, MessageWithBodiesFilter.INSTANCE); try { conOne.sendStanza(message); messageReceived.waitForResult(timeout); } finally { conTwo.removeAsyncStanzaListener(stanzaListener); } }</code><technical_language>I this is necessary</technical_language>

Target:
public void createConnectionTest() throws TimeoutException, Exception { EntityFullJid userTwo = conTwo.getUser(); final String messageBody = testRunId + ": Hello from the other side!"; Message message = conTwo.getStanzaFactory().buildMessageStanza() .to(userTwo) .setBody(messageBody) .build(); final SimpleResultSyncPoint messageReceived = new SimpleResultSyncPoint(); final StanzaListener stanzaListener = (Stanza stanza) -> { if (((Message) stanza).getBody().equals(messageBody)) { messageReceived.signal(); } }; conTwo.addAsyncStanzaListener(stanzaListener, MessageWithBodiesFilter.INSTANCE); try { conOne.sendStanza(message); messageReceived.waitForResult(timeout); } finally { conTwo.removeAsyncStanzaListener(stanzaListener); } }
Source:
<code>public void checkConfig() { assertNotNull(gateway); assertThat((Boolean) getPropertyValue(gateway, "expectReply"), is(true)); assertThat((Boolean) getPropertyValue(gateway, "convertExceptions"), is(true)); assertThat((PollableChannel) getPropertyValue(gateway, "replyChannel"), is(responses)); assertNotNull(TestUtils.getPropertyValue(gateway, "errorChannel")); MessagingTemplate messagingTemplate = TestUtils.getPropertyValue( gateway, "messagingTemplate", MessagingTemplate.class); assertEquals(Long.valueOf(1234), TestUtils.getPropertyValue(messagingTemplate, "sendTimeout")); assertEquals(Long.valueOf(4567), TestUtils.getPropertyValue(messagingTemplate, "receiveTimeout")); boolean registerDefaultConverters = TestUtils.getPropertyValue(gateway,"registerDefaultConverters", Boolean.class); assertThat(registerDefaultConverters, is(true)); @SuppressWarnings("unchecked") List<HttpMessageConverter<?>> messageConverters = TestUtils.getPropertyValue(gateway,"messageConverters", List.class); <START> assertThat(messageConverters.size()>0, is(true)); <END> }</code><technical_language>Convert, please, assertTrue</technical_language>

Target:
public void checkConfig() { assertNotNull(gateway); assertThat((Boolean) getPropertyValue(gateway, "expectReply"), is(true)); assertThat((Boolean) getPropertyValue(gateway, "convertExceptions"), is(true)); assertThat((PollableChannel) getPropertyValue(gateway, "replyChannel"), is(responses)); assertNotNull(TestUtils.getPropertyValue(gateway, "errorChannel")); MessagingTemplate messagingTemplate = TestUtils.getPropertyValue( gateway, "messagingTemplate", MessagingTemplate.class); assertEquals(Long.valueOf(1234), TestUtils.getPropertyValue(messagingTemplate, "sendTimeout")); assertEquals(Long.valueOf(4567), TestUtils.getPropertyValue(messagingTemplate, "receiveTimeout")); boolean registerDefaultConverters = TestUtils.getPropertyValue(gateway,"mergeWithDefaultConverters", Boolean.class); assertFalse("By default the register-default-converters flag should be false", registerDefaultConverters); @SuppressWarnings("unchecked") List<HttpMessageConverter<?>> messageConverters = TestUtils.getPropertyValue(gateway,"messageConverters", List.class); assertTrue("The default converters should have been registered, given there are no custom converters", messageConverters.size() > 0); }