auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void checkConstructorWithDetailMessageAndThrowable() { Throwable testThrowable = new RuntimeException("yo"); StorIOException storIOException = new StorIOException("test detail message", testThrowable); assertThat(storIOException).hasMessage("test detail message"); assertThat(storIOException.getCause()).isEqualTo(testThrowable); }

Target:
public void checkConstructorWithDetailMessageAndThrowable() { Throwable testThrowable = new RuntimeException("yo"); StorIOException storIOException = new StorIOException("test detail message", testThrowable); assertThat(storIOException).hasMessage("test detail message"); assertThat(storIOException.getCause()).isSameAs(testThrowable); }
Source:
public static synchronized void cleanDirectBuffer(ByteBuffer buffer) { Preconditions.checkNotNull(buffer, "buffer is null"); Preconditions.checkArgument(buffer.isDirect(), "buffer isn't a DirectByteBuffer"); int javaVersion = Integer.parseInt(System.getProperty("java.version").split("\\D+")[0]); if (javaVersion < 9) { cleanDirectBufferJava8(buffer); } else { cleanDirectBufferJava11(buffer); } }

Target:
public static synchronized void cleanDirectBuffer(ByteBuffer buffer) { Preconditions.checkNotNull(buffer, "buffer is null"); Preconditions.checkArgument(buffer.isDirect(), "buffer isn't a DirectByteBuffer"); int javaVersion = CommonUtils.getJavaVersion(); if (javaVersion < 9) { cleanDirectBufferJava8(buffer); } else { cleanDirectBufferJava11(buffer); } }
Source:
public BeanDefinition parse(Element element, ParserContext parserContext) { this.initializeSpelFunctionRegistrarIfNecessary(parserContext); String id = element.getAttribute("id"); String className = element.getAttribute("class"); String signature = element.getAttribute("method"); Class clazz = null; try { clazz = ClassUtils.forName(className, ClassUtils.getDefaultClassLoader()); } catch (ClassNotFoundException e) { parserContext.getReaderContext().error(e.getMessage(), element); } Method method = BeanUtils.resolveSignature(signature, clazz); if (method == null) { parserContext.getReaderContext().error(String.format("No declared method '%s' in class '%s'", signature, className), element); return null; } if (!Modifier.isStatic(method.getModifiers())) { parserContext.getReaderContext().error("SpEL-function method has to be 'static'", element); } this.functions.put(id, method); return null; }

Target:
public BeanDefinition parse(Element element, ParserContext parserContext) { this.initializeSpelFunctionRegistrarIfNecessary(parserContext); String id = element.getAttribute("id"); String className = element.getAttribute("class"); String signature = element.getAttribute("method"); Class<?> clazz = null; try { clazz = ClassUtils.forName(className, parserContext.getReaderContext().getBeanClassLoader()); } catch (ClassNotFoundException e) { parserContext.getReaderContext().error(e.getMessage(), element); } Method method = BeanUtils.resolveSignature(signature, clazz); if (method == null) { parserContext.getReaderContext().error(String.format("No declared method '%s' in class '%s'", signature, className), element); return null; } if (!Modifier.isStatic(method.getModifiers())) { parserContext.getReaderContext().error("SpEL-function method has to be 'static'", element); } this.functions.put(id, method); return null; }
Source:
protected Mutation generateMutation(MutatableCode mutatableCode) { generateCachedNewInstanceInsns(mutatableCode); int newInstanceIdx = rng.nextInt(newInstanceCachedInsns.size() - 1); int newInstanceTypeIdx = rng.nextInt(mutatableCode.program.getTotalPoolIndicesByKind(PoolIndexKind.Type)); AssociatedMutation mutation = new AssociatedMutation(); mutation.setup(this.getClass(), mutatableCode); mutation.newInstanceToChangeIdx = newInstanceIdx; mutation.newInstanceTypeIdx = newInstanceTypeIdx; return mutation; }

Target:
protected Mutation generateMutation(MutatableCode mutatableCode) { generateCachedNewInstanceInsns(mutatableCode); int newInstanceIdx = rng.nextInt(newInstanceCachedInsns.size()); int newInstanceTypeIdx = rng.nextInt(mutatableCode.program.getTotalPoolIndicesByKind(PoolIndexKind.Type)); AssociatedMutation mutation = new AssociatedMutation(); mutation.setup(this.getClass(), mutatableCode); mutation.newInstanceToChangeIdx = newInstanceIdx; mutation.newInstanceTypeIdx = newInstanceTypeIdx; return mutation; }
Source:
public ListInstancesOptions publicIpAddresses(String... publicIpAddresses) { String instanceIdsAsString = Joiner.on(",") .join(Iterables.transform(Arrays.asList(publicIpAddresses), new Function<String, String>() { @Override public String apply(String s) { return new StringBuilder(s.length() + 1).append('"').append(s).append('"').toString(); } })); queryParameters.put(PUBLIC_IP_ADDRESSES_PARAM, String.format("[%s]", instanceIdsAsString)); return this; }

Target:
public ListInstancesOptions publicIpAddresses(String... publicIpAddresses) { String instanceIdsAsString = Joiner.on(",") .join(Iterables.transform(Arrays.asList(publicIpAddresses), new PutStringInDoubleQuotes())); queryParameters.put(PUBLIC_IP_ADDRESSES_PARAM, String.format("[%s]", instanceIdsAsString)); return this; }
Source:
public static State getSoundState(final float sound, final DateTime dataTimestampUTC, final Boolean preSleep) { State.Condition condition = State.Condition.IDEAL;; String idealSoundCondition = English.SOUND_ADVICE_MESSAGE; String message = (preSleep) ? English.IDEAL_SOUND_PRE_SLEEP_MESSAGE: English.IDEAL_SOUND_MESSAGE;; if (sound > 90.0) { condition = State.Condition.ALERT; idealSoundCondition += English.RECOMMENDATION_SOUND_TOO_HIGH; message = (preSleep) ? English.ALERT_SOUND_PRE_SLEEP_MESSAGE : English.ALERT_SOUND_MESSAGE; } else if (sound > 55.0) { condition = State.Condition.WARNING; idealSoundCondition += English.RECOMMENDATION_SOUND_TOO_HIGH; message = (preSleep) ? English.WARNING_SOUND_PRE_SLEEP_MESSAGE: English.WARNING_SOUND_MESSAGE; } return new State(sound, message, idealSoundCondition, condition, dataTimestampUTC, State.Unit.DB); }

