auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected IStatus run(final IProgressMonitor monitor) { int alreadyDone = 0; ITmfTraceKnownSize traceWithSize = (ITmfTraceKnownSize) fTrace; if (fTraceWithSize != null) { monitor.beginTask("", traceWithSize.size()); } else { monitor.beginTask("", IProgressMonitor.UNKNOWN); } while (!monitor.isCanceled()) { try { long prevNbEvents = fTrace.getNbEvents(); Thread.sleep(250); long nbEvents = fTrace.getNbEvents(); if (fTraceWithSize != null) { final int done = traceWithSize.progress(); monitor.worked(done - alreadyDone); alreadyDone = done; } setName(Messages.TmfCheckpointIndexer_Indexing + ' ' + fTrace.getName() + " (" + String.format("%,d", nbEvents) + ")"); long rate = (nbEvents - prevNbEvents) * 4; monitor.setTaskName(String.format("%,d", rate) + " " + Messages.TmfCheckpointIndexer_EventsPerSecond); } catch (final InterruptedException e) { return Status.OK_STATUS; } } monitor.done(); return fException != null ? new Status(IStatus.ERROR, Activator.PLUGIN_ID, fException.getMessage(), fException) : Status.OK_STATUS; }

Target:
protected IStatus run(final IProgressMonitor monitor) { SubMonitor subMonitor = SubMonitor.convert(monitor); if (fTraceWithSize != null) { subMonitor.beginTask("", fTraceWithSize.size()); } else { subMonitor.beginTask("", IProgressMonitor.UNKNOWN); } while (!monitor.isCanceled()) { try { long prevNbEvents = fTrace.getNbEvents(); Thread.sleep(250); long nbEvents = fTrace.getNbEvents(); if (fTraceWithSize != null) { final int done = fTraceWithSize.progress(); subMonitor.setWorkRemaining(fTraceWithSize.size() - done); subMonitor.worked(done); } setName(Messages.TmfCheckpointIndexer_Indexing + ' ' + fTrace.getName() + " (" + String.format("%,d", nbEvents) + ")"); long rate = (nbEvents - prevNbEvents) * 4; subMonitor.setTaskName(String.format("%,d", rate) + " " + Messages.TmfCheckpointIndexer_EventsPerSecond); } catch (final InterruptedException e) { return Status.OK_STATUS; } } subMonitor.done(); monitor.done(); return fException != null ? new Status(IStatus.ERROR, Activator.PLUGIN_ID, fException.getMessage(), fException) : Status.OK_STATUS; }
Source:
protected boolean assignHostsToGroups(CommandContext context) { boolean requiresRestart = false; Map<String, String> hostGroups = context.getAppConfig().getHostGroups(); HostManager hostMgr = new HostManager(context.getManageClient()); for (Map.Entry<String, String> entry : hostGroups.entrySet()) { String hostName = entry.getKey(); String groupName = entry.getValue(); ServerManager serverMgr = new ServerManager(context.getManageClient(), groupName); if (serverMgr.exists(MANAGE_SERVER_NAME, "group-id="+groupName)) { logger.info(format("%s appserver already exists in target group %s", MANAGE_SERVER_NAME, groupName)); } else { String manageServerPayload = format(MANAGE_SERVER_JSON_TEMPLATE, MANAGE_SERVER_NAME, groupName); serverMgr.save(manageServerPayload); logger.info(format("Created the %s appserver in target group %s", MANAGE_SERVER_NAME, groupName)); } if (serverMgr.exists(APP_SERVER_NAME, "group-id="+groupName)) { logger.info(format("%s appserver already exists in target group %s", APP_SERVER_NAME, groupName)); } else { String manageServerPayload = format(APP_SERVER_JSON_TEMPLATE, APP_SERVER_NAME, groupName); serverMgr.save(manageServerPayload); logger.info(format("Created the %s appserver in target group %s", APP_SERVER_NAME, groupName)); } if (hostMgr.getAssignedGroupName(hostName) != groupName) { hostMgr.setHostToGroup(hostName, groupName); requiresRestart = true; } } return requiresRestart; }

Target:
protected boolean assignHostsToGroups(CommandContext context) { boolean requiresRestart = false; Map<String, String> hostGroups = context.getAppConfig().getHostGroups(); HostManager hostMgr = new HostManager(context.getManageClient()); for (Map.Entry<String, String> entry : hostGroups.entrySet()) { String hostName = entry.getKey(); String groupName = entry.getValue(); ServerManager serverMgr = new ServerManager(context.getManageClient(), groupName); if (serverMgr.exists(ManageServer.MANAGE_SERVER_NAME)) { logger.info(format("%s appserver already exists in target group %s", ManageServer.MANAGE_SERVER_NAME, groupName)); } else { manageServerTemplate.setGroupName(groupName); serverMgr.save(manageServerTemplate.getJson()); logger.info(format("Created the %s appserver in target group %s", ManageServer.MANAGE_SERVER_NAME, groupName)); } if (serverMgr.exists(AppServicesServer.APP_SERVICES_SERVER_NAME)) { logger.info(format("%s appserver already exists in target group %s", AppServicesServer.APP_SERVICES_SERVER_NAME, groupName)); } else { appServicesServerTemplate.setGroupName(groupName); serverMgr.save(appServicesServerTemplate.getJson()); logger.info(format("Created the %s appserver in target group %s", AppServicesServer.APP_SERVICES_SERVER_NAME, groupName)); } if (!groupName.equals(hostMgr.getAssignedGroupName(hostName))) { hostMgr.setHostToGroup(hostName, groupName); requiresRestart = true; } } return requiresRestart; }
Source:
public void test_n_iterations() { ArrayList<CandidateClusterContext> arrayList = new ArrayList<CandidateClusterContext>(); int n = 15; for (int i = 0; i < 10; i++) { arrayList.add(createContext()); } ClientDiscoveryService discoveryService = new ClientDiscoveryService(15, arrayList); int count = 0; while (discoveryService.hasNext()) { discoveryService.next(); count++; } assertEquals(10 * n, count); discoveryService.next(); }

