auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public String executeNeo4jQuery(String queryName, Map<String, String> parameters, String returnType) throws AsyncExecutionException { String query = env.getProperty(queryName); if (parameters != null) { for (String paraName : parameters.keySet()) { query = query.replace("{" + paraName + "}", "'"+parameters.get(paraName)+"'"); } } logger.debug("Running query: " + query); ResponseEntity<String> response = executeQuery(query, returnType); HttpStatus status = response.getStatusCode(); String resbody = response.getBody(); if (status == HttpStatus.BAD_REQUEST || status == HttpStatus.INTERNAL_SERVER_ERROR) { String errorMessage = resbody.substring(resbody.indexOf("<message>"), resbody.indexOf("</message>")); throw new AsyncExecutionException(errorMessage); } QStoreAsyncResult asyncResult = getResponseFromXML(resbody); String pollURL = asyncResult.getPollurl(); long delay = Long.parseLong(env.getProperty("qstore.rest.delay")); String res = getQueryResult(pollURL); asyncResult = getResponseFromXML(res); while (asyncResult != null && asyncResult.getQueryStatus().equals(RUNNING.name())) { try { Thread.sleep(delay); res = getQueryResult(pollURL); asyncResult = getResponseFromXML(res); } catch (InterruptedException e) { throw new AsyncExecutionException(e); } } return asyncResult.getResult(); }

Target:
public String executeNeo4jQuery(String queryName, Map<String, String> parameters, String returnType) throws AsyncExecutionException { String query = env.getProperty(queryName); if (parameters != null) { for (String paraName : parameters.keySet()) { query = query.replace("{" + paraName + "}", parameters.get(paraName)); } } logger.debug("Running query: " + query); ResponseEntity<String> response = executeQuery(query, returnType); HttpStatus status = response.getStatusCode(); String resbody = response.getBody(); if (status == HttpStatus.BAD_REQUEST || status == HttpStatus.INTERNAL_SERVER_ERROR) { String errorMessage = resbody.substring(resbody.indexOf("<message>"), resbody.indexOf("</message>")); throw new AsyncExecutionException(errorMessage); } QStoreAsyncResult asyncResult = getResponseFromXML(resbody); String pollURL = asyncResult.getPollurl(); long delay = Long.parseLong(env.getProperty("qstore.rest.delay")); String res = getQueryResult(pollURL); asyncResult = getResponseFromXML(res); while (asyncResult != null && asyncResult.getQueryStatus().equals(RUNNING.name())) { try { Thread.sleep(delay); res = getQueryResult(pollURL); asyncResult = getResponseFromXML(res); } catch (InterruptedException e) { throw new AsyncExecutionException(e); } } return asyncResult.getResult(); }
Source:
public static void setDonationURL() { try { Class donationManager = Class.forName("openblocks.common.DonationURLManager"); Method instance = donationManager.getMethod("instance"); Method url = donationManager.getMethod("addUrl"); url.invoke(instance.invoke(null),Reference.ID,"<LINK_0>"); } catch (Exception e) { e.printStackTrace(); } }

Target:
public static void setDonationURL() { try { Class donationManager = Class.forName("openblocks.common.DonationURLManager"); Method instance = donationManager.getMethod("instance"); Method url = donationManager.getMethod("addUrl"); url.invoke(instance.invoke(null),Reference.ID,"<LINK_1>"); } catch (Exception e) { e.printStackTrace(); } }
Source:
public void shouldNotCloseTaskWithinCommitIfTaskMigratedException() { mockTaskInitialization(); EasyMock.expect(t1.commitNeeded()).andReturn(true); t1.commit(); EasyMock.expectLastCall().andThrow(new TaskMigratedException()); EasyMock.replay(t1); addAndInitTask(); try { assignedTasks.commit(); fail("Should have thrown TaskMigratedException."); } catch (final TaskMigratedException expected) { assertThat(assignedTasks.runningTaskIds(), equalTo(Collections.singleton(taskId1))); } EasyMock.verify(t1); }

Target:
public void shouldNotCloseTaskWithinCommitIfTaskMigratedException() { mockTaskInitialization(); EasyMock.expect(t1.commitNeeded()).andReturn(true); t1.commit(); EasyMock.expectLastCall().andThrow(new TaskMigratedException()); EasyMock.replay(t1); addAndInitTask(); verifyTaskMigratedExceptionDoesNotCloseTask( () -> assignedTasks.commit()); }
Source:
private DistStageAck executeStreamTask(Statistics stats) { long durationNanos; long start; configureStreamTask(); StreamStageAck ack = new StreamStageAck(slaveState); try { start = TimeService.nanoTime(); streamTaskResult = function.apply(streamable.stream(cacheName)); durationNanos = TimeService.nanoTime() - start; stats.registerRequest(durationNanos, Streamable.STREAMABLE); log.info("Stream task completed in " + Utils.prettyPrintTime(durationNanos, TimeUnit.NANOSECONDS)); long resultCount = function.getResultCount(); log.info("Result map contains '" + resultCount + "' keys."); ack.setNumberOfResultKeys(resultCount); ack.setStats(stats); String printableResult = function.getPrintableResult(); if (printResult && printableResult != null) { log.info("Stream task result:"); log.info(printableResult); } } catch (Exception e) { ack.error("executeStreamTask() threw an exception", e); log.error("executeStreamTask() returned an exception", e); } log.infof("%d nodes were used. %d entries on this node", clustered.getMembers().size(), cacheInformation .getCache(cacheName).getLocallyStoredSize()); log.info("--------------------"); return ack; }

Target:
private DistStageAck executeStreamTask(Statistics stats) { long durationNanos; long start; configureStreamTask(); StreamStageAck ack = new StreamStageAck(slaveState); start = TimeService.nanoTime(); try { if (parallelStream) { streamTaskResult = function.apply(streamable.parallelStream(cacheName)); } else { streamTaskResult = function.apply(streamable.stream(cacheName)); } durationNanos = TimeService.nanoTime() - start; stats.registerRequest(durationNanos, Streamable.STREAMABLE); log.info("Stream task completed in " + Utils.prettyPrintTime(durationNanos, TimeUnit.NANOSECONDS)); long resultCount = function.getResultCount(); log.info("Result map contains '" + resultCount + "' keys."); ack.setNumberOfResultKeys(resultCount); ack.setStats(stats); if (printResult) { String printableResult = function.getPrintableResult(); if (printableResult != null) { log.info("Stream task result:" + printableResult); } } } catch (Exception e) { durationNanos = TimeService.nanoTime() - start; stats.registerError(durationNanos, Streamable.STREAMABLE); ack.error("executeStreamTask() threw an exception", e); log.error("executeStreamTask() returned an exception", e); } if (clustered != null && cacheInformation != null){ log.infof("%d nodes were used. %d entries on this node", clustered.getMembers().size(), cacheInformation .getCache(cacheName).getLocallyStoredSize()); } log.info("--------------------"); return ack; }
Source:
private static String getGerritHost(String canonicalWebUrl) { String host = null; if (canonicalWebUrl != null) { try { host = new URL(canonicalWebUrl).getHost(); } catch (MalformedURLException e) { } } if (host == null) { host = SystemReader.getInstance().getHostname(); } return trimTrailingSlashes(host); }