Target:
public static State getSoundState(final float sound, final DateTime dataTimestampUTC, final Boolean preSleep) { State.Condition condition = State.Condition.IDEAL;; String idealSoundCondition = English.SOUND_ADVICE_MESSAGE; String message = (preSleep) ? English.IDEAL_SOUND_PRE_SLEEP_MESSAGE: English.IDEAL_SOUND_MESSAGE;; if (sound > SoundLevel.SOUND_LEVEL_ALERT) { condition = State.Condition.ALERT; idealSoundCondition += English.RECOMMENDATION_SOUND_TOO_HIGH; message = (preSleep) ? English.ALERT_SOUND_PRE_SLEEP_MESSAGE : English.ALERT_SOUND_MESSAGE; } else if (sound > SoundLevel.SOUND_LEVEL_WARNING) { condition = State.Condition.WARNING; idealSoundCondition += English.RECOMMENDATION_SOUND_TOO_HIGH; message = (preSleep) ? English.WARNING_SOUND_PRE_SLEEP_MESSAGE: English.WARNING_SOUND_MESSAGE; } return new State(sound, message, idealSoundCondition, condition, dataTimestampUTC, State.Unit.DB); }
Source:
StringBasedN1qlQueryParser.N1qlSpelValues getN1qlSpelValues(ReactiveCouchbaseTemplate template, Class domainClass, boolean isCount) { String typeKey = template.getConverter().getTypeKey(); final CouchbasePersistentEntity<?> persistentEntity = template.getConverter().getMappingContext().getRequiredPersistentEntity( domainClass); MappingCouchbaseEntityInformation<?, Object> info = new MappingCouchbaseEntityInformation<>(persistentEntity); String typeValue = info.getJavaType().getName(); TypeInformation<?> typeInfo= ClassTypeInformation.from(info.getJavaType()); Alias alias = template.getConverter().getAlias(typeInfo); if ( alias != null && alias.isPresent()){ typeValue=alias.toString(); } return StringBasedN1qlQueryParser.createN1qlSpelValues(template.getBucketName(), typeKey, typeValue, isCount); }

Target:
StringBasedN1qlQueryParser.N1qlSpelValues getN1qlSpelValues(ReactiveCouchbaseTemplate template, Class domainClass, boolean isCount) { String typeKey = template.getConverter().getTypeKey(); final CouchbasePersistentEntity<?> persistentEntity = template.getConverter().getMappingContext() .getRequiredPersistentEntity(domainClass); MappingCouchbaseEntityInformation<?, Object> info = new MappingCouchbaseEntityInformation<>(persistentEntity); String typeValue = info.getJavaType().getName(); TypeInformation<?> typeInfo = ClassTypeInformation.from(info.getJavaType()); Alias alias = template.getConverter().getTypeAlias(typeInfo); if (alias != null && alias.isPresent()) { typeValue = alias.toString(); } return StringBasedN1qlQueryParser.createN1qlSpelValues(template.getBucketName(), typeKey, typeValue, isCount); }
Source:
public void adjust(Mechanism mechanism) { if (mechanism.matches("group")) { spawner.setGroup(mechanism.getValue().asString()); } else if (mechanism.matches("location") && mechanism.requireObject(LocationTag.class)) { spawner.setLocation(BukkitAdapter.adapt(mechanism.valueAsType(LocationTag.class))); } else if (mechanism.matches("cooldown") && mechanism.requireInteger()) { spawner.setCooldownSeconds(mechanism.getValue().asInt()); } else if (mechanism.matches("start_cooldown")) { spawner.setOnCooldown(); } else if (mechanism.matches("set_mob_type")) { MythicMob mob = MythicMobsBridge.getMythicMob(mechanism.getValue().asString()); if (mob == null) { Debug.echoError("MythicMob type does not exist: " + mechanism.getValue().asString()); return; } spawner.setType(mechanism.getValue().asString()); } else if (mechanism.matches("spawn")) { spawner.Spawn(); } else if (mechanism.matches("enable")) { spawner.Enable(); } else if (mechanism.matches("disable")) { spawner.Disable(); } }

Target:
public void adjust(Mechanism mechanism) { if (mechanism.matches("group")) { spawner.setGroup(mechanism.getValue().asString()); } else if (mechanism.matches("location") && mechanism.requireObject(LocationTag.class)) { spawner.setLocation(BukkitAdapter.adapt(mechanism.valueAsType(LocationTag.class))); } else if (mechanism.matches("cooldown") && mechanism.requireObject(DurationTag.class)) { spawner.setCooldownSeconds(mechanism.valueAsType(DurationTag.class).getSecondsAsInt()); } else if (mechanism.matches("start_cooldown")) { spawner.setOnCooldown(); } else if (mechanism.matches("mob_type")) { MythicMob mob = MythicMobsBridge.getMythicMob(mechanism.getValue().asString()); if (mob == null) { Debug.echoError("MythicMob type does not exist: " + mechanism.getValue().asString()); return; } spawner.setType(mechanism.getValue().asString()); } else if (mechanism.matches("spawn")) { spawner.Spawn(); } else if (mechanism.matches("enable")) { spawner.Enable(); } else if (mechanism.matches("disable")) { spawner.Disable(); } }
Source:
public void testExtractParentDataSingleParent() { final ReportServiceImpl unitUnderTest = Mockito.mock(ReportServiceImpl.class); Mockito.doReturn(this.germplasmDataManager).when(unitUnderTest).getGermplasmDataManager(); final List<MeasurementRow> measurementRowList = createMeasurementList(); final Map<Integer, GermplasmPedigreeTreeNode> pedigreeTreeNodeMap = GermplasmDataManagerDataInitializer.createTreeNodeMap(true); Mockito.doReturn(pedigreeTreeNodeMap).when(this.germplasmDataManager).getDirectParentsForStudy(TEST_STUDY_ID); Mockito.doCallRealMethod().when(unitUnderTest).appendParentsInformation(TEST_STUDY_ID, measurementRowList); unitUnderTest.appendParentsInformation(TEST_STUDY_ID, measurementRowList); final MeasurementRow row = measurementRowList.get(0); Assert.assertEquals("Female selection history should be blank if female parent information is not provided in database", "", row .getMeasurementData(AbstractReporter.FEMALE_SELECTION_HISTORY_KEY).getValue()); Assert.assertEquals("Male selection history not properly filled in from provided information", GermplasmDataManagerDataInitializer.MALE_SELECTION_HISTORY, row.getMeasurementData(AbstractReporter.MALE_SELECTION_HISTORY_KEY).getValue()); }