Target:
public void test_n_iterations() { ArrayList<CandidateClusterContext> arrayList = new ArrayList<CandidateClusterContext>(); int n = 15; for (int i = 0; i < 10; i++) { arrayList.add(createContext()); } ClientDiscoveryService discoveryService = new ClientDiscoveryService(n, arrayList); int count = 0; while (discoveryService.hasNext()) { discoveryService.next(); count++; } assertEquals(10 * n, count); discoveryService.next(); }
Source:
public synchronized String getFieldString(int size, String s) { try { buffer.replace(0, size, emptyString); buffer.setLength(size); int maxSize = size; if (s != null) { buffer.replace(0, size, s); int currentBytes = s.substring(0, Math.min(size, s.length())) .getBytes(charset.name()).length; if (currentBytes > size) { char[] c = new char[1]; for (int index = size - 1; currentBytes > size; index--) { c[0] = buffer.charAt(index); String string = new String(c); buffer.deleteCharAt(index); currentBytes -= string.getBytes().length; maxSize--; } } else { if (s.length() < size) { maxSize = size - (currentBytes - s.length()); for (int i = s.length(); i < size; i++) { buffer.append(' '); } } } } buffer.setLength(maxSize); return buffer.toString(); } catch(UnsupportedEncodingException e) { throw new RuntimeException("This error should never occurr", e); } }

Target:
public String getFieldString(int size, String s) { try { buffer.replace(0, size, emptyString); buffer.setLength(size); int maxSize = size; if (s != null) { buffer.replace(0, size, s); int currentBytes = s.substring(0, Math.min(size, s.length())) .getBytes(charset.name()).length; if (currentBytes > size) { char[] c = new char[1]; for (int index = size - 1; currentBytes > size; index--) { c[0] = buffer.charAt(index); String string = new String(c); buffer.deleteCharAt(index); currentBytes -= string.getBytes().length; maxSize--; } } else { if (s.length() < size) { maxSize = size - (currentBytes - s.length()); for (int i = s.length(); i < size; i++) { buffer.append(' '); } } } } buffer.setLength(maxSize); return buffer.toString(); } catch(UnsupportedEncodingException e) { throw new RuntimeException("This error should never occurr", e); } }
Source:
public void autoSelectResumeBehavior(VmBase vmBase, Version clusterVersion) { Version version = CompatibilityVersionUtils.getEffective(vmBase.getCustomCompatibilityVersion(), () -> clusterVersion); if (Version.v4_2.lessOrEquals(version)) { if (vmBase.isAutoStartup() && vmBase.getLeaseStorageDomainId() != null) { vmBase.setResumeBehavior(ResumeBehavior.KILL); } } }

Target:
public void autoSelectResumeBehavior(VmBase vmBase, Version clusterVersion) { Version version = CompatibilityVersionUtils.getEffective(vmBase.getCustomCompatibilityVersion(), () -> clusterVersion); if (FeatureSupported.isResumeBehaviorSupported(version)) { if (vmBase.isAutoStartup() && vmBase.getLeaseStorageDomainId() != null) { vmBase.setResumeBehavior(VmResumeBehavior.KILL); } else if (vmBase.getResumeBehavior() == null) { vmBase.setResumeBehavior(VmResumeBehavior.AUTO_RESUME); } } }
Source:
public void createVault() throws InterruptedException { server.enqueue(jsonResponse("/vaultcreate.json").setResponseCode(200)); final VaultApi vaultApi = api.getVaultApi(resourceGroup); Vault vault = vaultApi.createOrUpdateVault(vaultName, location, VaultProperties.builder() .tenantId(this.tenantId) .sku(SKU.create(location, "standard", null, "A")) .accessPolicies(ImmutableList.of(VaultProperties.AccessPolicyEntry.create(null, this.identityObjId, this.tenantId, VaultProperties.Permissions.create( ImmutableList.of( "Get", "List", "Update", "Create", "Import", "Delete", "ManageContacts", "ManageIssuers", "GetIssuers", "ListIssuers", "SetIssuers", "DeleteIssuers", "Purge", "Recover" ), ImmutableList.of( "Get", "List", "Update", "Create", "Import", "Delete", "Recover", "Backup", "Restore", "Purge" ), ImmutableList.of( "Get", "List", "Set", "Delete", "Recover", "Backup", "Restore", "Purge" ), ImmutableList.<String>of() )))) .build(), null); String path = String.format( "/subscriptions/%s/resourcegroups/%s/providers/Microsoft.KeyVault/vaults/%s?%s", subscriptionId, resourceGroup, vaultName, apiVersion ); assertSent(server, "PUT", path); assertNotNull(vault); assertNotNull(vault.properties().vaultUri()); assertTrue(!vault.name().isEmpty()); }

Target:
public void createVault() throws InterruptedException { server.enqueue(jsonResponse("/vaultcreate.json").setResponseCode(200)); final VaultApi vaultApi = api.getVaultApi(resourceGroup); Vault vault = vaultApi.createOrUpdateVault(vaultName, location, VaultProperties.builder() .tenantId(this.tenantId) .sku(SKU.create(location, "standard", null, "A")) .accessPolicies(ImmutableList.of(VaultProperties.AccessPolicyEntry.create(null, this.identityObjId, this.tenantId, VaultProperties.Permissions.create( ImmutableList.of( "Get", "List", "Update", "Create", "Import", "Delete", "ManageContacts", "ManageIssuers", "GetIssuers", "ListIssuers", "SetIssuers", "DeleteIssuers", "Purge", "Recover" ), ImmutableList.of( "Get", "List", "Update", "Create", "Import", "Delete", "Recover", "Backup", "Restore", "Purge", "Encrypt", "Decrypt", "Sign", "Verify", "WrapKey", "UnwrapKey" ), ImmutableList.of( "Get", "List", "Set", "Delete", "Recover", "Backup", "Restore", "Purge" ), ImmutableList.<String>of() )))) .build(), null); String path = String.format( "/subscriptions/%s/resourcegroups/%s/providers/Microsoft.KeyVault/vaults/%s?%s", subscriptionId, resourceGroup, vaultName, apiVersion ); assertSent(server, "PUT", path, stringFromResource("/vaultcreaterequestbody.json")); assertNotNull(vault); assertNotNull(vault.properties().vaultUri()); assertTrue(!vault.name().isEmpty()); }
Source:
public String[] getInfoForIdentifier(String identifier) { String name = Const.USER_NOBODY_TEXT; String teamName = Const.USER_NOBODY_TEXT; String sectionName = Const.DEFAULT_SECTION; boolean isStudent = this.getStudentForEmail(identifier) != null; boolean isInstructor = this.getInstructorForEmail(identifier) != null; boolean isTeam = this.getTeamToMembersTable().containsKey(identifier); if (isStudent) { StudentAttributes student = this.getStudentForEmail(identifier); name = student.getName(); teamName = student.getTeam(); sectionName = student.getSection(); } else if (isInstructor) { InstructorAttributes instructor = this.getInstructorForEmail(identifier); name = instructor.getName(); teamName = Const.USER_TEAM_FOR_INSTRUCTOR; sectionName = Const.DEFAULT_SECTION; } else if (isTeam) { StudentAttributes teamMember = this.getTeamToMembersTable().get(identifier).iterator().next(); name = identifier; teamName = identifier; sectionName = teamMember.getSection(); } return new String[] { name, teamName, sectionName }; }