Target:
private static String getGerritHost(String canonicalWebUrl) { String host; if (canonicalWebUrl != null) { try { host = new URL(canonicalWebUrl).getHost(); } catch (MalformedURLException e) { host = SystemReader.getInstance().getHostname(); } } else { host = SystemReader.getInstance().getHostname(); } return host; }
Source:
public void testIndivisibleMiniBatchSize() { final Random generator = new Random(); final int numTotalMiniBatches = 5; final int numRemainderForLastMiniBatch = (MINI_BATCH_SIZE - 2); final int numTotalInstances = MINI_BATCH_SIZE * (numTotalMiniBatches - 1) + numRemainderForLastMiniBatch; for (int i = 0; i < numTotalInstances; i++) { final int value = generator.nextInt(); values.put(i, value); } trainingDataProvider.prepareDataForEpoch(); assertTrue(numTotalInstances % MINI_BATCH_SIZE != 0); int miniBatchCount = 0; Map<Integer, Integer> trainingData = trainingDataProvider.getNextTrainingData(); while (!trainingData.isEmpty()) { miniBatchCount++; for (final Integer key : trainingData.keySet()) { assertEquals(values.get(key), trainingData.get(key)); } if (miniBatchCount < numTotalMiniBatches) { assertEquals("Should process MINI_BATCH_SIZE instances", MINI_BATCH_SIZE, trainingData.size()); } else { assertEquals("The last mini-batch should process remaining instances", numRemainderForLastMiniBatch, trainingData.size()); } trainingData = trainingDataProvider.getNextTrainingData(); } assertEquals("The total number of mini-batches is different from expectation", numTotalMiniBatches, miniBatchCount); }

Target:
public void testIndivisibleMiniBatchSize() { final int numTotalInstances = 23; createMockTrainingData(numTotalInstances); trainingDataProvider.prepareDataForEpoch(); testGetNextTrainingData(numTotalInstances); assertTrue("Data should be exhausted", trainingDataProvider.getNextTrainingData().isEmpty()); trainingDataProvider.prepareDataForEpoch(); testGetNextTrainingData(numTotalInstances); assertTrue("Data should be exhausted", trainingDataProvider.getNextTrainingData().isEmpty()); }
Source:
public void testFullByonLocationDescription() { String templateUrl = getClasspathUrlForResource("templates/full-location.byon.tosca.yaml"); EntitySpec<? extends Application> app = transformer.createApplicationSpec( new ResourceUtils(mgmt).getResourceAsString(templateUrl)); assertNotNull(app); assertEquals(app.getChildren().size(), 1); EntitySpec<VanillaSoftwareProcess> vanillaEntity = (EntitySpec<VanillaSoftwareProcess>) Iterables.getOnlyElement(app.getChildren()); assertEquals(vanillaEntity.getLocations().size(), 1); assertTrue(Iterables.getOnlyElement(vanillaEntity.getLocations()) instanceof FixedListMachineProvisioningLocation); FixedListMachineProvisioningLocation location = (FixedListMachineProvisioningLocation) Iterables .getOnlyElement(vanillaEntity.getLocations()); Map<String, Object> configByon = location.getLocalConfigBag().getAllConfig(); assertEquals(configByon.get("user"), "brooklyn"); assertEquals(configByon.get("provider"), "byon"); assertEquals(configByon.get("provider"), "byon"); assertEquals(((List)configByon.get("machines")).size(), 1); List<SshMachineLocation> machines = (List<SshMachineLocation>) configByon.get("machines"); assertEquals(machines.get(0).getAddress().getHostAddress(), "192.168.0.18"); }

Target:
public void testFullByonLocationDescription() { String templateUrl = getClasspathUrlForResource("templates/full-location.byon.tosca.yaml"); EntitySpec<? extends Application> app = transformer.createApplicationSpec( new ResourceUtils(mgmt).getResourceAsString(templateUrl)); assertNotNull(app); assertEquals(app.getChildren().size(), 1); EntitySpec<VanillaSoftwareProcess> vanillaEntity = (EntitySpec<VanillaSoftwareProcess>) Iterables.getOnlyElement(app.getChildren()); assertEquals(vanillaEntity.getLocations().size(), 1); assertTrue(Iterables.getOnlyElement(vanillaEntity.getLocations()) instanceof FixedListMachineProvisioningLocation); FixedListMachineProvisioningLocation location = (FixedListMachineProvisioningLocation) Iterables .getOnlyElement(vanillaEntity.getLocations()); Map<String, Object> configByon = location.getLocalConfigBag().getAllConfig(); assertEquals(configByon.get("user"), "brooklyn"); assertEquals(configByon.get("provider"), "byon"); assertTrue(configByon.get("machines") instanceof Collection); assertEquals(((Collection)configByon.get("machines")).size(), 1); List<SshMachineLocation> machines = (List<SshMachineLocation>) configByon.get("machines"); assertEquals(machines.get(0).getAddress().getHostAddress(), "192.168.0.18"); }
Source:
public ExpirationManager getExpirationManager() { return this.expirationManager; }

Target:
public ExpirationManager getExpirationManager() { return expirationManager; }
Source:
public void in(String in) { this.latch.countDown(); if ("nackIt".equals(in)) { throw new RuntimeException("testing auto nack"); } else { this.received = in; } }