Target:
public void testExtractParentDataSingleParent() { final ReportServiceImpl unitUnderTest = Mockito.mock(ReportServiceImpl.class); Mockito.doReturn(this.germplasmDataManager).when(unitUnderTest).getGermplasmDataManager(); final List<MeasurementRow> measurementRowList = createMeasurementList(); final Map<Integer, GermplasmPedigreeTreeNode> pedigreeTreeNodeMap = GermplasmDataManagerDataInitializer.createTreeNodeMap(true); Mockito.doReturn(pedigreeTreeNodeMap).when(this.germplasmDataManager).getDirectParentsForStudy(TEST_STUDY_ID); Mockito.doCallRealMethod().when(unitUnderTest).appendParentsInformation(TEST_STUDY_ID, measurementRowList); Mockito.doCallRealMethod().when(unitUnderTest).provideParentInformation(Mockito.any(GermplasmPedigreeTreeNode.class), Mockito.anyList()); unitUnderTest.appendParentsInformation(TEST_STUDY_ID, measurementRowList); final MeasurementRow row = measurementRowList.get(0); Assert.assertEquals("Female selection history should be blank if female parent information is not provided in database", ReportServiceImpl.BLANK_STRING_VALUE, row .getMeasurementData(AbstractReporter.FEMALE_SELECTION_HISTORY_KEY).getValue()); Assert.assertEquals("Male selection history not properly filled in from provided information", GermplasmDataManagerDataInitializer.MALE_SELECTION_HISTORY, row.getMeasurementData(AbstractReporter.MALE_SELECTION_HISTORY_KEY).getValue()); }
Source:
public void onPackageRemoved(String packageName) { int uid; synchronized (mPackageNameUidMap) { if (!mPackageNameUidMap.containsKey(packageName)) { return; } uid = mPackageNameUidMap.get(packageName); mPackageNameUidMap.remove(packageName); } SparseIntArray netdPermissionsAppIds = new SparseIntArray(); netdPermissionsAppIds.put(uid, INetd.NO_PERMISSIONS); sendPackagePermissionsToNetd(netdPermissionsAppIds); }

Target:
public void onPackageRemoved(String packageName) { int uid; synchronized (mPackageNameUidMap) { if (!mPackageNameUidMap.containsKey(packageName)) { return; } uid = mPackageNameUidMap.get(packageName); mPackageNameUidMap.remove(packageName); } int permission = 0; String[] packages = mPackageManager.getPackagesForUid(uid); if (packages != null && packages.length > 0) { for (String name : packages) { final PackageInfo app = getPackageInfo(name); if (app != null && app.requestedPermissions != null) { permission |= filterPermission(Arrays.asList(app.requestedPermissions)); } } } sendPackagePermissionsForUid(uid, permission); }
Source:
private Schema getOutputSchema() { List<Schema.Field> fields = new ArrayList<>(); String[] mappings = fieldTypeMapping.split(","); for (String mapping : mappings) { String[] params = mapping.split(":"); String fieldName = params[0].trim(); if (Strings.isNullOrEmpty(fieldName)) { throw new IllegalArgumentException("Field name cannot be null or empty."); } else if (params.length < 2 || Strings.isNullOrEmpty(params[1])) { throw new IllegalArgumentException("Type cannot be null. Please specify type for " + fieldName); } Schema.Field field = Schema.Field.of(fieldName, Schema.nullableOf(Schema.of(Schema.Type.valueOf( params[1].trim().toUpperCase())))); if (fields.contains(field)) { throw new IllegalArgumentException("Field " + fieldName + " already has type specified. Check the mapping."); } else { fields.add(field); } } return Schema.recordOf("record", fields); }

Target:
private Schema getOutputSchema() { List<Schema.Field> fields = new ArrayList<>(); String[] mappings = fieldTypeMapping.split(","); for (String mapping : mappings) { String[] params = mapping.split(":"); String fieldName = params[0].trim(); if (Strings.isNullOrEmpty(fieldName)) { throw new IllegalArgumentException("Field name cannot be null or empty."); } else if (params.length < 2 || Strings.isNullOrEmpty(params[1])) { throw new IllegalArgumentException("Type cannot be null. Please specify type for " + fieldName); } Schema.Field field = Schema.Field.of(fieldName, Schema.nullableOf(Schema.of(Schema.Type.valueOf( params[1].trim().toUpperCase())))); if (fields.contains(field)) { throw new IllegalArgumentException(String.format("Field %s already has type specified. Duplicate field %s", fieldName, fieldName)); } else { fields.add(field); } } return Schema.recordOf("record", fields); }
Source:
public void onBackPressed() { if (narrowedList == null) { if (backPressedOnce) { finish(); } backPressedOnce = true; Toast.makeText(this, R.string.press_again_to_exit, Toast.LENGTH_SHORT).show(); statusUpdateRunnable = new Runnable() { @Override public void run() { backPressedOnce = false; } }; statusUpdateHandler.postDelayed(statusUpdateRunnable, 2000); } else { narrowedList = null; getSupportFragmentManager().popBackStack(NARROW, FragmentManager.POP_BACK_STACK_INCLUSIVE); clearSearch(); } }

Target:
public void onBackPressed() { if (narrowedList == null) { if (backPressedOnce) { finish(); } backPressedOnce = true; Toast.makeText(this, R.string.press_again_to_exit, Toast.LENGTH_SHORT).show(); statusUpdateRunnable = new Runnable() { @Override public void run() { backPressedOnce = false; } }; statusUpdateHandler.postDelayed(statusUpdateRunnable, 2000); } else { narrowedList = null; getSupportFragmentManager().popBackStack(NARROW, FragmentManager.POP_BACK_STACK_INCLUSIVE); } }
Source:
public void runScript(String scriptContent, Consumer<Exception> errorCallback) { final String language = Locale.getDefault().getLanguage(); final String i18nextInit = "i18next.init({ " + String.format(" lng: '%s', ", language) + " debug: true, " + " resources: { " + " en: { " + " translation: { " + " \"Please enter the name of your application\": \"Please enter the name of your application.\"" + " } " + " }, " + " de: { " + " translation: { " + " \"Please enter the name of your application\": \"Bitte geben Sie den Namen Ihrer Anwendung ein.\"" + " } " + " } " + " } " + "}, function(err, t) { " + " if (err) { " + " print('Could not load translation', err); " + " } " + "}); "; final String scriptContenti18n = "include([\"Functions\", \"i18n\", \"i18next\"]);" + i18nextInit + scriptContent; nashornEngineFactory.createEngine().eval(scriptContenti18n, errorCallback); }

Target:
public void runScript(String scriptContent, Consumer<Exception> errorCallback) { final String language = Locale.getDefault().getLanguage(); StringBuilder translationsBuilder = new StringBuilder(); for (TranslationDTO translationDTO : this.translations) { translationsBuilder.append(translationDTO.getLanguage()); translationsBuilder.append(":{"); translationsBuilder.append("translation:"); translationsBuilder.append(translationDTO.getJson()); translationsBuilder.append("},"); } final String i18nextInit = "i18next.init({ " + String.format(" lng: '%s', ", language) + " debug: true, " + " resources: { " + translationsBuilder.toString() + " } " + "}, function(err, t) { " + " if (err) { " + " print('Could not load translation', err); " + " } " + "}); "; final String scriptContenti18n = "include([\"Functions\", \"i18n\", \"i18next\"]);" + i18nextInit + scriptContent; nashornEngineFactory.createEngine().eval(scriptContenti18n, errorCallback); }
Source:
public void setTimeoutFuture(Future<?> timeoutFuture) { this.timeoutFuture = timeoutFuture; }