Target:
public ParticipantInfo getInfoForIdentifier(String identifier) { String name = Const.USER_NOBODY_TEXT; String teamName = Const.USER_NOBODY_TEXT; String sectionName = Const.DEFAULT_SECTION; boolean isStudent = getStudentForEmail(identifier) != null; boolean isInstructor = getInstructorForEmail(identifier) != null; boolean isTeam = getTeamToMembersTable().containsKey(identifier); if (isStudent) { StudentAttributes student = getStudentForEmail(identifier); name = student.getName(); teamName = student.getTeam(); sectionName = student.getSection(); } else if (isInstructor) { InstructorAttributes instructor = getInstructorForEmail(identifier); name = instructor.getName(); teamName = Const.USER_TEAM_FOR_INSTRUCTOR; sectionName = Const.DEFAULT_SECTION; } else if (isTeam) { StudentAttributes teamMember = getTeamToMembersTable().get(identifier).iterator().next(); name = identifier; teamName = identifier; sectionName = teamMember.getSection(); } return new ParticipantInfo(name, teamName, sectionName); }
Source:
public String getData() { String data; if (webSocketMessage == null || webSocketMessage.payload == null) { data = ""; } else { try { data = webSocketMessage.getPayloadAsString(); isErrorMessage = false; } catch (InvalidUtf8Exception e) { isErrorMessage = true; if (webSocketMessage.opcode.equals(WebSocketMessage.OPCODE_BINARY)) { data = Constant.messages.getString("websocket.payload.unreadable_binary"); } else { data = Constant.messages.getString("websocket.payload.invalid_utf8"); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Unable to decode " + Arrays.toString((byte[]) webSocketMessage.payload) + " as UTF-8.", e); } } } } return data; }

Target:
public String getData() { String data; if (webSocketMessage == null || webSocketMessage.payload == null) { data = ""; }else if(editable){ try { data = webSocketMessage.getReadablePayload(); isErrorMessage = false; } catch (InvalidUtf8Exception e) { isErrorMessage = true; if (webSocketMessage.opcode.equals(WebSocketMessage.OPCODE_BINARY)) { data = Constant.messages.getString("websocket.payload.unreadable_binary"); } else { data = Constant.messages.getString("websocket.payload.invalid_utf8"); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Unable to decode " + Arrays.toString((byte[]) webSocketMessage.payload) + " as UTF-8.", e); } } } }else { data = webSocketMessage.getPayloadAsString(); } return data; }
Source:
private boolean copyFile(URI srcUri, URI dstUri) throws IOException { try { String encodedUrl = null; try { encodedUrl = URLEncoder.encode(srcUri.getHost() + srcUri.getPath(), StandardCharsets.UTF_8.toString()); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } String dstPath = sanitizePath(dstUri.getPath()); CopyObjectRequest.Builder copyReqBuilder = CopyObjectRequest.builder().copySource(encodedUrl) .destinationBucket(dstUri.getHost()).destinationKey(dstPath); CopyObjectRequest copyReq; if (!disableAcl) { copyReq = copyReqBuilder.acl(ObjectCannedACL.BUCKET_OWNER_FULL_CONTROL).build(); } else { copyReq = copyReqBuilder.build(); } CopyObjectResponse copyObjectResponse = _s3Client.copyObject(copyReq); return copyObjectResponse.sdkHttpResponse().isSuccessful(); } catch (S3Exception e) { throw new IOException(e); } }

Target:
private boolean copyFile(URI srcUri, URI dstUri) throws IOException { try { String encodedUrl = null; try { encodedUrl = URLEncoder.encode(srcUri.getHost() + srcUri.getPath(), StandardCharsets.UTF_8.toString()); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } String dstPath = sanitizePath(dstUri.getPath()); CopyObjectRequest.Builder copyReqBuilder = CopyObjectRequest.builder().copySource(encodedUrl) .destinationBucket(dstUri.getHost()).destinationKey(dstPath); if (!disableAcl) { copyReqBuilder.acl(ObjectCannedACL.BUCKET_OWNER_FULL_CONTROL); } CopyObjectRequest copyReq = copyReqBuilder.build(); CopyObjectResponse copyObjectResponse = _s3Client.copyObject(copyReq); return copyObjectResponse.sdkHttpResponse().isSuccessful(); } catch (S3Exception e) { throw new IOException(e); } }
Source:
public List<Object> merge(List<?>... items) { if (ArrayUtils.isEmpty(items)) { return new ArrayList<Object>(); } List<Object> result = new ArrayList<Object>(); for (List<?> item : items) { if (item != null) { result.addAll(item); } } return result; }

Target:
public List<Object> merge(List<?>... items) { if (ArrayUtils.isEmpty(items)) { return Collections.emptyList(); } List<Object> result = new ArrayList<Object>(); for (List<?> item : items) { if (item != null) { result.addAll(item); } } return result; }
Source:
private static void setValueProperty(String entryId, String subKey, Object value) throws Exception { ConcurrentHashMap<String, Object> entryMap = entryIdToKalturaLiveEntryMap.get(entryId); entryMap.put(subKey, value); entryMap.put(Constants.KALTURA_ENTRY_START_TIME, System.currentTimeMillis()); logger.debug("(" + entryId + ") Successfully updated entry. Sub key \"" + subKey + "\" (map size:" + entryIdToKalturaLiveEntryMap.size() + ")"); }

Target:
private static void setValueProperty(String entryId, String subKey, Object value) throws Exception { ConcurrentHashMap<String, Object> entryMap = entryIdToKalturaLiveEntryMap.get(entryId); entryMap.put(subKey, value); long time = System.currentTimeMillis(); entryMap.put(Constants.KALTURA_ENTRY_VALIDATED_TIME, time); logger.debug("(" + entryId + ") Successfully updated entry ; Sub key \"" + subKey + "\" ; Time: (" + time + ")"); }
Source:
public void handle(Context context) throws Exception { if (!name.equals(DEFAULT_NAME_TOKEN)) { handleByName(context, name); } else { handleAll(context); } }

Target:
public void handle(Context context) throws Exception { if (name != null && !"".equals(name)) { handleByName(context, name); } else { handleAll(context); } }
Source:
private static ContinuousStream<Map<String, Object>> cepStatelessRulesTranslator( final ContinuousStream<Map<String, Object>> inputMap, final List<CepStatelessRule> cepStatelessRules) { final int ruleNum = cepStatelessRules.size(); for (int i = 0; i < ruleNum; i++) { final CepStatelessRule rule = cepStatelessRules.get(i); final CepAction action = rule.getAction(); final CepSink sink = action.getCepSink(); ContinuousStream<Map<String, Object>> temp = inputMap; switch (action.getCepActionType()) { case TEXT_WRITE: { switch (sink.getCepSinkType()) { case TEXT_SOCKET_OUTPUT: { temp = cepConditionTranslator(temp, rule.getCondition()); final List<Object> params = action.getParams(); final String separator = sink.getSeparator(); temp.map(new CepMapToStringFunction(params, separator)) .textSocketOutput((String)sink.getSinkConfigs().get("SOCKET_SINK_ADDRESS"), (int)sink.getSinkConfigs().get("SOCKET_SINK_PORT")); break; } case MQTT_OUTPUT: { temp = cepConditionTranslator(temp, rule.getCondition()); final List<Object> params = action.getParams(); final String separator = sink.getSeparator(); temp.map(new CepMapToStringFunction(params, separator)) .map(value -> new MqttMessage(value.getBytes())) .mqttOutput((String) sink.getSinkConfigs().get("MQTT_SINK_BROKER_URI"), (String) sink.getSinkConfigs().get("MQTT_SINK_TOPIC")); break; } default: throw new IllegalStateException("Wrong sink type!"); } break; } default: continue; } } return inputMap; }

Target:
private static ContinuousStream<Map<String, Object>> cepStatelessRulesTranslator( final ContinuousStream<Map<String, Object>> inputMap, final List<CepStatelessRule> cepStatelessRules) { final int ruleNum = cepStatelessRules.size(); for (int i = 0; i < ruleNum; i++) { final CepStatelessRule rule = cepStatelessRules.get(i); final CepAction action = rule.getAction(); final CepSink sink = action.getCepSink(); ContinuousStream<Map<String, Object>> temp = inputMap; switch (action.getCepActionType()) { case TEXT_WRITE: { switch (sink.getCepSinkType()) { case TEXT_SOCKET_OUTPUT: { temp = cepConditionTranslator(temp, rule.getCondition()); final List<Object> params = action.getParams(); final String separator = sink.getSeparator(); temp.map(new CepMapToStringFunction(params, separator)) .textSocketOutput((String)sink.getSinkConfigs().get("SOCKET_SINK_ADDRESS"), (int)sink.getSinkConfigs().get("SOCKET_SINK_PORT")); break; } case MQTT_OUTPUT: { temp = cepConditionTranslator(temp, rule.getCondition()); final List<Object> params = action.getParams(); final String separator = sink.getSeparator(); temp.map(new CepMapToStringFunction(params, separator)) .map(value -> new MqttMessage(value.getBytes())) .mqttOutput((String) sink.getSinkConfigs().get("MQTT_SINK_BROKER_URI"), (String) sink.getSinkConfigs().get("MQTT_SINK_TOPIC")); break; } default: throw new IllegalStateException("TEXT_SOCKET_OUTPUT, MQTT_OUTPUT are available!"); } break; } default: continue; } } return inputMap; }
Source:
void onCanvasElementUpdated(final @Observes CanvasElementUpdatedEvent event) { final Element<?> element = event.getElement(); if ((element instanceof Node)) { final Node node = (Node) element; if (node.getContent() instanceof Definition) { final Definition definition = (Definition) node.getContent(); hasExpression.ifPresent(e -> { if (e.equals(definition.getDefinition())) { view.setReturnToDRGText(Optional.ofNullable((HasName) definition.getDefinition())); } }); } } }

Target:
void onCanvasElementUpdated(final @Observes CanvasElementUpdatedEvent event) { final Element<?> element = event.getElement(); if ((element instanceof Node)) { if (element.getContent() instanceof Definition) { final Definition definition = (Definition) element.getContent(); hasExpression.ifPresent(e -> { if (Objects.equals(e, definition.getDefinition())) { view.setReturnToDRGText(Optional.ofNullable((HasName) definition.getDefinition())); } }); } } }
Source:
public void testPipelineCompatibility() throws Exception { WorkflowJob p = rule.jenkins.createProject(WorkflowJob.class, "p"); p.setDefinition(new CpsFlowDefinition( "node {\n" + " catchError {error 'oops'}\n" + " step([$class: 'Mailer', recipients: '" + RECIPIENT + "'])\n" + "}", true)); Mailbox inbox = getMailbox(RECIPIENT); inbox.clear(); WorkflowRun b = rule.assertBuildStatus(Result.FAILURE, p.scheduleBuild2(0).get()); assertEquals(1, inbox.size()); assertEquals("Build failed in Jenkins: " + b.getFullDisplayName(), inbox.get(0).getSubject()); assertThat(rule.getLog(b), containsString("Sending e-mails to")); }

Target:
public void testPipelineCompatibility() throws Exception { WorkflowJob p = rule.jenkins.createProject(WorkflowJob.class, "p"); p.setDefinition(new CpsFlowDefinition( "node {\n" + " catchError {error 'oops'}\n" + " step([$class: 'Mailer', recipients: '" + RECIPIENT + "'])\n" + "}", true)); Mailbox inbox = getMailbox(RECIPIENT); inbox.clear(); WorkflowRun b = rule.assertBuildStatus(Result.FAILURE, p.scheduleBuild2(0).get()); assertThat("One email should have been sent", inbox, hasSize(1)); assertEquals("Build failed in Jenkins: " + b.getFullDisplayName(), inbox.get(0).getSubject()); assertThat(rule.getLog(b), containsString("Sending e-mails to")); }
Source:
public Map<String, String> get(@PathParam("location") Integer locationId) { return asMap(locationId, store.get(locationId)); }

Target:
public LocationSummary get(@PathParam("location") Integer locationId) { return new LocationSummary(locationId.toString(), store.get(locationId)); }
Source:
public int hashCode() { int result = storageDomainId != null ? storageDomainId.hashCode() : 0; result = 31 * result + (imageGroupId != null ? imageGroupId.hashCode() : 0); result = 31 * result + (baseImageId != null ? baseImageId.hashCode() : 0); result = 31 * result + (topImageId != null ? topImageId.hashCode() : 0); result = 31 * result + (baseImageGeneration != null ? baseImageGeneration.hashCode() : 0); result = 31 * result + (baseImage != null ? baseImage.hashCode() : 0); result = 31 * result + (topImage != null ? topImage.hashCode() : 0); return result; }

Target:
public int hashCode() { return Objects.hash(storageDomainId, imageGroupId, baseImageId, topImageId, baseImageGeneration, baseImage, topImage); }
Source:
private <T extends Serializable> void sendMessageToAllRegionsSync(final T body) throws IOException { if ( sns == null ) { logger.error( "SNS client is null, perhaps it failed to initialize successfully" ); return; } final String stringBody = toString( body ); String topicArn = getWriteTopicArn(); if ( logger.isTraceEnabled() ) { logger.trace( "Publishing Message...{} to arn: {}", stringBody, topicArn ); } try { PublishResult publishResult = sns.publish(topicArn, toString(body)); if ( logger.isTraceEnabled() ) { logger.trace( "Successfully published... messageID=[{}], arn=[{}]", publishResult.getMessageId(), topicArn ); } } catch (Exception e) { if (logger.isErrorEnabled()) { logger.error("Failed to send this message to SNS queue at {}", stringBody, topicArn); } sendMessageToAllRegionsAsync(body); } }

Target:
private <T extends Serializable> void sendMessageToAllRegionsSync(final T body) throws IOException { if ( sns == null ) { logger.error( "SNS client is null, perhaps it failed to initialize successfully" ); return; } final String stringBody = toString( body ); String topicArn = getWriteTopicArn(); if ( logger.isTraceEnabled() ) { logger.trace( "Publishing Message...{} to arn: {}", stringBody, topicArn ); } try { PublishResult publishResult = sns.publish(topicArn, toString(body)); if ( logger.isTraceEnabled() ) { logger.trace( "Successfully published... messageID=[{}], arn=[{}]", publishResult.getMessageId(), topicArn ); } } catch (Exception e) { if (logger.isErrorEnabled()) { logger.error(FAILED_TO_SEND_MESSAGE, stringBody, topicArn, e); } sendMessageToAllRegionsAsync(body); } }
Source:
private void handleVdsLiveSnapshotFailure(VdcBLLException e) { log.warnFormat("Wasn't able to live snpashot due to error: {0}. VM will still be configured to the new created snapshot", ExceptionUtils.getMessage(e)); AuditLogableBase logable = new AuditLogableBase(); logable.AddCustomValue("SnapshotName", getSnapshotName()); logable.AddCustomValue("VmName", getVmName()); AuditLogDirector.log(logable, AuditLogType.USER_CREATE_LIVE_SNAPSHOT_FINISHED_FAILURE); }

Target:
private void handleVdsLiveSnapshotFailure(VdcBLLException e) { log.warnFormat("Wasn't able to live snpashot due to error: {0}. VM will still be configured to the new created snapshot", ExceptionUtils.getMessage(e)); AddCustomValue("SnapshotName", getSnapshotName()); AddCustomValue("VmName", getVmName()); AuditLogDirector.log(this, AuditLogType.USER_CREATE_LIVE_SNAPSHOT_FINISHED_FAILURE); }
Source:
protected Marshaller getMarshaller() { Marshaller marshaller = null; try { JAXBContextHandler oHandler = new JAXBContextHandler(); JAXBContext jc = oHandler.getJAXBContext(CORE_X12AuditDataTransformConstants.CORE_X12_JAXB_CONTEXT); marshaller = jc.createMarshaller(); return marshaller; } catch (JAXBException ex) { LOG.error("JAXB Marshall error : " + ex.getMessage(), ex); } return marshaller; }

Target:
protected Marshaller getMarshaller() { Marshaller marshaller = null; try { JAXBContextHandler oHandler = new JAXBContextHandler(); JAXBContext jc = oHandler.getJAXBContext(CORE_X12AuditDataTransformConstants.CORE_X12_JAXB_CONTEXT); marshaller = jc.createMarshaller(); } catch (JAXBException ex) { LOG.error("JAXB Marshall error : " + ex.getMessage(), ex); } return marshaller; }
Source:
private <T> RPCResponse<T> invoke(String name, String path, Class<T> resultType) throws FreeIpaClientException { Invocation.Builder builder = rpcTarget.path(path) .request() .headers(headers); try (Response response = builder.get()) { if (!response.bufferEntity()) { throw new FreeIpaClientException("Unable to buffer the response from FreeIPA"); } if (listener != null) { listener.onBeforeResponseProcessed(response); } if (response.getStatusInfo().getFamily() != Response.Status.Family.SUCCESSFUL && response.getStatus() != Response.Status.SERVICE_UNAVAILABLE.getStatusCode()) { String message = String.format("Invoke FreeIpa health check failed: %d", response.getStatus()); throw new FreeIpaClientException(message, response.getStatus()); } return toRpcResponse(name, response, resultType); } catch (FreeIpaClientException e) { throw e; } catch (Throwable throwable) { String message = String.format("Invoke FreeIpa health check failed: %s", throwable.getLocalizedMessage()); LOGGER.warn(message); throw new FreeIpaClientException(message, throwable); } }

Target:
private <T> RPCResponse<T> invoke(String name, String path, Class<T> resultType) throws FreeIpaClientException { Invocation.Builder builder = rpcTarget.path(path) .request() .headers(headers); try (Response response = builder.get()) { bufferResponseEntity(response); processRpcListener(response); checkResponseStatus(response); return toRpcResponse(name, response, resultType); } catch (FreeIpaClientException e) { throw e; } catch (Throwable throwable) { String message = String.format("Invoke FreeIPA health check failed: %s", throwable.getLocalizedMessage()); LOGGER.warn(message); throw new FreeIpaClientException(message, throwable); } }
Source:
protected SecondaryToolbar createSecondaryToolbar() { replaceToolbar_ = new SecondaryToolbar("Replace"); replaceMode_ = true; replaceLabel_ = new Label("Replace with: "); replaceToolbar_.addLeftWidget(replaceLabel_); replaceTextBox_ = new TextBox(); replaceToolbar_.addLeftWidget(replaceTextBox_); replaceTextBox_.addKeyUpHandler(new KeyUpHandler() { public void onKeyUp(KeyUpEvent event) { displayPreview_.nudge(); } }); useGitIgnore_ = new CheckBox(); useGitIgnoreLabel_ = new CheckboxLabel(useGitIgnore_, "Use .gitignore").getLabel(); useGitIgnore_.getElement().getStyle().setMarginRight(0, Unit.PX); replaceToolbar_.addLeftWidget(useGitIgnore_); useGitIgnoreLabel_.getElement().getStyle().setMarginRight(9, Unit.PX); replaceToolbar_.addLeftWidget(useGitIgnoreLabel_); useGitIgnore_.setVisible(false); useGitIgnoreLabel_.setVisible(false); stopReplace_ = new ToolbarButton( ToolbarButton.NoText, "Stop replace", commands_.interruptR().getImageResource()); stopReplace_.setVisible(false); replaceToolbar_.addRightWidget(stopReplace_); replaceAllButton_ = new ToolbarButton("Replace All", "Replace All", null); replaceToolbar_.addRightWidget(replaceAllButton_); replaceProgress_ = new ProgressBar(); replaceProgress_.setHeight("10px"); replaceProgress_.setWidth("195px"); replaceProgress_.setVisible(false); replaceToolbar_.addLeftWidget(replaceProgress_); return replaceToolbar_; }

Target:
protected SecondaryToolbar createSecondaryToolbar() { replaceToolbar_ = new SecondaryToolbar("Replace"); replaceMode_ = true; replaceTextBox_ = new TextBox(); replaceTextBox_.addKeyUpHandler(new KeyUpHandler() { public void onKeyUp(KeyUpEvent event) { displayPreview_.nudge(); } }); replaceLabel_ = new FormLabel("Replace with: ", replaceTextBox_); replaceToolbar_.addLeftWidget(replaceLabel_); replaceToolbar_.addLeftWidget(replaceTextBox_); useGitIgnore_ = new CheckBox(); useGitIgnoreLabel_ = new CheckboxLabel(useGitIgnore_, "Use .gitignore").getLabel(); useGitIgnore_.getElement().getStyle().setMarginRight(0, Unit.PX); replaceToolbar_.addLeftWidget(useGitIgnore_); useGitIgnoreLabel_.getElement().getStyle().setMarginRight(9, Unit.PX); replaceToolbar_.addLeftWidget(useGitIgnoreLabel_); useGitIgnore_.setVisible(false); useGitIgnoreLabel_.setVisible(false); stopReplace_ = new ToolbarButton( ToolbarButton.NoText, "Stop replace", commands_.interruptR().getImageResource()); stopReplace_.setVisible(false); replaceToolbar_.addRightWidget(stopReplace_); replaceAllButton_ = new ToolbarButton("Replace All", "Replace All", null); replaceToolbar_.addRightWidget(replaceAllButton_); replaceProgress_ = new ProgressBar(); replaceProgress_.setHeight("10px"); replaceProgress_.setWidth("195px"); replaceProgress_.setVisible(false); replaceToolbar_.addLeftWidget(replaceProgress_); return replaceToolbar_; }
Source:
private static Object getValueByName(Class<? extends Enum<?>> enumClass, String name) { final Enum<?>[] enumConstants = enumClass.getEnumConstants(); return JdbiOptionals.findFirstPresent( () -> Arrays.stream(enumConstants).filter(e -> { final Field field; try { field = enumClass.getField(e.name()); } catch (final NoSuchFieldException ex) { throw new RuntimeException(ex); } final DatabaseValue databaseValue = field.getAnnotation(DatabaseValue.class); return databaseValue != null && databaseValue.value().equals(name); }).findFirst(), () -> Arrays.stream(enumConstants).filter(e -> e.name().equals(name)).findFirst(), () -> Arrays.stream(enumConstants).filter(e -> e.name().equalsIgnoreCase(name)).findFirst() ) .orElseThrow(() -> new UnableToProduceResultException( String.format("no %s value could be matched to the name %s", enumClass.getSimpleName(), name))); }

Target:
private static Object getValueByName(Class<? extends Enum<?>> enumClass, String name) { final Enum<?>[] enumConstants = enumClass.getEnumConstants(); return JdbiOptionals.findFirstPresent( () -> Arrays.stream(enumConstants).filter(e -> { final Field field = Unchecked.function(enumClass::getField).apply(e.name()); final DatabaseValue databaseValue = field.getAnnotation(DatabaseValue.class); return databaseValue != null && databaseValue.value().equals(name); }).findFirst(), () -> Arrays.stream(enumConstants).filter(e -> e.name().equals(name)).findFirst(), () -> Arrays.stream(enumConstants).filter(e -> e.name().equalsIgnoreCase(name)).findFirst() ) .orElseThrow(() -> new UnableToProduceResultException( String.format("no %s value could be matched to the name %s", enumClass.getSimpleName(), name))); }
Source:
private static Field[] getExportedPropertyFields(Class<?> klass) { if (sFieldsForClasses == null) { sFieldsForClasses = new HashMap<Class<?>, Field[]>(); } if (sAnnotations == null) { sAnnotations = new HashMap<AccessibleObject, ExportedProperty>(512); } final HashMap<Class<?>, Field[]> map = sFieldsForClasses; Field[] fields = map.get(klass); if (fields != null) { return fields; } try { final Field[] declaredFields = klass.getDeclaredFieldsUnchecked(false); final ArrayList<Field> foundFields = new ArrayList<Field>(); for (final Field field : declaredFields) { if (field.isAnnotationPresent(ExportedProperty.class)) { field.setAccessible(true); foundFields.add(field); sAnnotations.put(field, field.getAnnotation(ExportedProperty.class)); } } fields = foundFields.toArray(new Field[foundFields.size()]); map.put(klass, fields); } catch (NoClassDefFoundError e) { throw new AssertionError(e); } return fields; }

Target:
private static Field[] getExportedPropertyFields(Class<?> klass) { if (sFieldsForClasses == null) { sFieldsForClasses = new HashMap<Class<?>, Field[]>(); } if (sAnnotations == null) { sAnnotations = new HashMap<AccessibleObject, ExportedProperty>(512); } final HashMap<Class<?>, Field[]> map = sFieldsForClasses; Field[] fields = map.get(klass); if (fields != null) { return fields; } try { final Field[] declaredFields = klass.getDeclaredFieldsUnchecked(false); final ArrayList<Field> foundFields = new ArrayList<Field>(); for (final Field field : declaredFields) { if (field.getType() != null && field.isAnnotationPresent(ExportedProperty.class)) { field.setAccessible(true); foundFields.add(field); sAnnotations.put(field, field.getAnnotation(ExportedProperty.class)); } } fields = foundFields.toArray(new Field[foundFields.size()]); map.put(klass, fields); } catch (NoClassDefFoundError e) { throw new AssertionError(e); } return fields; }
Source:
public void addDefaultRoute() { if ((mInterfaceName != null) && (mDefaultGatewayAddr != 0) && mDefaultRouteSet == false) { if (DBG) { Log.d(TAG, "addDefaultRoute for " + mNetworkInfo.getTypeName() + " (" + mInterfaceName + "), GatewayAddr=" + mDefaultGatewayAddr); } InetAddress inetAddress = NetworkUtils.intToInetAddress(mDefaultGatewayAddr); if (inetAddress == null) { if (DBG) Log.d(TAG, " Unable to add default route. mDefaultGatewayAddr Error"); } else { if (NetworkUtils.addDefaultRoute(mInterfaceName, inetAddress, 0)) { mDefaultRouteSet = true; } else { if (DBG) Log.d(TAG, " Unable to add default route."); } } } }

Target:
public void addDefaultRoute() { if ((mInterfaceName != null) && (mDefaultGatewayAddr != 0) && mDefaultRouteSet == false) { if (DBG) { Log.d(TAG, "addDefaultRoute for " + mNetworkInfo.getTypeName() + " (" + mInterfaceName + "), GatewayAddr=" + mDefaultGatewayAddr); } InetAddress inetAddress = NetworkUtils.intToInetAddress(mDefaultGatewayAddr); if (inetAddress == null) { if (DBG) Log.d(TAG, " Unable to add default route. mDefaultGatewayAddr Error"); } else { if (NetworkUtils.addDefaultRoute(mInterfaceName, inetAddress)) { mDefaultRouteSet = true; } else { if (DBG) Log.d(TAG, " Unable to add default route."); } } } }
Source:
public void testCountTotalNumberOfVariants() { assertFalse(service.countTotalNumberOfVariants() < 0); }

Target:
public void testCountTotalNumberOfVariants() { assertEquals(498, service.countTotalNumberOfVariants()); }
Source:
private void determineMessageFormat(){ if (!StringUtils.isEmpty(templatePath)) { messageFormat = MessageFormat.CUSTOM; } else if (messageFormat == null || messageFormat.equals("")) { messageFormat = MessageFormat.NONE; } log.info("Message format: {}", messageFormat); }

Target:
private MessageFormat determineMessageFormat(){ if (!StringUtils.isEmpty(templatePath)) { return MessageFormat.CUSTOM; } else if (messageFormat == null || messageFormat.equals("")) { return MessageFormat.NONE; } return messageFormat; }
Source:
public void merge(SegmentStoreStatistics other) { long min = fMin.getLength(); long max = fMax.getLength(); fMin = min <= other.getMin() ? fMin : other.getMinSegment(); fMax = max >= other.getMax() ? fMax : other.getMaxSegment(); long weight = fNbSegments; double oldAverage = fAverage; fNbSegments += other.getNbSegments(); fTotal += other.getTotal(); fAverage = ((weight * oldAverage) + (other.getAverage() * other.getNbSegments())) / fTotal; double avgTemp1 = oldAverage - fAverage; double avgTemp2 = other.getAverage() - fAverage; fVariance = ((fVariance + avgTemp1 * avgTemp1) * weight + (other.fVariance + avgTemp2 * avgTemp1) * other.getNbSegments()) / fTotal; }

Target:
public void merge(SegmentStoreStatistics other) { if (other.fNbSegments == 0) { return; } else if (fNbSegments == 0) { copy(other); } else if (other.fNbSegments == 1) { update(other.fMax); } else if (fNbSegments == 1) { SegmentStoreStatistics copyOther = new SegmentStoreStatistics(); copyOther.copy(other); copyOther.update(fMax); copy(copyOther); } else { internalMerge(other); } }
Source:
public void encode(StringBuilder builder) { String xacmlVersionId = metaData.getXACMLIdentifier(); String version = getVersion(); builder.append("<PolicySet xmlns=\"" + xacmlVersionId + "\"" + " PolicySetId=\"" + getId() + "\"" + " Version=\"" + version + ""). append("\" PolicyCombiningAlgId=\"").append(getCombiningAlg().getIdentifier().toString()).append("\">\n"); String description = getDescription(); if (description != null){ builder.append("<Description>").append(description).append("</Description>\n"); } String xPathVersion = metaData.getXPathIdentifier(); if (xPathVersion != null){ builder.append("<PolicySetDefaults><XPathVersion>"). append(xPathVersion).append("</XPathVersion></PolicySetDefaults>\n"); } getTarget().encode(builder); encodeCommonElements(builder); builder.append("</PolicySet>\n"); }

Target:
public void encode(StringBuilder builder) { String xacmlVersionId = metaData.getXACMLIdentifier(); String version = getVersion(); builder.append("<PolicySet xmlns=\"").append(xacmlVersionId).append("\" PolicySetId=\""). append(getId().toString()).append("\" PolicyCombiningAlgId=\""). append(getCombiningAlg().getIdentifier().toString()).append("\">\n"); String description = getDescription(); if (description != null){ builder.append("<Description>").append(description).append("</Description>\n"); } String xPathVersion = metaData.getXPathIdentifier(); if (xPathVersion != null){ builder.append("<PolicySetDefaults><XPathVersion>"). append(xPathVersion).append("</XPathVersion></PolicySetDefaults>\n"); } getTarget().encode(builder); encodeCommonElements(builder); builder.append("</PolicySet>\n"); }
Source:
public void differentialRnaSeqExperimentEvidence(@RequestParam(defaultValue = "0") double logFoldChangeCutoff, @RequestParam(defaultValue = "1") double pValueCutoff, @RequestParam(defaultValue = "-1") int maxGenesPerContrast, @PathVariable String experimentAccession, @RequestParam(defaultValue = "") String accessKey, HttpServletResponse response) throws IOException { DifferentialExperiment experiment = (DifferentialExperiment) experimentTrader.getExperiment(experimentAccession, accessKey); response.setHeader("content-type", "application/json-seq; charset=UTF-8"); response.setCharacterEncoding("UTF-8"); PrintWriter w = response.getWriter(); diffRnaSeqEvidenceService.evidenceForExperiment( experiment, contrast -> { DifferentialRequestPreferences requestPreferences = new DifferentialRequestPreferences(); requestPreferences.setFoldChangeCutoff(logFoldChangeCutoff); requestPreferences.setCutoff(pValueCutoff); requestPreferences.setHeatmapMatrixSize(maxGenesPerContrast); requestPreferences.setSelectedColumnIds(ImmutableSet.of(contrast.getId())); return new RnaSeqRequestContext(requestPreferences, experiment); }, o -> w.println(GSON.toJson(o))); }

Target:
public void differentialRnaSeqExperimentEvidence(@RequestParam(defaultValue = "0") double logFoldChangeCutoff, @RequestParam(defaultValue = "1") double pValueCutoff, @RequestParam(defaultValue = "-1") int maxGenesPerContrast, @PathVariable String experimentAccession, @RequestParam(defaultValue = "") String accessKey, HttpServletResponse response) throws IOException { DifferentialExperiment experiment = (DifferentialExperiment) experimentTrader.getExperiment(experimentAccession, accessKey); response.setHeader("content-type", "application/json-seq; charset=UTF-8"); PrintWriter w = response.getWriter(); diffRnaSeqEvidenceService.evidenceForExperiment( experiment, contrast -> { DifferentialRequestPreferences requestPreferences = new DifferentialRequestPreferences(); requestPreferences.setFoldChangeCutoff(logFoldChangeCutoff); requestPreferences.setCutoff(pValueCutoff); requestPreferences.setHeatmapMatrixSize(maxGenesPerContrast); requestPreferences.setSelectedColumnIds(ImmutableSet.of(contrast.getId())); return new RnaSeqRequestContext(requestPreferences, experiment); }, o -> w.println(GSON.toJson(o))); }
Source:
public TrustingSslSocketFactory() { super(); try { sslContext.init(null, new TrustManager[] { TRUST_ALL }, null); } catch (Exception e) { throw Throwables.propagate(e); } }

Target:
protected TrustingSslSocketFactory() { super(); try { sslContext.init(null, new TrustManager[] { TRUST_ALL }, null); } catch (Exception e) { throw Throwables.propagate(e); } }
Source:
public void testInitializeTwiceFails() throws FluoAdmin.AlreadyInitializedException { FluoAdmin fluoAdmin = new FluoAdminImpl(config); config.setClearZookeeper(true); fluoAdmin.initialize(); fluoAdmin.initialize(); config.setClearZookeeper(false); try { fluoAdmin.initialize(); fail("This should have failed"); } catch(FluoAdmin.AlreadyInitializedException e) { } }

Target:
public void testInitializeTwiceFails() throws FluoAdmin.AlreadyInitializedException { FluoAdmin fluoAdmin = new FluoAdminImpl(config); config.setAllowReinitialize(true); fluoAdmin.initialize(); fluoAdmin.initialize(); config.setAllowReinitialize(false); try { fluoAdmin.initialize(); fail("This should have failed"); } catch(FluoAdmin.AlreadyInitializedException e) { } assertTrue(conn.tableOperations().exists(config.getAccumuloTable())); }
Source:
public Map<String, Object> from(final Object identifier, final Saga saga) { checkNotNull(saga); final Map<String, Object> properties = Maps.newHashMap(); properties.put(X_KASPER_SAGA_CLASS, saga.getClass()); properties.put(X_KASPER_SAGA_IDENTIFIER, identifier); for (final Field field : saga.getClass().getDeclaredFields()) { field.setAccessible(Boolean.TRUE); if ( ! field.getName().startsWith("$") && (Serializable.class.isAssignableFrom(field.getType()) || field.getType().isPrimitive())) { Object value = null; try { value = field.get(saga); } catch (final IllegalAccessException e) { e.printStackTrace(); } if (null != value) { properties.put(field.getName(), value); } } } return properties; }

Target:
public Map<String, Object> from(final Object identifier, final Saga saga) { checkNotNull(saga); final Map<String, Object> properties = Maps.newHashMap(); properties.put(X_KASPER_SAGA_CLASS, saga.getClass()); properties.put(X_KASPER_SAGA_IDENTIFIER, identifier); for (final Field field : saga.getClass().getDeclaredFields()) { field.setAccessible(Boolean.TRUE); if ( ! field.getName().startsWith("$") && (Serializable.class.isAssignableFrom(field.getType()) || field.getType().isPrimitive())) { Object value = null; try { value = field.get(saga); } catch (final IllegalAccessException e) { LOGGER.error("Failed to extract property '{}' from a saga, <saga={}> <identifier={}>", field.getName(), saga.getClass(), identifier, e); } if (null != value) { properties.put(field.getName(), value); } } } return properties; }
Source:
public String getIdLabel() { Instance instance = getInstance(); if (instance == null) { return ""; } return String.format("%s (0x%x)", ValueDescriptorImpl.getIdLabel(myObjectReference), getInstance().getUniqueId()); }

Target:
public String getIdLabel() { Instance instance = getInstance(); if (instance == null) { return ""; } return String.format("%s (0x%x)", ValueDescriptorImpl.getIdLabel(myObjectReference), instance.getUniqueId()); }
Source:
getQuestionResponseMapByRecipientTeam() { LinkedHashMap<String, Map<FeedbackQuestionAttributes, List<FeedbackResponseAttributes>>> sortedMap = new LinkedHashMap<String, Map<FeedbackQuestionAttributes, List<FeedbackResponseAttributes>>>(); Collections.sort(responses, compareByTeamQuestionRecipientTeamGiver); for (FeedbackResponseAttributes response : responses) { String recipientTeam = getTeamNameForEmail(response.recipientEmail); if (recipientTeam == "") { recipientTeam = getNameForEmail(response.recipientEmail); } if (!sortedMap.containsKey(recipientTeam)) { sortedMap.put(recipientTeam, new LinkedHashMap<FeedbackQuestionAttributes, List<FeedbackResponseAttributes>>()); } Map<FeedbackQuestionAttributes, List<FeedbackResponseAttributes>> responsesForOneRecipient = sortedMap.get(recipientTeam); FeedbackQuestionAttributes question = questions.get(response.feedbackQuestionId); if (!responsesForOneRecipient.containsKey(question)) { responsesForOneRecipient.put(question, new ArrayList<FeedbackResponseAttributes>()); } List<FeedbackResponseAttributes> responsesForOneRecipientOneQuestion = responsesForOneRecipient.get(question); responsesForOneRecipientOneQuestion.add(response); } return sortedMap; }

Target:
getQuestionResponseMapByRecipientTeam() { LinkedHashMap<String, Map<FeedbackQuestionAttributes, List<FeedbackResponseAttributes>>> sortedMap = new LinkedHashMap<String, Map<FeedbackQuestionAttributes, List<FeedbackResponseAttributes>>>(); Collections.sort(responses, compareByTeamQuestionRecipientTeamGiver); for (FeedbackResponseAttributes response : responses) { String recipientTeam = getTeamNameForEmail(response.recipientEmail); if (recipientTeam.isEmpty()) { recipientTeam = getNameForEmail(response.recipientEmail); } if (!sortedMap.containsKey(recipientTeam)) { sortedMap.put(recipientTeam, new LinkedHashMap<FeedbackQuestionAttributes, List<FeedbackResponseAttributes>>()); } Map<FeedbackQuestionAttributes, List<FeedbackResponseAttributes>> responsesForOneRecipient = sortedMap.get(recipientTeam); FeedbackQuestionAttributes question = questions.get(response.feedbackQuestionId); if (!responsesForOneRecipient.containsKey(question)) { responsesForOneRecipient.put(question, new ArrayList<FeedbackResponseAttributes>()); } List<FeedbackResponseAttributes> responsesForOneRecipientOneQuestion = responsesForOneRecipient.get(question); responsesForOneRecipientOneQuestion.add(response); } return sortedMap; }