Target:
public void in(String in) { try { if ("nackIt".equals(in)) { throw new RuntimeException("testing auto nack"); } else { this.received = in; } } finally { this.latch.countDown(); } }
Source:
public void activateHoverHelp(final Control control) { control.addMouseListener(new MouseAdapter() { @Override public void mouseDown(MouseEvent e) { if (fTipShell != null && !fTipShell.isDisposed()) { fTipShell.dispose(); } } }); control.addMouseMoveListener(e -> { if (fTipShell != null && !fTipShell.isDisposed()) { fTipShell.dispose(); } }); control.addMouseTrackListener(new MouseTrackAdapter() { @Override public void mouseExit(MouseEvent e) { Point pt = control.toDisplay(e.x, e.y); if (fTipShell != null && !fTipShell.isDisposed() && !fTipShell.getBounds().contains(pt)) { fTipShell.dispose(); } } @Override public void mouseHover(MouseEvent event) { if ((event.stateMask & SWT.BUTTON_MASK) != 0) { return; } Point pt = new Point(event.x, event.y); Control timeGraphControl = (Control) event.widget; createTooltipShell(timeGraphControl.getShell()); for (Control child : fTipComposite.getChildren()) { child.dispose(); } fill(control, event, pt); fTipShell.pack(); Point tipPosition = control.toDisplay(pt); fTipShell.pack(); setHoverLocation(fTipShell, tipPosition); if (fTipComposite.getChildren().length > 0) { fTipShell.setVisible(true); } } }); }

Target:
public void activateHoverHelp(final Control control) { control.addMouseListener(new MouseAdapter() { @Override public void mouseDown(MouseEvent e) { if (fTipShell != null && !fTipShell.isDisposed()) { fTipShell.dispose(); } } }); control.addMouseMoveListener(e -> { if (fTipShell != null && !fTipShell.isDisposed()) { fTipShell.dispose(); } }); control.addMouseTrackListener(new MouseTrackAdapter() { @Override public void mouseExit(MouseEvent e) { Point pt = control.toDisplay(e.x, e.y); if (fTipShell != null && !fTipShell.isDisposed() && !fTipShell.getBounds().contains(pt)) { fTipShell.dispose(); } } @Override public void mouseHover(MouseEvent event) { if ((event.stateMask & SWT.BUTTON_MASK) != 0) { return; } Point pt = new Point(event.x, event.y); Control timeGraphControl = (Control) event.widget; createTooltipShell(timeGraphControl.getShell()); for (Control child : fTipComposite.getChildren()) { child.dispose(); } fill(control, event, pt); if (fTipComposite.getChildren().length == 0) { return; } fTipShell.pack(); Point tipPosition = control.toDisplay(pt); setHoverLocation(fTipShell, tipPosition); fTipShell.setVisible(true); } }); }
Source:
public boolean start() throws IOException { connection = source.connect(container); result = new Result(); Schema schema = rowProperties.schemaFlow.schema.getValue(); if (AvroUtils.isIncludeAllFields(schema)) { schema = source.getEndpointSchema(container, rowProperties.table.tableName.getValue()); } factory.setSchema(schema); try { if (rowProperties.usePreparedStatement.getValue()) { statement = connection.prepareStatement(rowProperties.query.getValue()); PreparedStatement pstmt = (PreparedStatement) statement; SnowflakePreparedStatementUtils.fillPreparedStatement(pstmt, rowProperties.preparedStatementTable); pstmt.execute(); rs = pstmt.getResultSet(); pstmt.clearParameters(); } else { statement = connection.createStatement(); rs = statement.executeQuery(rowProperties.query.getValue()); } } catch (SQLException e) { throw new IOException(e); } return advance(); }

Target:
public boolean start() throws IOException { connection = source.createConnection(container); result = new Result(); Schema schema = source.getRuntimeSchema(container); converter.setSchema(schema); try { if (source.usePreparedStatement()) { statement = connection.prepareStatement(source.getQuery()); PreparedStatement pstmt = (PreparedStatement) statement; SnowflakePreparedStatementUtils.fillPreparedStatement(pstmt, source.getRowProperties().preparedStatementTable); pstmt.execute(); rs = pstmt.getResultSet(); pstmt.clearParameters(); } else { statement = connection.createStatement(); rs = statement.executeQuery(source.getQuery()); } } catch (SQLException e) { throw new IOException(e); } return advance(); }
Source:
public String createStyledText() { if (!StringUtility.hasText(getText())) { setText("<!-- -->"); } String styledText = getText().trim(); boolean originalTextIsHTML = false; if (HTML_PATTERN.matcher(styledText).matches()) { styledText = StringUtility.getTag(styledText, "html"); originalTextIsHTML = true; } if (BODY_PATTERN.matcher(styledText).matches()) { styledText = StringUtility.getTag(styledText, "body"); } String align = "left"; String valign = "top"; if (getHorizontalAlignment() == SwingConstants.HORIZONTAL) { align = "center"; } else if (getHorizontalAlignment() == SwingConstants.RIGHT) { align = "right"; } if (getVerticalAlignment() == SwingConstants.CENTER) { valign = "middle"; } else if (getVerticalAlignment() == SwingConstants.BOTTOM) { valign = "bottom"; } String wrapText = "normal"; if (!isTextWrap()) { wrapText = "nowrap"; } String bodyStyle = ""; if (StringUtility.hasText(ColorUtility.createStringFromColor(getBackgroundColor()))) { bodyStyle += "background-color: " + ColorUtility.createStringFromColor(getBackgroundColor()) + ";"; } if (StringUtility.hasText(ColorUtility.createStringFromColor(getForegroundColor()))) { bodyStyle += "color: " + ColorUtility.createStringFromColor(getForegroundColor()) + ";"; } if (!originalTextIsHTML) { styledText = StringUtility.replaceNewLines(styledText, "<br>"); } styledText = "<html><body style=\"" + bodyStyle + "\"><div align=\"" + align + "\"><table cellpadding=\"0\" cellspacing=\"0\"><tr><td valign=\"" + valign + "\" height=\"" + getHeight() + "px\" style=\"white-space:" + wrapText + ";\">" + styledText + "</td></tr></table></div></body></html>"; return styledText; }

Target:
public String createStyledText() { if (!StringUtility.hasText(getText())) { setText("<!-- -->"); } String styledText = getText().trim(); boolean originalTextIsHTML = false; if (HTML_PATTERN.matcher(styledText).matches()) { styledText = StringUtility.getTag(styledText, "html"); originalTextIsHTML = true; } if (BODY_PATTERN.matcher(styledText).matches()) { styledText = StringUtility.getTag(styledText, "body"); } if (!originalTextIsHTML) { styledText = StringUtility.replaceNewLines(styledText, "<br>"); } styledText = "<html><body style=\"" + getBodyStyle() + "\"><div align=\"" + getAlign() + "\"><table cellpadding=\"0\" cellspacing=\"0\"><tr><td valign=\"" + getValign() + "\" height=\"" + getHeight() + "px\" style=\"white-space:" + getWrapText() + ";\">" + styledText + "</td></tr></table></div></body></html>"; return styledText; }
Source:
public static Container fromJson(JSONObject json, short parentAccountId) throws JSONException { return new Container(json, parentAccountId); }