Target:
public void setTimeoutFuture(Future<?> timeoutFuture) { this.timeoutFuture = timeoutFuture; if (isDone()) { timeoutFuture.cancel(false); } }
Source:
public boolean apply(GitHubPRCause cause) { try { cause.setPollingLog(trigger.getPollingLogAction().getLogFile()); StringBuilder sb = new StringBuilder(); sb.append("Jenkins queued the run (").append(cause.getReason()).append(")"); if (trigger.isCancelQueued() && cancelQueuedBuildByPrNumber(cause.getNumber())) { sb.append(". Queued builds aborted"); } QueueTaskFuture<?> queueTaskFuture = startJob(cause); if (isNull(queueTaskFuture)) { LOGGER.error("{} job didn't start", job.getFullName()); } LOGGER.info(sb.toString()); if (trigger.isPreStatus()) { if (job instanceof MatrixProject) { Collection<? extends MatrixConfiguration> configs = ((MatrixProject) job).getActiveConfigurations(); for (MatrixConfiguration config : configs) { trigger.getRemoteRepo() .createCommitStatus(cause.getHeadSha(), GHCommitState.PENDING, config.getAbsoluteUrl(), sb.toString(), config.getFullName()); } } else { trigger.getRemoteRepo() .createCommitStatus(cause.getHeadSha(), GHCommitState.PENDING, job.getAbsoluteUrl(), sb.toString(), job.getFullName()); } } } catch (IOException e) { LOGGER.error("Can't trigger build ({})", e.getMessage(), e); return false; } return true; }

Target:
public boolean apply(GitHubPRCause cause) { try { cause.setPollingLog(trigger.getPollingLogAction().getPollingLogFile()); StringBuilder sb = new StringBuilder(); sb.append("Jenkins queued the run (").append(cause.getReason()).append(")"); if (trigger.isCancelQueued() && cancelQueuedBuildByPrNumber(cause.getNumber())) { sb.append(". Queued builds aborted"); } QueueTaskFuture<?> queueTaskFuture = startJob(cause); if (isNull(queueTaskFuture)) { LOGGER.error("{} job didn't start", job.getFullName()); } LOGGER.info(sb.toString()); if (trigger.isPreStatus()) { if (job instanceof MatrixProject) { Collection<? extends MatrixConfiguration> configs = ((MatrixProject) job).getActiveConfigurations(); for (MatrixConfiguration config : configs) { trigger.getRemoteRepo() .createCommitStatus(cause.getHeadSha(), GHCommitState.PENDING, config.getAbsoluteUrl(), sb.toString(), config.getFullName()); } } else { trigger.getRemoteRepo() .createCommitStatus(cause.getHeadSha(), GHCommitState.PENDING, job.getAbsoluteUrl(), sb.toString(), job.getFullName()); } } } catch (IOException e) { LOGGER.error("Can't trigger build ({})", e.getMessage(), e); return false; } return true; }
Source:
public void setMaximizedControl(Control control){ checkWidget(); if (control == null) { if (maxControl != null) { this.maxControl = null; layout(false); for (Sash sashe : sashes) { sashe.setVisible(true); } } return; } for (Sash sashe : sashes) { sashe.setVisible(false); } maxControl = control; layout(false); }

Target:
public void setMaximizedControl(Control control){ checkWidget(); if (control == null) { if (maxControl != null) { this.maxControl = null; layout(false); for (Sash sashe : sashes) { sashe.setVisible(true); } } return; } for (Sash sash : sashes) { sash.setVisible(false); } maxControl = control; layout(false); }
Source:
private void fillEdges(SPTEntry currEdge, PriorityQueue<SPTEntry> prioQueue, IntObjectMap<SPTEntry> bestWeightMap, RoutingCHEdgeExplorer explorer, boolean reverse) { RoutingCHEdgeIterator iter = explorer.setBaseNode(currEdge.adjNode); while (iter.next()) { if (!accept(iter, currEdge, reverse)) continue; final double weight = calcWeight(iter, currEdge, reverse); if (Double.isInfinite(weight)) { continue; } final int origEdgeId = getOrigEdgeId(iter, reverse); final int traversalId = getTraversalId(iter, origEdgeId, reverse); SPTEntry entry = bestWeightMap.get(traversalId); if (entry == null) { entry = createEntry(iter, origEdgeId, weight, currEdge, reverse); bestWeightMap.put(traversalId, entry); prioQueue.add(entry); } else if (entry.getWeightOfVisitedPath() > weight) { prioQueue.remove(entry); updateEntry(entry, iter, origEdgeId, weight, currEdge, reverse); prioQueue.add(entry); } else continue; if (updateBestPath) { double edgeWeight = traversalMode.isEdgeBased() ? calcWeight(iter, reverse, NO_EDGE) : Double.POSITIVE_INFINITY; updateBestPath(edgeWeight, entry, origEdgeId, traversalId, reverse); } } }

Target:
private void fillEdges(SPTEntry currEdge, PriorityQueue<SPTEntry> prioQueue, IntObjectMap<SPTEntry> bestWeightMap, RoutingCHEdgeExplorer explorer, boolean reverse) { RoutingCHEdgeIterator iter = explorer.setBaseNode(currEdge.adjNode); while (iter.next()) { if (!accept(iter, currEdge, reverse)) continue; final double weight = calcWeight(iter, currEdge, reverse); if (Double.isInfinite(weight)) { continue; } final int origEdgeId = getOrigEdgeId(iter, reverse); final int traversalId = getTraversalId(iter, origEdgeId, reverse); SPTEntry entry = bestWeightMap.get(traversalId); if (entry == null) { entry = createEntry(iter, origEdgeId, weight, currEdge, reverse); bestWeightMap.put(traversalId, entry); prioQueue.add(entry); } else if (entry.getWeightOfVisitedPath() > weight) { prioQueue.remove(entry); updateEntry(entry, iter, origEdgeId, weight, currEdge, reverse); prioQueue.add(entry); } else continue; if (updateBestPath) { updateBestPath(Double.POSITIVE_INFINITY, entry, origEdgeId, traversalId, reverse); } } }
Source:
public static RequestControlAdminRequest readFrom(DataInputStream stream, AdminRequest adminRequest) throws IOException { Short versionId = stream.readShort(); if (!versionId.equals(VERSION_V1)) { throw new IllegalStateException("Unrecognized version for RequestControlAdminRequest: " + VERSION_V1); } RequestOrResponseType requestType = RequestOrResponseType.values()[stream.readShort()]; boolean enable = stream.readByte() == 1; return new RequestControlAdminRequest(requestType, enable, adminRequest); }