Target:
static Container fromJson(JSONObject json, short parentAccountId) throws JSONException { return new Container(json, parentAccountId); }
Source:
private static <T> Publisher<Message<T>> adaptSubscribableChannelToPublisher(SubscribableChannel inputChannel) { EmitterProcessor<Message<T>> publisher = EmitterProcessor.create(1); @SuppressWarnings("unchecked") MessageHandler messageHandler = (message) -> publisher.onNext((Message<T>) message); return publisher .doOnSubscribe((sub) -> inputChannel.subscribe(messageHandler)) .doOnCancel(() -> inputChannel.unsubscribe(messageHandler)); }

Target:
private static <T> Publisher<Message<T>> adaptSubscribableChannelToPublisher(SubscribableChannel inputChannel) { return Flux.defer(() -> { EmitterProcessor<Message<T>> publisher = EmitterProcessor.create(1); @SuppressWarnings("unchecked") MessageHandler messageHandler = (message) -> publisher.onNext((Message<T>) message); inputChannel.subscribe(messageHandler); return publisher .doOnCancel(() -> inputChannel.unsubscribe(messageHandler)); }); }
Source:
private List<YamlPreference> jsonToYamlPreference(String jsonStr) { ArrayList yamlPreferences = new ArrayList<YamlPreference>(); JsonObject parsedJson = Json.parse(jsonStr); for (String glob : parsedJson.keys()) { try { JsonArray jsonArray = parsedJson.getArray(glob); for (int arrNum = 0; arrNum < jsonArray.length(); arrNum++) { YamlPreference newYamlPref = new YamlPreference(jsonArray.getString(arrNum), glob); yamlPreferences.add(newYamlPref); } } catch (Exception e) { System.out.println(e); } } return yamlPreferences; }

Target:
private List<YamlPreference> jsonToYamlPreference(String jsonStr) { ArrayList yamlPreferences = new ArrayList<YamlPreference>(); JsonObject parsedJson = Json.parse(jsonStr); for (String glob : parsedJson.keys()) { try { JsonArray jsonArray = parsedJson.getArray(glob); for (int arrNum = 0; arrNum < jsonArray.length(); arrNum++) { YamlPreference newYamlPref = new YamlPreference(jsonArray.getString(arrNum), glob); yamlPreferences.add(newYamlPref); } } catch (Exception e) { LOG.debug(e.getMessage(), e); } } return yamlPreferences; }
Source:
public MqttConnectOptions getConnectionInfo() { MqttConnectOptions options = this.clientFactory.getConnectionOptions(); if (options.getServerURIs() == null && getUrl() != null) { options = MqttUtils.cloneConnectOptions(options); options.setServerURIs(new String[] { getUrl() }); } return options; }

Target:
public MqttConnectOptions getConnectionInfo() { MqttConnectOptions options = this.clientFactory.getConnectionOptions(); if (options.getServerURIs() == null) { String url = getUrl(); if (url != null) { options = MqttUtils.cloneConnectOptions(options); options.setServerURIs(new String[] { url }); } } return options; }
Source:
public void dispose() { refreshable = false; refreshTask.cancel(false); }

Target:
public void dispose() { refreshable = false; if (!refreshTask.isCancelled()) { refreshTask.cancel(false); } }
Source:
private String encryptDecryptPassword( String source, EncryptDirection direction ) { try { URI uri = new URI( source ); String userInfo = uri.getUserInfo(); if ( userInfo != null ) { String[] userInfoArray = userInfo.split( ":", 2 ); String password = userInfoArray[ 1 ]; String processedPassword = password; if ( direction == EncryptDirection.ENCRYPT ) { processedPassword = Encr.encryptPassword( password ); } else if ( direction == EncryptDirection.DECRYPT ) { processedPassword = Encr.decryptPassword( password ); } URI encryptedUri = new URI( uri.getScheme(), userInfoArray[ 0 ] + ":" + processedPassword, uri.getHost(), uri.getPort(), uri.getPath(), uri.getQuery(), uri.getFragment() ); return encryptedUri.toString(); } } catch ( Exception e ) { return source; } return source; }

Target:
private String encryptDecryptPassword( String source, EncryptDirection direction ) { Validate.notNull( direction, "'direction' must not be null" ); try { URI uri = new URI( source ); String userInfo = uri.getUserInfo(); if ( userInfo != null ) { String[] userInfoArray = userInfo.split( ":", 2 ); String password = userInfoArray[ 1 ]; String processedPassword = password; switch ( direction ) { case ENCRYPT: processedPassword = Encr.encryptPassword( password ); break; case DECRYPT: processedPassword = Encr.decryptPassword( password ); break; default: throw new InvalidParameterException( "direction must be 'ENCODE' or 'DECODE'" ); } URI encryptedUri = new URI( uri.getScheme(), userInfoArray[ 0 ] + ":" + processedPassword, uri.getHost(), uri.getPort(), uri.getPath(), uri.getQuery(), uri.getFragment() ); return encryptedUri.toString(); } } catch ( URISyntaxException e ) { return source; } return source; }
Source:
public String toString() { StringBuilder sb = new StringBuilder(); sb.append("dr=").append(region.getDiskRegion().getId()); sb.append(" versionOnly=").append(this.versionOnly); if (this.versionOnly) { sb.append(" versionTag=").append(this.tag); } if (de != null) { sb.append(" key=").append(de.getKey()); } else { sb.append(" <END CLEAR_REGION>"); } return sb.toString(); }

Target:
public String toString() { StringBuilder sb = new StringBuilder(); sb.append("dr=").append(region.getDiskRegion().getId()); sb.append(" versionOnly=").append(this.versionOnly); if (this.versionOnly) { sb.append(" versionTag=").append(this.tag); } if (de != null) { sb.append(" key=").append(de.getKey()); } else { sb.append(" <END CLEAR>"); } return sb.toString(); }
Source:
public IStyledString.IComposedStyledString getStyledText(Object object) { Conflict conflict = (Conflict)object; ComposedStyledString ret = new ComposedStyledString(); boolean unresolvedConflict = any(conflict.getDifferences(), EMFComparePredicates .hasState(DifferenceState.UNRESOLVED)); if (unresolvedConflict) { ret.append("> ", Style.DECORATIONS_STYLER); } if (conflict.getKind() == ConflictKind.PSEUDO) { ret.append(EMFCompareEditMessages.getString("pseudoconflict")); } else { ret.append(EMFCompareEditMessages.getString("conflict")); } if (unresolvedConflict) { final int differencesToMerge = size(Iterables.filter(conflict.getDifferences(), hasState(DifferenceState.UNRESOLVED))); ret.append( " [" + EMFCompareEditMessages.getString("unresolved", differencesToMerge, conflict.getDifferences().size()) + "]", Style.DECORATIONS_STYLER); } else { ret.append(" [" + EMFCompareEditMessages.getString("resolved") + "]", Style.DECORATIONS_STYLER); } return ret; }

Target:
public IStyledString.IComposedStyledString getStyledText(Object object) { Conflict conflict = (Conflict)object; ComposedStyledString ret = new ComposedStyledString(); int unresolvedDiffCount = size(Iterables.filter(conflict.getDifferences(), hasState(DifferenceState.UNRESOLVED))); if (unresolvedDiffCount > 0) { ret.append("> ", Style.DECORATIONS_STYLER); } if (conflict.getKind() == ConflictKind.PSEUDO) { ret.append(EMFCompareEditMessages.getString("pseudoconflict")); } else { ret.append(EMFCompareEditMessages.getString("conflict")); } if (unresolvedDiffCount > 0) { ret.append( " [" + EMFCompareEditMessages.getString("unresolved", unresolvedDiffCount, conflict.getDifferences().size()) + "]", Style.DECORATIONS_STYLER); } else { ret.append(" [" + EMFCompareEditMessages.getString("resolved") + "]", Style.DECORATIONS_STYLER); } return ret; }
Source:
private void printUPNToResponse(HttpServletResponse response, String upn) { PrintWriter out; try { out = response.getWriter(); out.print(upn); } catch (IOException e) { log.error("IO Exception while writing user name: ", e); } }

Target:
private void printUPNToResponse(HttpServletResponse response, String upn) { try { response.getWriter().print(upn); } catch (IOException e) { log.error("IO Exception while writing user name: ", e); } }
Source:
public static void main(String[] args) { Cli<Runnable> parser = Cli.<Runnable>builder("verifier") .withDescription("Presto Verifier") .withDefaultCommand(Help.class) .withCommand(Help.class) .withCommand(GenerateReleaseNotesCommand.class) .build(); parser.parse(args).run(); }

Target:
public static void main(String[] args) { Cli<Runnable> parser = Cli.<Runnable>builder("release") .withDescription("Presto Release") .withDefaultCommand(Help.class) .withCommand(Help.class) .withCommand(GenerateReleaseNotesCommand.class) .build(); parser.parse(args).run(); }
Source:
public void testUpdateSchema() { DefaultTableSchemaUpdater schemaUpdater = new DefaultTableSchemaUpdater(); AssistantApp app = new AssistantApp(getInstrumentation().getTargetContext().getApplicationContext()); TestTable testTable = new TestTable(app, DATABASE_NAME, TABLE_NAME, TABLE_VERSION, Arrays.<com.sarality.app.datastore.Column> asList(Column.values()), null, null, schemaUpdater); TestOnlineHelper onlineHelper = new TestOnlineHelper(getInstrumentation().getTargetContext().getApplicationContext(), null, null, TABLE_VERSION); SQLiteDatabase db = onlineHelper.getWritableDatabase(); schemaUpdater.updateSchema(db, testTable); }

Target:
public void testUpdateSchema() { DefaultTableSchemaUpdater schemaUpdater = new DefaultTableSchemaUpdater(); AssistantApp app = new AssistantApp(getInstrumentation().getTargetContext().getApplicationContext()); TestTable testTable = new TestTable(app, DATABASE_NAME, TABLE_NAME, TABLE_VERSION, Arrays.<com.sarality.app.datastore.Column> asList(Column.values()), null, null, schemaUpdater); TestOnlineHelper onlineHelper = new TestOnlineHelper(getInstrumentation().getTargetContext() .getApplicationContext(), null, null, TABLE_VERSION); SQLiteDatabase db = onlineHelper.getWritableDatabase(); schemaUpdater.updateSchema(db, testTable); assertEquals(true, TableExists(db)); }
Source:
ContainerShutdownDescriptor(ImageConfiguration imageConfig, String containerId) { this.imageConfig = imageConfig; this.containerId = containerId; RunImageConfiguration runConfig = imageConfig.getRunConfiguration(); WaitConfiguration waitConfig = runConfig != null ? runConfig.getWaitConfiguration() : null; this.shutdownGracePeriod = waitConfig != null ? waitConfig.shutdown() : 0; this.killGracePeriod = waitConfig != null ? waitConfig.kill() : 0; if (waitConfig != null && waitConfig.getExec() != null) { this.preStop = waitConfig.getExec().getPreStop(); this.breakOnError = waitConfig.getExec().isBreakOnError(); } }

Target:
ContainerShutdownDescriptor(ImageConfiguration imageConfig, String containerId) { this.imageConfig = imageConfig; this.containerId = containerId; RunImageConfiguration runConfig = imageConfig.getRunConfiguration(); WaitConfiguration waitConfig = runConfig != null ? runConfig.getWaitConfiguration() : null; this.shutdownGracePeriod = waitConfig != null && waitConfig.getShutdown() != null ? waitConfig.getShutdown() : 0; this.killGracePeriod = waitConfig != null && waitConfig.getKill() != null ? waitConfig.getKill() : 0; if (waitConfig != null && waitConfig.getExec() != null) { this.preStop = waitConfig.getExec().getPreStop(); this.breakOnError = waitConfig.getExec().isBreakOnError(); } }
Source:
public String toString() { return "Response:" + request + "(" + (returnValue != null ? returnValue.getClass().getName() : exception != null ? exception.getClass().getName() : null) + ")"; }

Target:
public String toString() { return "Response" + (request != null ? ":" + request : "") + "(" + (returnValue != null ? returnValue.getClass().getName() : exception != null ? exception.getClass().getName() : null) + ")"; }
Source:
private String assemble() { if (limit > 0) { if (size > limit) { size = limit; } } Map<String, String> uriParams = new LinkedHashMap<String, String>(); StringBuilder sb = new StringBuilder(); sb.append(indices); if (StringUtils.hasLength(types)) { sb.append("/"); sb.append(types); } sb.append("/_search?"); if (version.onOrAfter(EsMajorVersion.V_5_X)) { uriParams.put("sort", "_doc"); } else { uriParams.put("search_type", "scan"); } uriParams.put("scroll", String.valueOf(scroll.toString())); uriParams.put("size", String.valueOf(size)); if (includeVersion) { uriParams.put("version", "true"); } StringBuilder pref = new StringBuilder(); if (StringUtils.hasText(shard)) { pref.append("_shards:"); pref.append(shard); } if (!preference.isEmpty() || local) { if (pref.length() > 0) { if (version.onOrAfter(EsMajorVersion.V_5_X)) { pref.append("|"); } else { pref.append(";"); } } if (!preference.isEmpty()) { pref.append(preference); } else { pref.append("_local"); } } if (pref.length() > 0) { uriParams.put("preference", HttpEncodingTools.encode(pref.toString())); } if (routing != null) { uriParams.put("routing", HttpEncodingTools.encode(routing)); } if (readMetadata) { uriParams.put("track_scores", "true"); } for (Iterator<Entry<String, String>> it = uriParams.entrySet().iterator(); it.hasNext();) { Entry<String, String> entry = it.next(); sb.append(entry.getKey()); if (StringUtils.hasText(entry.getValue())) { sb.append("="); sb.append(entry.getValue()); } if (it.hasNext()) { sb.append("&"); } } return sb.toString(); }