Target:
public static RequestControlAdminRequest readFrom(DataInputStream stream, AdminRequest adminRequest) throws IOException { Short versionId = stream.readShort(); if (!versionId.equals(VERSION_V1)) { throw new IllegalStateException("Unrecognized version for RequestControlAdminRequest: " + versionId); } RequestOrResponseType requestType = RequestOrResponseType.values()[stream.readShort()]; boolean enable = stream.readByte() == 1; return new RequestControlAdminRequest(requestType, enable, adminRequest); }
Source:
public void init(StreamGraph graph, Config config) { try { BiFunction<String, String, String> messageBuilder = (key, msg) -> { String result = ""; try { TestKafkaEvent incomingMessage = TestKafkaEvent.fromSerializedString(msg); if (appLifeCycleListener != null) { appLifeCycleListener.onMessageReceived(incomingMessage); } result = incomingMessage.toString(); } catch (Exception e) { LOGGER.error("Exception when processing message in TestStreamApplication: ", e); appLifeCycleListener.onExceptionOccurred(e); } if (processedMessagesLatch != null) { processedMessagesLatch.countDown(); } return result; }; MessageStream<String> inputStream = graph.getInputStream(inputTopic, messageBuilder); OutputStream<String, String, String> outputStream = graph.getOutputStream(outputTopic, event -> null, event -> event); inputStream.sendTo(outputStream); } catch (Exception e) { if (appLifeCycleListener != null) { appLifeCycleListener.onExceptionOccurred(e); } } }

Target:
public void init(StreamGraph graph, Config config) { MessageStream<String> inputStream = graph.getInputStream(inputTopic, (key, msg) -> { TestKafkaEvent incomingMessage = TestKafkaEvent.fromString((String) msg); if (streamApplicationCallback != null) { streamApplicationCallback.onMessageReceived(incomingMessage); } if (processedMessagesLatch != null) { processedMessagesLatch.countDown(); } if (kafkaEventsConsumedLatch != null) { kafkaEventsConsumedLatch.countDown(); } return incomingMessage.toString(); }); OutputStream<String, String, String> outputStream = graph.getOutputStream(outputTopic, event -> null, event -> event); inputStream.sendTo(outputStream); }
Source:
private static List<File> getAllFiles(File dir) { final List<File> result = new ArrayList<>(); dir.listFiles(file -> { if (file.isDirectory()) { result.addAll(getAllFiles(file)); } else if (file.getName().endsWith(".java") && !file.getName().endsWith("InputGrammar.java") && !file.getName().endsWith("InputPackageDeclarationWithCommentOnly.java") && !file.getName().endsWith("InputSingleSpaceSeparatorEmpty.java") && !file.getName().endsWith("InputNoCodeInFile1.java") && !file.getName().endsWith("InputNoCodeInFile2.java") && !file.getName().endsWith("InputNoCodeInFile3.java")) { result.add(file); } return false; }); return result; }

Target:
private static List<File> getAllFiles(File dir) { final List<File> result = new ArrayList<>(); dir.listFiles(file -> { if (file.isDirectory()) { result.addAll(getAllFiles(file)); } else if (file.getName().endsWith(".java") && !NO_ROOT_FILES.contains(file.getName())) { result.add(file); } return false; }); return result; }
Source:
public void load(List<FormStatus> forms, BriefcasePreferences preferences) { this.forms = forms; this.lastPullCursorsByFormId = forms.stream() .map(form -> Pair.of(form.getFormId(), preferences.nullSafeGet(form.getFormId() + "-last-cursor"))) .filter(pair -> pair.getRight().isPresent()) .map(pair -> pair.map(identity(), Optional::get)) .collect(toMap(Pair::getLeft, Pair::getRight)); triggerOnChange(); }

Target:
public void load(List<FormStatus> forms, BriefcasePreferences preferences) { this.forms = forms; this.lastPullCursorsByFormId = forms.stream() .map(form -> Pair.of(form.getFormId(), preferences.nullSafeGet(form.getFormId() + LAST_CURSOR_PREFERENCE_KEY_SUFFIX))) .filter(pair -> pair.getRight().isPresent()) .map(pair -> pair.map(identity(), Optional::get)) .collect(toMap(Pair::getLeft, Pair::getRight)); triggerOnChange(); }
Source:
public boolean setupTable() { log.debug("setting up table {}, policy={}}", tableName, policy); if (policy.equals(CREATE_TABLE_POLICY_NEVER)) { log.debug("policy='{}', skipping setup", CREATE_TABLE_POLICY_NEVER); return false; } synchronized (DIRECTORY_INIT_LOCK) { boolean tableExists = tableExists(); if (policy.equals(CREATE_TABLE_POLICY_ON_MISSING_COLUMNS) && tableExists) { if (hasMatchingColumns()) { log.debug("policy='{}' and all column matched, skipping data load", CREATE_TABLE_POLICY_ON_MISSING_COLUMNS); } else { log.debug("policy='{}' and some columns are missing", CREATE_TABLE_POLICY_ON_MISSING_COLUMNS); addMissingColumns(); } return false; } try { createTable(tableExists); } catch (ConcurrentUpdateException e) { } return true; } }

Target:
public boolean setupTable() { log.debug("setting up table {}, policy={}", tableName, policy); if (policy.equals(CREATE_TABLE_POLICY_NEVER)) { log.debug("policy='{}', skipping setup", CREATE_TABLE_POLICY_NEVER); return false; } synchronized (DIRECTORY_INIT_LOCK) { boolean tableExists = tableExists(); if (policy.equals(CREATE_TABLE_POLICY_ON_MISSING_COLUMNS) && tableExists) { if (hasMatchingColumns()) { log.debug("policy='{}' and all column matched, skipping data load", CREATE_TABLE_POLICY_ON_MISSING_COLUMNS); } else { log.debug("policy='{}' and some columns are missing", CREATE_TABLE_POLICY_ON_MISSING_COLUMNS); addMissingColumns(); } return false; } try { createTable(tableExists); } catch (ConcurrentUpdateException e) { } return true; } }
Source:
protected List<String> getClasspathElements() throws Exception { final List<String> back = project.getCompileClasspathElements(); back.remove(project.getBuild().getOutputDirectory()); if (additionalDependencies != null) { for (Dependency dependency : additionalDependencies) { addToClasspath(factory.createDependencyArtifact(dependency), back, false); } } if (classpath != null && classpath.getAdd() != null) { getLog().warn("using 'classpath' is deprecated, use 'additionalDependencies' instead"); for (File f : classpath.getAdd()) { back.add(f.getAbsolutePath()); } } back.addAll(TychoUtilities.addOsgiClasspathElements(project)); return back; }