Target:
private String assemble() { if (limit > 0) { if (size > limit) { size = limit; } } Map<String, String> uriParams = new LinkedHashMap<String, String>(); StringBuilder sb = new StringBuilder(); sb.append(indices); if (StringUtils.hasLength(types)) { sb.append("/"); sb.append(types); } sb.append("/_search?"); if (version.onOrAfter(EsMajorVersion.V_5_X)) { uriParams.put("sort", "_doc"); } else { uriParams.put("search_type", "scan"); } uriParams.put("scroll", String.valueOf(scroll.toString())); uriParams.put("size", String.valueOf(size)); if (includeVersion) { uriParams.put("version", "true"); } StringBuilder pref = new StringBuilder(); if (StringUtils.hasText(shard)) { pref.append("_shards:"); pref.append(shard); } if (local || StringUtils.hasText(preference)) { if (pref.length() > 0) { if (version.onOrAfter(EsMajorVersion.V_5_X)) { pref.append("|"); } else { pref.append(";"); } } if (StringUtils.hasText(preference)) { pref.append(preference); } else { pref.append("_local"); } } if (pref.length() > 0) { uriParams.put("preference", HttpEncodingTools.encode(pref.toString())); } if (routing != null) { uriParams.put("routing", HttpEncodingTools.encode(routing)); } if (readMetadata) { uriParams.put("track_scores", "true"); } for (Iterator<Entry<String, String>> it = uriParams.entrySet().iterator(); it.hasNext();) { Entry<String, String> entry = it.next(); sb.append(entry.getKey()); if (StringUtils.hasText(entry.getValue())) { sb.append("="); sb.append(entry.getValue()); } if (it.hasNext()) { sb.append("&"); } } return sb.toString(); }
Source:
public @NonNull String getName() { return fTypeId; }

Target:
public String getName() { return fTypeId; }
Source:
protected void beforeExecute(Thread t, Runnable r) { Work work = WorkHolder.getWork(r); if (isShutdown()) { work.setWorkInstanceState(State.SCHEDULED); queuing.workReschedule(queueId, work); throw new RejectedExecutionException(queueId + " was shutdown, rescheduled " + work); } NuxeoBlockingQueue q = queuing.getQueue(queueId); if (!q.active) { work.setWorkInstanceState(State.SCHEDULED); queuing.workReschedule(queueId, work); throw new RejectedExecutionException(queueId + " is not active, rescheduled " + work); } work.setWorkInstanceState(State.RUNNING); queuing.workRunning(queueId, work); running.add(work); runningCount.inc(); }

Target:
protected void beforeExecute(Thread t, Runnable r) { Work work = WorkHolder.getWork(r); if (isShutdown()) { work.setWorkInstanceState(State.SCHEDULED); queuing.workReschedule(queueId, work); throw new RejectedExecutionException(queueId + " was shutdown, rescheduled " + work); } work.setWorkInstanceState(State.RUNNING); queuing.workRunning(queueId, work); running.add(work); runningCount.inc(); }
Source:
protected String generateDestPath(VirtualMachineTO vmTO, VolumeVO srcVolume, Host destHost, StoragePoolVO destStoragePool, VolumeInfo destVolumeInfo) { DiskOfferingVO diskOffering = _diskOfferingDao.findById(srcVolume.getDiskOfferingId()); DiskProfile diskProfile = new DiskProfile(destVolumeInfo, diskOffering, HypervisorType.KVM); String templateUuid = getTemplateUuid(destVolumeInfo.getTemplateId()); CreateCommand rootImageProvisioningCommand = new CreateCommand(diskProfile, templateUuid, destStoragePool, true); Answer rootImageProvisioningAnswer = _agentMgr.easySend(destHost.getId(), rootImageProvisioningCommand); if (rootImageProvisioningAnswer == null) { throw new CloudRuntimeException(String.format("Migration with storage of vm [%s] failed while provisioning root image", vmTO.getName())); } if (!rootImageProvisioningAnswer.getResult()) { throw new CloudRuntimeException(String.format("Unable to modify target volume on the host [host id:%s, name:%s]", destHost.getId(), destHost.getName())); } String libvirtDestImgsPath = StringUtils.EMPTY; if (rootImageProvisioningAnswer instanceof CreateAnswer) { libvirtDestImgsPath = ((CreateAnswer)rootImageProvisioningAnswer).getVolume().getName() + "/"; } return libvirtDestImgsPath + destVolumeInfo.getUuid(); }

Target:
protected String generateDestPath(VirtualMachineTO vmTO, VolumeVO srcVolume, Host destHost, StoragePoolVO destStoragePool, VolumeInfo destVolumeInfo) { DiskOfferingVO diskOffering = _diskOfferingDao.findById(srcVolume.getDiskOfferingId()); DiskProfile diskProfile = new DiskProfile(destVolumeInfo, diskOffering, HypervisorType.KVM); String templateUuid = getTemplateUuid(destVolumeInfo.getTemplateId()); CreateCommand rootImageProvisioningCommand = new CreateCommand(diskProfile, templateUuid, destStoragePool, true); Answer rootImageProvisioningAnswer = _agentMgr.easySend(destHost.getId(), rootImageProvisioningCommand); if (rootImageProvisioningAnswer == null) { throw new CloudRuntimeException(String.format("Migration with storage of vm [%s] failed while provisioning root image", vmTO.getName())); } if (!rootImageProvisioningAnswer.getResult()) { throw new CloudRuntimeException(String.format("Unable to modify target volume on the host [host id:%s, name:%s]", destHost.getId(), destHost.getName())); } String libvirtDestImgsPath = null; if (rootImageProvisioningAnswer instanceof CreateAnswer) { libvirtDestImgsPath = ((CreateAnswer)rootImageProvisioningAnswer).getVolume().getName(); } return new File(libvirtDestImgsPath, destVolumeInfo.getUuid()).getAbsolutePath(); }
Source:
public static Package getBaseProtocol(Element anElement) { if (anElement != null) { IDefaultLanguage language = null; try { IDefaultLanguageService service = ServiceUtilsForEObject.getInstance().getService(IDefaultLanguageService.class, anElement); language = service.getActiveDefaultLanguage(anElement); } catch (ServiceException e) { Activator.log.error(e); } TransactionalEditingDomain domain = TransactionUtil.getEditingDomain(anElement); Collaboration baseProtocol = language.getBaseProtocol(domain.getResourceSet()); if (baseProtocol != null) { return getProtocolContainer(baseProtocol); } } return null; }