Target:
protected Set<String> getClasspathElements() throws Exception { final Set<String> back = new HashSet<>(project.getCompileClasspathElements()); back.remove(project.getBuild().getOutputDirectory()); addAdditionalDependencies(back); if (classpath != null && classpath.getAdd() != null) { getLog().warn("using 'classpath' is deprecated, use 'additionalDependencies' instead"); for (File f : classpath.getAdd()) { back.add(f.getAbsolutePath()); } } back.addAll(TychoUtilities.addOsgiClasspathElements(project)); return back; }
Source:
public IntegrationFlow ftpInboundFlow() { IntegrationFlowBuilder flowBuilder = IntegrationFlows.from(Ftp.inboundAdapter(FtpSource.this.ftpSessionFactory) .preserveTimestamp(config.isPreserveTimestamp()) .remoteDirectory(config.getRemoteDir()) .patternFilter(config.getFilenamePattern()) .remoteFileSeparator(config.getRemoteFileSeparator()) .localDirectory(config.getLocalDir()) .autoCreateLocalDirectory(config.isAutoCreateLocalDir()) .temporaryFileSuffix(config.getTmpFileSuffix()) .deleteRemoteFiles(config.isDeleteRemoteFiles()) , new Consumer<SourcePollingChannelAdapterSpec>() { @Override public void accept(SourcePollingChannelAdapterSpec sourcePollingChannelAdapterSpec) { sourcePollingChannelAdapterSpec.poller(poller()); } }); switch (fileConsumerConfig.getMode()) { case contents: flowBuilder.enrichHeaders(Collections.singletonMap(MessageHeaders.CONTENT_TYPE, "application/octet-stream")) .transform(new FileToByteArrayTransformer()); break; case lines: flowBuilder.enrichHeaders(Collections.singletonMap(MessageHeaders.CONTENT_TYPE, "text/plain")) .split(new FileSplitter(true, fileConsumerConfig.getWithMarkers()), null); default: break; } if (fileConsumerConfig.getMode().equals(FileReadingMode.contents)) { } return flowBuilder.channel(source.output()).get(); }

Target:
public IntegrationFlow ftpInboundFlow() { IntegrationFlowBuilder flowBuilder = IntegrationFlows.from(Ftp.inboundAdapter(FtpSource.this.ftpSessionFactory) .preserveTimestamp(config.isPreserveTimestamp()) .remoteDirectory(config.getRemoteDir()) .patternFilter(config.getFilenamePattern()) .remoteFileSeparator(config.getRemoteFileSeparator()) .localDirectory(config.getLocalDir()) .autoCreateLocalDirectory(config.isAutoCreateLocalDir()) .temporaryFileSuffix(config.getTmpFileSuffix()) .deleteRemoteFiles(config.isDeleteRemoteFiles()) , new Consumer<SourcePollingChannelAdapterSpec>() { @Override public void accept(SourcePollingChannelAdapterSpec sourcePollingChannelAdapterSpec) { sourcePollingChannelAdapterSpec .autoStartup(false) .poller(poller()); } }); switch (fileConsumerConfig.getMode()) { case contents: flowBuilder.enrichHeaders(Collections.<String, Object>singletonMap(MessageHeaders.CONTENT_TYPE, "application/octet-stream")) .transform(new FileToByteArrayTransformer()); break; case lines: flowBuilder.enrichHeaders(Collections.<String, Object>singletonMap(MessageHeaders.CONTENT_TYPE, "text/plain")) .split(new FileSplitter(true, fileConsumerConfig.getWithMarkers()), null); case ref: break; default: throw new IllegalArgumentException(fileConsumerConfig.getMode().name() + " is not a supported file reading mode."); } return flowBuilder.channel(source.output()).get(); }
Source:
public static void sleep(long millis) { try { Thread.sleep(millis); } catch (InterruptedException e) { throw Throwables.propagate(e); } }

Target:
public static void sleep(long millis) { try { Thread.sleep(millis); } catch (InterruptedException e) { throw Exceptions.propagate(e); } }
Source:
public void setWindingOrder(EnumWindingOrderTypes windingOrderType) { setParameter(PARAM_UNIFY_WINDING_ORDER, Value.of(windingOrderType)); }

Target:
public void setWindingOrder(EnumWindingOrderTypes windingOrderType) { setParameter(PARAM_UNIFY_WINDING_ORDER, Value.of(windingOrderType.toString())); }
Source:
public void triggerRoleRefresh(ApiClient client, String clusterName, String serviceName, String roleName) { LOGGER.info("Attempting to trigger role refresh on clusterName = {}, serviceName = {}, roleName = {}", clusterName, serviceName, roleName); ApiRoleNameList roleNameList = new ApiRoleNameList(); roleNameList.addItemsItem(roleName); RoleCommandsResourceApi roleCommandsResourceApi = clouderaManagerApiFactory.getRoleCommandsResourceApi(client); try { ApiBulkCommandList bulkResponse = roleCommandsResourceApi.refreshCommand(clusterName, serviceName, roleNameList); ApiCommand response = Iterables.getOnlyElement(bulkResponse.getItems()); LOGGER.info("ApiCommand response for role refresh = {}", response); if (response != null && (response.getActive() || response.getSuccess())) { LOGGER.info("Successfully triggered role refresh"); } else { LOGGER.debug("Failed to trigger role refresh"); throw new RangerCloudIdentitySyncException("Role refresh was not successfully trigerred"); } } catch (ApiException e) { throw new RangerCloudIdentitySyncException("Encountered ApiException on role refresh", e); } }

Target:
private void triggerRoleRefresh(ApiClient client, String clusterName, String serviceName, String roleName) { LOGGER.info("Attempting to trigger role refresh on clusterName = {}, serviceName = {}, roleName = {}", clusterName, serviceName, roleName); ApiRoleNameList roleNameList = new ApiRoleNameList(); roleNameList.addItemsItem(roleName); RoleCommandsResourceApi roleCommandsResourceApi = clouderaManagerApiFactory.getRoleCommandsResourceApi(client); try { ApiBulkCommandList bulkResponse = roleCommandsResourceApi.refreshCommand(clusterName, serviceName, roleNameList); ApiCommand response = Iterables.getOnlyElement(bulkResponse.getItems()); LOGGER.info("ApiCommand response for role refresh = {}", response); if (response != null && (response.getActive() || response.getSuccess())) { LOGGER.info("Successfully triggered role refresh"); } else { LOGGER.debug("Failed to trigger role refresh"); throw new RangerCloudIdentitySyncException("Role refresh was not successfully trigerred"); } } catch (ApiException e) { LOGGER.error("Encountered ApiException on role refresh", e); throw new RangerCloudIdentitySyncException("Encountered ApiException on role refresh", e); } }
Source:
private void stopConfiguration() throws Exception { if (configuration == null) { if (progress == null) { progress = new ScriptProgress(newSequential(0, 0), ""); } RegionInfo scriptInfo = progress.getScriptInfo(); progress.addScriptFailure(scriptInfo); } else { for (ServerBootstrapResolver serverResolver : configuration.getServerResolvers()) { ServerBootstrap server = serverResolver.resolve(); server.setPipelineFactory(pipelineFactory(pipeline(closeOnExceptionHandler))); } for (ClientBootstrapResolver clientResolver : configuration.getClientResolvers()) { try { ClientBootstrap client = clientResolver.resolve(); client.setPipelineFactory(pipelineFactory(pipeline(closeOnExceptionHandler))); } catch (RuntimeException e) { LOGGER.warn("Exception caught while trying to stop client pipelies: " + e); } } for (ChannelPipeline pipeline : configuration.getClientAndServerPipelines()) { stopStream(pipeline); } for (ChannelFuture bindFuture : bindFutures) { bindFuture.cancel(); } for (ChannelFuture connectFuture : connectFutures) { if (connectFuture.cancel()) { LOGGER.debug("Cancelled connect future: " + connectFuture.getChannel().getRemoteAddress()); } } } }

Target:
private void stopConfiguration() throws Exception { if (configuration == null) { if (progress == null) { progress = new ScriptProgress(newSequential(0, 0), ""); } RegionInfo scriptInfo = progress.getScriptInfo(); progress.addScriptFailure(scriptInfo); } else { for (ServerBootstrapResolver serverResolver : configuration.getServerResolvers()) { try { ServerBootstrap server = serverResolver.resolve(); server.setPipelineFactory(pipelineFactory(pipeline(closeOnExceptionHandler))); } catch (RuntimeException e) { LOGGER.warn("Exception caught while trying to stop server pipelies", e); } } for (ClientBootstrapResolver clientResolver : configuration.getClientResolvers()) { try { ClientBootstrap client = clientResolver.resolve(); client.setPipelineFactory(pipelineFactory(pipeline(closeOnExceptionHandler))); } catch (RuntimeException e) { LOGGER.warn("Exception caught while trying to stop client pipelies", e); } } for (ChannelPipeline pipeline : configuration.getClientAndServerPipelines()) { stopStream(pipeline); } for (ChannelFuture bindFuture : bindFutures) { bindFuture.cancel(); } for (ChannelFuture connectFuture : connectFutures) { if (connectFuture.cancel()) { LOGGER.debug("Cancelled connect future: " + connectFuture.getChannel().getRemoteAddress()); } } } }
Source:
private static String getFilePath(String line, int strip, Path outputDirectory) { String file = null; line = line.split("\t")[0]; if (line.length() > 4) { file = stripPath(line.substring(4), strip); file = outputDirectory.getRelative(file).getPathString(); } return file; }

Target:
private static Path getFilePath(String line, int strip, Path outputDirectory) { String file = null; line = line.split("\t")[0]; if (line.length() > 4) { if (line.substring(4).trim().equals("/dev/null")) { return null; } file = stripPath(line.substring(4), strip); if (!file.isEmpty()) { return outputDirectory.getRelative(file); } } return null; }
Source:
private ArrayList<ArrayList> loadFromEf(int efType) { ArrayList<ArrayList> results = new ArrayList<ArrayList>(); List<AdnRecord> adnRecords = null; AdnComparator adnComparator = new AdnComparator(); if (DBG) log("loadFromEf: efType=" + efType); try { IIccPhoneBook iccIpb = IIccPhoneBook.Stub.asInterface( ServiceManager.getService("simphonebook")); if (iccIpb != null) { adnRecords = iccIpb.getAdnRecordsInEf(efType); } } catch (RemoteException ex) { } catch (SecurityException ex) { if (DBG) log(ex.toString()); } if (adnRecords != null) { int N = adnRecords.size(); if (DBG) log("adnRecords.size=" + N); List<AdnRecord> newAdn = new ArrayList<AdnRecord>(); for (int i = 0; i < N; i++) { AdnRecord record = adnRecords.get(i); if (!record.isEmpty()) { newAdn.add(record); } } Collections.sort(newAdn, adnComparator); if (DBG) log("loadFromEf: results =" + newAdn); N = newAdn.size(); for (int i = 0; i < N; i++) { loadRecord((AdnRecord) newAdn.get(i), results); } } else { Log.w(TAG, "Cannot load ADN records"); results.clear(); } if (DBG) log("loadFromEf: return results"); return results; }

Target:
private ArrayList<ArrayList> loadFromEf(int efType) { ArrayList<ArrayList> results = new ArrayList<ArrayList>(); List<AdnRecord> adnRecords = null; AdnComparator adnComparator = new AdnComparator(); if (DBG) log("loadFromEf: efType=" + efType); try { IIccPhoneBook iccIpb = IIccPhoneBook.Stub.asInterface( ServiceManager.getService("simphonebook")); if (iccIpb != null) { adnRecords = iccIpb.getAdnRecordsInEf(efType); } } catch (RemoteException ex) { } catch (SecurityException ex) { if (DBG) log(ex.toString()); } if (adnRecords != null) { List<AdnRecord> newAdn = new ArrayList<AdnRecord>(); for (AdnRecord record : adnRecords) { if (!record.isEmpty()) { newAdn.add(record); } } Collections.sort(newAdn, adnComparator); if (DBG) log("loadFromEf: results =" + newAdn); for (AdnRecord record : newAdn) { loadRecord(record, results); } } else { Log.w(TAG, "Cannot load ADN records"); results.clear(); } if (DBG) log("loadFromEf: return results"); return results; }
Source:
public void setViewStartY(int viewStartY) { if (viewStartY > mMaxViewStartY) { mViewStartY = mMaxViewStartY; } else if (viewStartY < 0) { mViewStartY = 0; } else { mViewStartY = viewStartY; } if (DEBUG_SCROLLING) Log.e(TAG, "setViewStartY 1099: mViewStartY=" + mViewStartY); computeFirstHour(); invalidate(); }