Target:
public static Package getBaseProtocol(Element anElement) { if (anElement != null) { IDefaultLanguage language = null; try { IDefaultLanguageService service = ServiceUtilsForEObject.getInstance().getService(IDefaultLanguageService.class, anElement); language = service.getActiveDefaultLanguage(anElement); } catch (ServiceException e) { Activator.log.error(e); } if (language != null) { TransactionalEditingDomain domain = TransactionUtil.getEditingDomain(anElement); Collaboration baseProtocol = language.getBaseProtocol(domain.getResourceSet()); if (baseProtocol != null) { return getProtocolContainer(baseProtocol); } } } return null; }
Source:
public static Dataset<Row> resultSetToDF(ResultSet rs) throws StandardException { EmbedResultSet40 ers = (EmbedResultSet40) rs; com.splicemachine.db.iapi.sql.ResultSet serverSideResultSet = ers.getUnderlyingResultSet(); SpliceBaseOperation operation = (SpliceBaseOperation) serverSideResultSet; DataSetProcessor dsp = EngineDriver.driver().processorFactory().distributedProcessor(); DataSet<ExecRow> spliceDataSet = operation.getResultDataSet(dsp); final ResultColumnDescriptor[] columns = serverSideResultSet.getResultDescription().getColumnInfo(); List<StructField> fields = new ArrayList<>(); for (ResultColumnDescriptor column : columns) { fields.add(column.getStructField()); } if( fields.stream().map( f -> f.name().toUpperCase() ).distinct().count() != fields.size() ) { fields = new ArrayList<>(); Set<String> used = new HashSet<>(); for (ResultColumnDescriptor column : columns) { int i = 0; String fullname = column.getSourceSchemaName()+"."+column.getSourceTableName()+"."+column.getName(); String name = fullname; while( used.contains(name) ) { i += 1; name = fullname+"_"+i; } used.add(name); StructField sf = column.getStructField(); fields.add(new StructField(name, sf.dataType(), sf.nullable(), sf.metadata())); } } StructType schema = DataTypes.createStructType(fields); if(spliceDataSet instanceof SparkDataSet) { JavaRDD<ExecRow> rdd = ((SparkDataSet)spliceDataSet).rdd; return SpliceSpark.getSession().createDataFrame(rdd.map(new LocatedRowToRowFunction()), schema); } else { return ((NativeSparkDataSet) spliceDataSet).dataset.toDF( schema.fieldNames() ); } }

Target:
public static Dataset<Row> resultSetToDF(ResultSet rs) throws StandardException { EmbedResultSet40 ers = (EmbedResultSet40) rs; com.splicemachine.db.iapi.sql.ResultSet serverSideResultSet = ers.getUnderlyingResultSet(); SpliceBaseOperation operation = (SpliceBaseOperation) serverSideResultSet; DataSetProcessor dsp = EngineDriver.driver().processorFactory().distributedProcessor(); DataSet<ExecRow> spliceDataSet = operation.getResultDataSet(dsp); final ResultColumnDescriptor[] columns = serverSideResultSet.getResultDescription().getColumnInfo(); List<StructField> fields = new ArrayList<>(); for (ResultColumnDescriptor column : columns) { fields.add(column.getStructField()); } if( fields.stream().map( f -> f.name() ).distinct().count() != fields.size() ) { fields = new ArrayList<>(); Set<String> used = new HashSet<>(); for (ResultColumnDescriptor column : columns) { int i = 0; String fullname = column.getSourceSchemaName()+"."+column.getSourceTableName()+"."+column.getName(); String name = fullname; while( used.contains(name) ) { i += 1; name = fullname+"_"+i; } used.add(name); StructField sf = column.getStructField(); fields.add(new StructField(name, sf.dataType(), sf.nullable(), sf.metadata())); } } StructType schema = DataTypes.createStructType(fields); if(spliceDataSet instanceof SparkDataSet) { JavaRDD<ExecRow> rdd = ((SparkDataSet)spliceDataSet).rdd; return SpliceSpark.getSession().createDataFrame(rdd.map(new LocatedRowToRowFunction()), schema); } else { return ((NativeSparkDataSet) spliceDataSet).dataset.toDF( schema.fieldNames() ); } }
Source:
protected void render0(FunctionRenderContext context) { Object[] jsonPathElements = new Object[context.getArgumentsSize() - 1]; for (int i = 1; i < context.getArgumentsSize(); i++) { try { jsonPathElements[i - 1] = Integer.parseInt(JpqlFunctionUtil.unquoteSingleQuotes(context.getArgument(i))); } catch (NumberFormatException e) { jsonPathElements[i - 1] = JpqlFunctionUtil.unquoteDoubleQuotes(JpqlFunctionUtil.unquoteSingleQuotes(context.getArgument(i))); } } String jsonPath = AbstractJsonGetFunction.toJsonPath(jsonPathElements, jsonPathElements.length, true); context.addChunk("json_unquote("); context.addChunk("nullif(json_extract("); context.addArgument(0); context.addChunk(",'"); context.addChunk(jsonPath); context.addChunk("')"); context.addChunk(",cast('null' as json)))"); }

Target:
protected void render0(FunctionRenderContext context) { List<Object> jsonPathElements = AbstractJsonGetFunction.retrieveJsonPathElements(context, 1); String jsonPath = AbstractJsonGetFunction.toJsonPath(jsonPathElements, jsonPathElements.size(), true); context.addChunk("json_unquote("); context.addChunk("nullif(json_extract("); context.addArgument(0); context.addChunk(",'"); context.addChunk(jsonPath); context.addChunk("')"); context.addChunk(",cast('null' as json)))"); }
Source:
protected void onResume() { super.onResume(); if (!initComplete) { loaderManager.initLoader(ID_BLOCKCHAIN_STATE_LOADER, null, blockchainStateLoaderCallbacks); initComplete = true; } else { loaderManager.restartLoader(ID_BLOCKCHAIN_STATE_LOADER, null, blockchainStateLoaderCallbacks); } handler.postDelayed(new Runnable() { @Override public void run() { getWalletApplication().startBlockchainService(true); } }, 1000); checkLowStorageAlert(); detectUserCountry(); showBackupWalletDialogIfNeeded(); showHideSecureAction(); }

Target:
protected void onResume() { super.onResume(); handler.postDelayed(new Runnable() { @Override public void run() { getWalletApplication().startBlockchainService(true); } }, 1000); checkLowStorageAlert(); detectUserCountry(); showBackupWalletDialogIfNeeded(); showHideSecureAction(); }
Source:
public List<Ref> call() throws GitAPIException { checkCallable(); List<Ref> refList; List<Ref> tags = new ArrayList<>(); try (RevWalk revWalk = new RevWalk(repo)) { refList = repo.getRefDatabase().getRefsByPrefix(Constants.R_TAGS); for (Ref ref : refList) { tags.add(ref); } } catch (IOException e) { throw new JGitInternalException(e.getMessage(), e); } Collections.sort(tags, new Comparator<Ref>() { @Override public int compare(Ref o1, Ref o2) { return o1.getName().compareTo(o2.getName()); } }); setCallable(false); return tags; }

Target:
public List<Ref> call() throws GitAPIException { checkCallable(); List<Ref> tags = new ArrayList<>(); try (RevWalk revWalk = new RevWalk(repo)) { List<Ref> refList = repo.getRefDatabase() .getRefsByPrefix(Constants.R_TAGS); for (Ref ref : refList) { tags.add(ref); } } catch (IOException e) { throw new JGitInternalException(e.getMessage(), e); } Collections.sort(tags, new Comparator<Ref>() { @Override public int compare(Ref o1, Ref o2) { return o1.getName().compareTo(o2.getName()); } }); setCallable(false); return tags; }
Source:
public void query(final Query query, final int chunkSize, final Consumer<QueryResult> consumer) { if (version().startsWith("0.") || version().startsWith("1.0")) { throw new UnsupportedOperationException("chunking not supported"); } Call<ResponseBody> call = null; if (query instanceof BoundParameterQuery) { BoundParameterQuery boundParameterQuery = (BoundParameterQuery) query; call = this.influxDBService.query(this.username, this.password, query.getDatabase(), query.getCommandWithUrlEncoded(), chunkSize, boundParameterQuery.getParameterJsonWithUrlEncoded()); } else { call = this.influxDBService.query(this.username, this.password, query.getDatabase(), query.getCommandWithUrlEncoded(), chunkSize); } call.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(final Call<ResponseBody> call, final Response<ResponseBody> response) { try { if (response.isSuccessful()) { ResponseBody chunkedBody = response.body(); chunkProccesor.process(chunkedBody, consumer); } else { ResponseBody errorBody = response.errorBody(); if (errorBody != null) { throw new InfluxDBException(errorBody.string()); } } } catch (IOException e) { QueryResult queryResult = new QueryResult(); queryResult.setError(e.toString()); consumer.accept(queryResult); } } @Override public void onFailure(final Call<ResponseBody> call, final Throwable t) { throw new InfluxDBException(t); } }); }

Target:
public void query(final Query query, final int chunkSize, final Consumer<QueryResult> consumer) { Call<ResponseBody> call = null; if (query instanceof BoundParameterQuery) { BoundParameterQuery boundParameterQuery = (BoundParameterQuery) query; call = this.influxDBService.query(this.username, this.password, query.getDatabase(), query.getCommandWithUrlEncoded(), chunkSize, boundParameterQuery.getParameterJsonWithUrlEncoded()); } else { call = this.influxDBService.query(this.username, this.password, query.getDatabase(), query.getCommandWithUrlEncoded(), chunkSize); } call.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(final Call<ResponseBody> call, final Response<ResponseBody> response) { try { if (response.isSuccessful()) { ResponseBody chunkedBody = response.body(); chunkProccesor.process(chunkedBody, consumer); } else { ResponseBody errorBody = response.errorBody(); if (errorBody != null) { throw new InfluxDBException(errorBody.string()); } } } catch (IOException e) { QueryResult queryResult = new QueryResult(); queryResult.setError(e.toString()); consumer.accept(queryResult); } } @Override public void onFailure(final Call<ResponseBody> call, final Throwable t) { throw new InfluxDBException(t); } }); }
Source:
public RMInitialState getRMInitialState() { Map<String, RMNodeEvent> nodeEvents = new HashMap<>(this.allNodes.size()); for (RMNode rmnode : this.allNodes.values()) { final RMNodeEvent nodeEvent = rmnode.createNodeEvent(); nodeEvents.put(nodeEvent.getNodeUrl(), nodeEvent); } Map<String, RMNodeSourceEvent> nodeSourcesList = new HashMap<>(this.deployedNodeSources.size()); for (NodeSource nodeSource : this.definedNodeSources.values()) { nodeSourcesList.put(nodeSource.getName(), new RMNodeSourceEvent(nodeSource.getName(), nodeSource.getDescription(), nodeSource.getAdministrator().getName(), nodeSource.getStatus().toString())); if (this.deployedNodeSources.containsKey(nodeSource.getName())) { for (RMDeployingNode node : nodeSource.getDeployingAndLostNodes()) { final RMNodeEvent nodeEvent = node.createNodeEvent(); nodeEvents.put(nodeEvent.getNodeUrl(), nodeEvent); } } } return new RMInitialState(nodeEvents, nodeSourcesList); }

Target:
public RMInitialState getRMInitialState() { final Map<String, RMNodeEvent> nodeEvents = this.allNodes.values() .stream() .map(RMNode::createNodeEvent) .collect(Collectors.toMap(RMNodeEvent::getNodeUrl, event -> event)); for (NodeSource source : this.deployedNodeSources.values()) { for (RMDeployingNode node : source.getDeployingAndLostNodes()) { final RMNodeEvent nodeEvent = node.createNodeEvent(); nodeEvents.put(nodeEvent.getNodeUrl(), nodeEvent); } } final Map<String, RMNodeSourceEvent> nodeSourceEvents = this.definedNodeSources.values() .stream() .map(NodeSource::createNodeSourceEvent) .collect(Collectors.toMap(RMNodeSourceEvent::getSourceName, event -> event)); return new RMInitialState(nodeEvents, nodeSourceEvents); }