Target:
public void setViewStartY(int viewStartY) { if (viewStartY > mMaxViewStartY) { mViewStartY = mMaxViewStartY; } else if (viewStartY < 0) { mViewStartY = 0; } else { mViewStartY = viewStartY; } computeFirstHour(); invalidate(); }
Source:
public Format getFormat() { return new Format(){ private final Format delegateFormat = delegate.getFormat(); @Override public ParameterValueGroup getWriteParameters() { return delegateFormat.getWriteParameters(); } @Override public String getVersion() { return delegateFormat.getVersion(); } @Override public String getVendor() { return delegateFormat.getVendor(); } @Override public ParameterValueGroup getReadParameters() { HashMap<String, String> info = new HashMap<String, String>(); info.put("name", getName()); info.put("description", getDescription()); info.put("vendor", getVendor()); info.put("docURL", getDocURL()); info.put("version", getVersion()); return new ParameterGroup( new DefaultParameterDescriptorGroup( info, new GeneralParameterDescriptor[] { AbstractGridFormat.BANDS })); } @Override public String getName() { return delegateFormat.getName(); } @Override public String getDocURL() { return delegateFormat.getDocURL(); } @Override public String getDescription() { return delegateFormat.getDescription(); } }; }

Target:
public Format getFormat() { return new Format(){ private final Format delegateFormat = delegate.getFormat(); @Override public ParameterValueGroup getWriteParameters() { return delegateFormat.getWriteParameters(); } @Override public String getVersion() { return delegateFormat.getVersion(); } @Override public String getVendor() { return delegateFormat.getVendor(); } @Override public ParameterValueGroup getReadParameters() { HashMap<String, String> info = new HashMap<String, String>(); info.put("name", getName()); info.put("description", getDescription()); info.put("vendor", getVendor()); info.put("docURL", getDocURL()); info.put("version", getVersion()); List<GeneralParameterDescriptor> delegateFormatParams = new ArrayList<GeneralParameterDescriptor>(); delegateFormatParams.addAll( delegateFormat.getReadParameters().getDescriptor().descriptors()); delegateFormatParams.add(AbstractGridFormat.BANDS); return new ParameterGroup(new DefaultParameterDescriptorGroup( info, delegateFormatParams.toArray( new GeneralParameterDescriptor[delegateFormatParams.size()]))); } @Override public String getName() { return delegateFormat.getName(); } @Override public String getDocURL() { return delegateFormat.getDocURL(); } @Override public String getDescription() { return delegateFormat.getDescription(); } }; }
Source:
public void joinAsGuest(BorderPane gameBox, String nickname) { if (nickname.length() == 0) { nickname = "Anon"; } try { clientPlayer = new Player(ibs.newGuest(nickname)); joinGame(gameBox); } catch (RemoteException e) { e.printStackTrace(); } }

Target:
public void joinAsGuest(BorderPane gameBox, String nickname) { try { clientPlayer = new Player(ibs.newGuest(nickname)); joinGame(gameBox); } catch (RemoteException e) { e.printStackTrace(); } }
Source:
public void setUp() throws IOException { af = File.createTempFile("AtomicFileWriter", ".tmp"); afw = new AtomicFileWriter(af, Charset.defaultCharset()); }

Target:
public void setUp() throws IOException { af = tmp.newFile(); afw = new AtomicFileWriter(af.toPath(), Charset.defaultCharset()); }
Source:
protected Set<Pair<MetricNameDto, List<PlotDatasetDto>>> fetchData(List<MetricNameDto> metricNames) { if (metricNames.isEmpty()) { return Collections.emptySet(); } Collection<MetricRawData> allRawData = getAllRawData(metricNames); if (allRawData.isEmpty()) { log.warn("No plot data found for metrics : {}", metricNames); return Collections.emptySet(); } Map<Long, Multimap<String, MetricRawData>> taskIdMetricIdRawMap = createMappedPlotDatasets(metricNames); for (MetricRawData rawData : allRawData) { String metricId = rawData.getMetricId(); Long taskId = rawData.getWorkloadTaskDataId(); taskIdMetricIdRawMap.get(taskId).put(metricId, rawData); } Multimap<MetricNameDto, PlotDatasetDto> metricNamePlotMap = ArrayListMultimap.create(); for (MetricNameDto metricName : metricNames) { for (Long taskId : metricName.getTaskIds()) { Collection<MetricRawData> rawDatas; try { rawDatas = taskIdMetricIdRawMap.get(taskId).get(metricName.getMetricName()); if (rawDatas.isEmpty()) { continue; } } catch (NullPointerException e) { continue; } metricNamePlotMap.put(metricName, assemble(metricName, rawDatas)); } } Set<Pair<MetricNameDto, List<PlotDatasetDto>>> resultSet = new HashSet<Pair<MetricNameDto, List<PlotDatasetDto>>>(metricNames.size()); for (MetricNameDto metricName : metricNamePlotMap.keySet()) { List<PlotDatasetDto> plotDatasetDtoList = new ArrayList<PlotDatasetDto>(metricNamePlotMap.get(metricName)); resultSet.add( Pair.of( metricName, plotDatasetDtoList )); } return resultSet; }

Target:
protected Set<Pair<MetricNameDto, List<PlotDatasetDto>>> fetchData(List<MetricNameDto> metricNames) { if (metricNames.isEmpty()) { return Collections.emptySet(); } Collection<MetricRawData> allRawData = getAllRawData(metricNames); if (allRawData.isEmpty()) { log.warn("No plot data found for metrics : {}", metricNames); return Collections.emptySet(); } Map<Long, Multimap<String, MetricRawData>> taskIdMetricIdRawMap = createMappedPlotDatasets(metricNames); for (MetricRawData rawData : allRawData) { String metricId = rawData.getMetricId(); Long taskId = rawData.getWorkloadTaskDataId(); taskIdMetricIdRawMap.get(taskId).put(metricId, rawData); } Multimap<MetricNameDto, PlotDatasetDto> metricNamePlotMap = ArrayListMultimap.create(); for (MetricNameDto metricName : metricNames) { for (Long taskId : metricName.getTaskIds()) { Collection<MetricRawData> rawDatas; Multimap<String, MetricRawData> multimap = taskIdMetricIdRawMap.get(taskId); if (multimap == null) { continue; } rawDatas = multimap.get(metricName.getMetricName()); if (rawDatas == null || rawDatas.isEmpty()) { continue; } metricNamePlotMap.put(metricName, assemble(metricName, rawDatas)); } } Set<Pair<MetricNameDto, List<PlotDatasetDto>>> resultSet = new HashSet<Pair<MetricNameDto, List<PlotDatasetDto>>>(metricNames.size()); for (MetricNameDto metricName : metricNamePlotMap.keySet()) { List<PlotDatasetDto> plotDatasetDtoList = new ArrayList<PlotDatasetDto>(metricNamePlotMap.get(metricName)); resultSet.add( Pair.of( metricName, plotDatasetDtoList )); } return resultSet; }