auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void setArtifactIdentifyData(IAtsAction fromAction, IAtsTeamWorkflow toTeam, IAtsChangeSet changes) throws OseeCoreException { <START> ArtifactReadable fromActionArt = (ArtifactReadable) fromAction.getStoreObject(); <END> setArtifactIdentifyData(toTeam, fromAction.getName(), fromActionArt.getSoleAttributeValue(AtsAttributeTypes.Description, ""), ChangeTypeUtil.getChangeType(fromAction), fromActionArt.getSoleAttributeValue(AtsAttributeTypes.PriorityType, ""), fromActionArt.getSoleAttributeValue(AtsAttributeTypes.ValidationRequired, false), fromActionArt.getSoleAttributeValue(AtsAttributeTypes.NeedBy, (Date) null), changes); }</code><technical_language>null check fromAction necessary</technical_language>

Target:
public void setArtifactIdentifyData(IAtsAction fromAction, IAtsTeamWorkflow toTeam, IAtsChangeSet changes) throws OseeCoreException { Conditions.checkNotNull(fromAction, "fromAction"); Conditions.checkNotNull(toTeam, "toTeam"); Conditions.checkNotNull(changes, "changes"); ArtifactReadable fromActionArt = (ArtifactReadable) fromAction.getStoreObject(); setArtifactIdentifyData(toTeam, fromAction.getName(), fromActionArt.getSoleAttributeValue(AtsAttributeTypes.Description, ""), ChangeTypeUtil.getChangeType(fromAction), fromActionArt.getSoleAttributeValue(AtsAttributeTypes.PriorityType, ""), fromActionArt.getSoleAttributeValue(AtsAttributeTypes.ValidationRequired, false), fromActionArt.getSoleAttributeValue(AtsAttributeTypes.NeedBy, (Date) null), changes); }
Source:
<code>protected void doWriteMaxKey() { writeStartDocument(); <START> writeInt32("$maxkey", 1); <END> writeEndDocument(); }</code><technical_language><LINK_0>, $maxKey $minKey is correct. I JsonReader needs change, JsonWriter</technical_language>

Target:
protected void doWriteMaxKey() { writeStartDocument(); writeInt32("$maxKey", 1); writeEndDocument(); }
Source:
<code>private final static void declareImage(String key, String path, boolean shared) { declareImage(key, <START> ImageDescriptor.createFromSupplier(()-> <END> ImageDescriptor.createFromURL( FileLocator.find(Platform.getBundle(PlatformUI.PLUGIN_ID), new Path(path), null)) .getImageData()), shared); }</code><technical_language>Suggest retaining local variables keeping calls find createFromUrl lines</technical_language>

Target:
private final static void declareImage(String key, String path, boolean shared) { declareImage(key, ImageDescriptor.createFromSupplier(()-> { URL url = FileLocator.find(Platform.getBundle(PlatformUI.PLUGIN_ID), new Path(path), null); return ImageDescriptor.createFromURL(url).getImageData(); }), shared); }
Source:
<code>protected void updateAxisAfterConfigurationChange() { List<Object> allAxisToDisplay = new ArrayList<Object>(); for (final IWrapper current : ((IMasterAxisProvider) getTableManager().getTable().getCurrentColumnAxisProvider()).getSources()) { <START> allAxisToDisplay.addAll(getListenFeatureValueFor((EObject) <END> current.getElement())); } List<Object> toAdd = new ArrayList<Object>(allAxisToDisplay); toAdd.removeAll(this.managedObject); List<Object> toRemove = new ArrayList<Object>(this.managedObject); toRemove.removeAll(allAxisToDisplay); updateManagedList(toAdd, toRemove); }</code><technical_language>committed</technical_language>

Target:
protected void updateAxisAfterConfigurationChange() { if (null == getTableManager() || null == getTableManager().getTable() || null == getTableManager().getTable().getCurrentColumnAxisProvider()) { return; } List<Object> allAxisToDisplay = new ArrayList<Object>(); for (final IWrapper current : ((IMasterAxisProvider) getTableManager().getTable().getCurrentColumnAxisProvider()).getSources()) { if (current.getElement() instanceof EObject) { allAxisToDisplay.addAll(getListenFeatureValueFor((EObject) current.getElement())); } } List<Object> toAdd = new ArrayList<Object>(allAxisToDisplay); toAdd.removeAll(this.managedObject); List<Object> toRemove = new ArrayList<Object>(this.managedObject); toRemove.removeAll(allAxisToDisplay); updateManagedList(toAdd, toRemove); }
Source:
<code>private void generateConfigIni(TargetEnvironment environment, File target) throws MojoExecutionException, MojoFailureException { getLog().debug("Generating config.ini"); Properties props = new Properties(); String id = productConfiguration.getProduct(); if (id != null) { String splash = id.split("\\.")[0]; setPropertyIfNotNull(props, "osgi.splashPath", "platform:/base/plugins/" + splash); } setPropertyIfNotNull(props, "eclipse.product", id); setPropertyIfNotNull(props, "osgi.bundles.defaultStartLevel", "4"); generateOSGiBundles(props, environment); File configsFolder = new File(target, "configuration"); configsFolder.mkdirs(); File configIni = new File(configsFolder, "config.ini"); FileOutputStream fos = null; try { fos = new FileOutputStream(configIni); props.store(fos, "Product Runtime Configuration File"); } catch (IOException e) { throw new MojoExecutionException("Error creating .eclipseproduct file.", e); <START> } finally { <END> try { if (fos != null) { fos.close(); } } catch (IOException ex) { throw new MojoExecutionException("Error closing stream for .eclipseproduct file.", ex); } } }</code><technical_language>IOUtil.close(fos) shorter</technical_language>

Target:
private void generateConfigIni(TargetEnvironment environment, File target) throws MojoExecutionException, MojoFailureException { getLog().debug("Generating config.ini"); Properties props = new Properties(); String id = productConfiguration.getProduct(); if (id != null) { String splash = id.split("\\.")[0]; setPropertyIfNotNull(props, "osgi.splashPath", "platform:/base/plugins/" + splash); } setPropertyIfNotNull(props, "eclipse.product", id); setPropertyIfNotNull(props, "osgi.bundles.defaultStartLevel", "4"); generateOSGiBundles(props, environment); File configsFolder = new File(target, "configuration"); configsFolder.mkdirs(); File configIni = new File(configsFolder, "config.ini"); FileOutputStream fos = null; try { fos = new FileOutputStream(configIni); props.store(fos, "Product Runtime Configuration File"); } catch (IOException e) { throw new MojoExecutionException("Error creating .eclipseproduct file.", e); } finally { IOUtil.close(fos); } }
Source:
<code>public TObject sumKeyRecord(String key, long record, AccessToken creds, TransactionToken transaction, String environment) throws SecurityException, TransactionException, TException { checkAccess(creds, transaction); AtomicSupport store = getStore(transaction, environment); BigDecimal result = new BigDecimal(0); AtomicOperation atomic = null; while (atomic == null || !atomic.commit()) { atomic = store.startAtomicOperation(); try { <START> Set<TObject> values = atomic.select(key, record); <END> for (TObject value : values) { Object obj = Convert.thriftToJava(value); if(!(obj instanceof Number)) { throw new UnsupportedOperationException(); } else { Number number = (Number) obj; if(number instanceof Byte || number instanceof Short) { throw new UnsupportedOperationException(); } else { result = result.add(Numbers.toBigDecimal(number)); } } } } catch (AtomicStateException e) { atomic = null; result = null; } } return Convert.javaToThrift(result); }</code><technical_language>This method sumKeyRecordAtomic duplicating logic</technical_language>

Target:
public TObject sumKeyRecord(String key, long record, AccessToken creds, TransactionToken transaction, String environment) throws TException { checkAccess(creds, transaction); AtomicSupport store = getStore(transaction, environment); AtomicOperation atomic = null; Number sum = 0; while (atomic == null || !atomic.commit()) { atomic = store.startAtomicOperation(); try { sum = sumKeyRecordAtomic(key, record, Time.NONE, sum, atomic); } catch (AtomicStateException e) { atomic = null; sum = 0; } } return Convert.javaToThrift(sum); }
Source:
<code>private void delete(File file) { if (file.isDirectory()) { for (File <START> listFile : <END> file.listFiles()) { delete(listFile); } } file.delete(); }</code><technical_language>rename f</technical_language>

Target:
private void delete(File file) { if (file.isDirectory()) { for (File f : file.listFiles()) { delete(f); } } file.delete(); }
Source:
<code>protected void onResume() { super.onResume(); if (!mOnTransfer && mSipServiceConnection.get() != null && mSipServiceConnection.get().getCurrentCall() != null) { if (mSipServiceConnection.get().getCurrentCall().isOnHold()) { mLogger.d("SipService has call on hold"); if (!mOnHold) { mLogger.i("But the activity DOES not have the call on hold. Match the sip service."); mOnHold = true; updateCallButton(R.id.button_onhold, true); onCallStatusUpdate(CALL_PUT_ON_HOLD_ACTION); } else if (!mOnHoldButton.isActivated()) { mLogger.i("Call is on hold but the button is not active. Update the button"); updateCallButton(R.id.button_onhold, true); } } } refreshAudioSourceButton(); if(!mNetworkUtil.isOnline()) { <START> mNetworkConnectivity.startNetworkAvailabilityActivity(); <END> mLogger.d("No connectivity available, the Network Availability Activity is being shown"); } }</code><technical_language>correct lines writing classes try responsibility a single (it's called Single Responsibility Principle if want read more). class is a broadcast receiver is responsible for listening network changes reacting, responsible for opening activity another place. suggest creating a new static method NetworkAvailabilityActivity itself, call NetworkAvailabilityActivity.start(). put log line in too</technical_language>

Target:
protected void onResume() { super.onResume(); updateUi(); if(!mNetworkUtil.isOnline()) { NetworkAvailabilityActivity.start(); } }
Source:
<code>private void buildCache() { LOG.debug("Inside buildCache"); if (!MessageMonitoringUtil.isMessageMonitoringEnabled()) { LOG.debug("Message Monitoring is not enabled."); return; } LOG.debug("Message Monitoring is enabled."); List<MonitoredMessage> pendingMessages = getAllPendingMessagesFromDatabase(); LOG.debug("Total cache rows from database:" + pendingMessages.size()); clearCache(); for (MonitoredMessage trackMessage : pendingMessages) { <START> if (!trackMessage.getStatus().equals(STATUS_ARCHIVED)) { <END> messageMonitoringCache.put(trackMessage.getMessageid(), trackMessage); LOG.debug("Total child rows for the messageId:" + trackMessage.getMonitoredmessagenotifications().size()); } } LOG.debug("Exiting buildCache."); }</code><technical_language>cleanup Archived message a server restart. Call deleteElapsedArchivedMessage() method if find archived message</technical_language>

Target:
private void buildCache() { LOG.debug("Inside buildCache"); if (!MessageMonitoringUtil.isMessageMonitoringEnabled()) { LOG.debug("Message Monitoring is not enabled."); return; } LOG.debug("Message Monitoring is enabled."); List<MonitoredMessage> pendingMessages = getAllPendingMessagesFromDatabase(); LOG.debug("Total cache rows from database:" + pendingMessages.size()); clearCache(); for (MonitoredMessage trackMessage : pendingMessages) { if (!trackMessage.getStatus().equals(STATUS_ARCHIVED)) { messageMonitoringCache.put(trackMessage.getMessageid(), trackMessage); LOG.debug("Total child rows for the messageId:" + trackMessage.getMonitoredmessagenotifications().size()); } else { deleteElapsedArchivedMessage(trackMessage); } } LOG.debug("Exiting buildCache."); }
Source:
<code>public CommunicationBridge(final WebView webView, final String baseURL) { this.webView = webView; this.marshaller = new BridgeMarshaller(); webView.getSettings().setJavaScriptEnabled(true); <START> webView.getSettings().setAllowFileAccessFromFileURLs(true); <END> webView.getSettings().setAllowUniversalAccessFromFileURLs(true); webView.setWebChromeClient(new CommunicatingChrome()); webView.addJavascriptInterface(marshaller, "marshaller"); webView.loadUrl(baseURL); eventListeners = new HashMap<>(); this.addListener("DOMLoaded", new JSEventListener() { @Override public void onMessage(String messageType, JSONObject messagePayload) { isDOMReady = true; for (String jsString : pendingJSMessages) { CommunicationBridge.this.webView.loadUrl(jsString); } } }); }</code><technical_language>Is this needed if setAllowUniversalAccessFromFileURLs is true? WebSettings docs sound redundant</technical_language>

Target:
public CommunicationBridge(final WebView webView, final String baseURL) { this.webView = webView; this.marshaller = new BridgeMarshaller(); webView.getSettings().setJavaScriptEnabled(true); webView.getSettings().setAllowUniversalAccessFromFileURLs(true); webView.setWebChromeClient(new CommunicatingChrome()); webView.addJavascriptInterface(marshaller, "marshaller"); webView.loadUrl(baseURL); eventListeners = new HashMap<>(); this.addListener("DOMLoaded", new JSEventListener() { @Override public void onMessage(String messageType, JSONObject messagePayload) { isDOMReady = true; for (String jsString : pendingJSMessages) { CommunicationBridge.this.webView.loadUrl(jsString); } } }); }
Source:
<code>public void updateAttributes() { OperatingSystem operatingSystem = getCurrentOperatingSystem(); if (operatingSystem != null) { OSProcess process = operatingSystem.getProcess(this.processID); if (process != null) { copyValuesToThisProcess(process); } else { <START> LOG.error("No process found: {}", this.processID); <END> } } else { LOG.error("Unsupported platform. No update performed."); } }</code><technical_language>This a common return error logging appropriate. I this method return boolean (and return false if update fails), do debug level logging here</technical_language>

Target:
public boolean updateAttributes() { OSProcess process = operatingSystem.getProcess(this.processID); if (process == null) { LOG.debug("No process found: {}", this.processID); return false; } copyValuesToThisProcess(process); return true; }
Source:
<code>void checkOperationChains(List<OperationChain> opChains) throws Exception { Map<PartitionId, Integer> partitionCount = new HashMap<>(); double blobsPut = 0; for (OperationChain opChain : opChains) { if (!opChain.latch.await(AWAIT_TIMEOUT, TimeUnit.SECONDS)) { Assert.fail("Timeout waiting for operation chain " + opChain.chainId + " to finish."); } synchronized (opChain.testFutures) { for (TestFuture testFuture : opChain.testFutures) { testFuture.check(); } } <START> Assert.assertEquals("opChain stops in the middle.", 0, opChain.operations.size()); <END> if (opChain.blobId != null) { blobsPut++; PartitionId partitionId = new BlobId(opChain.blobId, clusterMap).getPartition(); int count = partitionCount.getOrDefault(partitionId, 0); partitionCount.put(partitionId, count + 1); } } double numPartitions = clusterMap.getWritablePartitionIds(null).size(); if (opChains.size() > numPartitions) { double blobBalanceThreshold = BALANCE_FACTOR * Math.ceil(blobsPut / numPartitions); for (Map.Entry<PartitionId, Integer> entry : partitionCount.entrySet()) { Assert.assertTrue("Number of blobs is " + entry.getValue() + " on partition: " + entry.getKey() + ", which is greater than the threshold of " + blobBalanceThreshold, entry.getValue() <= blobBalanceThreshold); } } }</code><technical_language>minor: opChain stopped in middle</technical_language>

Target:
void checkOperationChains(List<OperationChain> opChains) throws Exception { Map<PartitionId, Integer> partitionCount = new HashMap<>(); double blobsPut = 0; for (OperationChain opChain : opChains) { if (!opChain.latch.await(AWAIT_TIMEOUT, TimeUnit.SECONDS)) { Assert.fail("Timeout waiting for operation chain " + opChain.chainId + " to finish."); } synchronized (opChain.testFutures) { for (TestFuture testFuture : opChain.testFutures) { testFuture.check(); } } Assert.assertEquals("opChain stopped in the middle.", 0, opChain.operations.size()); if (opChain.blobId != null) { blobsPut++; PartitionId partitionId = new BlobId(opChain.blobId, clusterMap).getPartition(); int count = partitionCount.getOrDefault(partitionId, 0); partitionCount.put(partitionId, count + 1); } } double numPartitions = clusterMap.getWritablePartitionIds(null).size(); if (opChains.size() > numPartitions) { double blobBalanceThreshold = BALANCE_FACTOR * Math.ceil(blobsPut / numPartitions); for (Map.Entry<PartitionId, Integer> entry : partitionCount.entrySet()) { Assert.assertTrue("Number of blobs is " + entry.getValue() + " on partition: " + entry.getKey() + ", which is greater than the threshold of " + blobBalanceThreshold, entry.getValue() <= blobBalanceThreshold); } } }
Source:
<code>public List<RichGroup> getRichGroupsWithAttributesAssignedToResource(PerunSession sess, Resource resource, List<String> attrNames) throws InternalErrorException, GroupResourceMismatchException { List<Group> assignedGroups = getPerunBl().getResourcesManagerBl().getAssignedGroups(sess, resource); <START> return this.convertGroupsToRichGroupsWithAttributes(sess, resource, assignedGroups, attrNames); <END> }</code><technical_language>Please catch GroupResourceMismatchException conversion method wrap ConsistencyErrorException. input, is group retrieve groups assigned resource - VO happen Group-Resource mismatch</technical_language>

Target:
public List<RichGroup> getRichGroupsWithAttributesAssignedToResource(PerunSession sess, Resource resource, List<String> attrNames) throws InternalErrorException { List<Group> assignedGroups = getPerunBl().getResourcesManagerBl().getAssignedGroups(sess, resource); try { return this.convertGroupsToRichGroupsWithAttributes(sess, resource, assignedGroups, attrNames); } catch (GroupResourceMismatchException ex) { throw new ConsistencyErrorException(ex); } }
Source:
<code>protected StorageDomainStatic generateNewEntity() { StorageDomainStatic newStaticDomain = new StorageDomainStatic(); newStaticDomain.setStorageName("NewStorageDomain"); newStaticDomain.setStorage("fDMzhE-wx3s-zo3q-Qcxd-T0li-yoYU-QvVePl"); newStaticDomain.setStorageFormat(StorageFormatType.V1); newStaticDomain.setWipeAfterDelete(true); newStaticDomain.setDiscardAfterDelete(false); newStaticDomain.setWarningLowSpaceIndicator(3); newStaticDomain.setCriticalSpaceActionBlocker(9); newStaticDomain.setWarningLowConfirmedSpaceIndicator(6); newStaticDomain.setFirstMetadataDevice(FixturesTool.LUN_ID2); newStaticDomain.setVgMetadataDevice(FixturesTool.LUN_ID2); newStaticDomain.setBackup(false); newStaticDomain.setDescription(""); <START> newStaticDomain.setComment(""); <END> return newStaticDomain; }</code><technical_language>needed, part of constructor</technical_language>

Target:
protected StorageDomainStatic generateNewEntity() { StorageDomainStatic newStaticDomain = new StorageDomainStatic(); newStaticDomain.setStorageName("NewStorageDomain"); newStaticDomain.setStorage("fDMzhE-wx3s-zo3q-Qcxd-T0li-yoYU-QvVePl"); newStaticDomain.setStorageFormat(StorageFormatType.V1); newStaticDomain.setWipeAfterDelete(true); newStaticDomain.setDiscardAfterDelete(false); newStaticDomain.setWarningLowSpaceIndicator(3); newStaticDomain.setCriticalSpaceActionBlocker(9); newStaticDomain.setWarningLowConfirmedSpaceIndicator(6); newStaticDomain.setFirstMetadataDevice(FixturesTool.LUN_ID2); newStaticDomain.setVgMetadataDevice(FixturesTool.LUN_ID2); newStaticDomain.setBackup(false); return newStaticDomain; }
Source:
<code>private PregelDriver(final ETMaster etMaster, final CentCommConfProvider centCommConfProvider, final PregelMaster pregelMaster, @Parameter(SerializedTaskConf.class) final String serializedTaskConf, @Parameter(SerializedMasterConf.class) final String serializedMasterConf) throws IOException, InjectionException { this.etMaster = etMaster; this.masterConfInjector = Tang.Factory.getTang().newInjector(ConfigurationUtils.fromString(serializedMasterConf)); this.taskConf = ConfigurationUtils.fromString(serializedTaskConf); final StreamingCodec vertexValueCodec = masterConfInjector.getNamedInstance(VertexValueCodec.class); final StreamingCodec edgeCodec = masterConfInjector.getNamedInstance(EdgeCodec.class); this.executorConf = ExecutorConfiguration.newBuilder() .setResourceConf(ResourceConfiguration.newBuilder() .setNumCores(1) .setMemSizeInMB(128) .build()) .setRemoteAccessConf(RemoteAccessConfiguration.newBuilder() .setHandlerQueueSize(2048) .setNumHandlerThreads(1) .setSenderQueueSize(2048) .setNumSenderThreads(1) .build()) .setUserContextConf(centCommConfProvider.getContextConfiguration()) <START> .setUserServiceConf(Configurations.merge(centCommConfProvider.getServiceConfWithoutNameResolver(), <END> Tang.Factory.getTang().newConfigurationBuilder() .bindNamedParameter(VertexValueCodec.class, vertexValueCodec.getClass()) .bindNamedParameter(EdgeCodec.class, edgeCodec.getClass()) .build())) .build(); }</code><technical_language>do configure for executors, msg tables</technical_language>

Target:
private PregelDriver(final ETMaster etMaster, final CentCommConfProvider centCommConfProvider, final PregelMaster pregelMaster, @Parameter(SerializedTaskConf.class) final String serializedTaskConf, @Parameter(SerializedMasterConf.class) final String serializedMasterConf) throws IOException { this.etMaster = etMaster; this.masterConfInjector = Tang.Factory.getTang().newInjector(ConfigurationUtils.fromString(serializedMasterConf)); this.taskConf = ConfigurationUtils.fromString(serializedTaskConf); this.executorConf = ExecutorConfiguration.newBuilder() .setResourceConf(ResourceConfiguration.newBuilder() .setNumCores(1) .setMemSizeInMB(128) .build()) .setRemoteAccessConf(RemoteAccessConfiguration.newBuilder() .setHandlerQueueSize(2048) .setNumHandlerThreads(1) .setSenderQueueSize(2048) .setNumSenderThreads(1) .build()) .setUserContextConf(centCommConfProvider.getContextConfiguration()) .setUserServiceConf(centCommConfProvider.getServiceConfWithoutNameResolver()) .build(); }
Source:
<code>public Query getParsedQueryExecutor(OgmSession session, String queryString, Map<String, Object> namedParameters) { FullTextSession fullTextSession = Search.getFullTextSession( session ); LuceneQueryParsingResult parsingResult = new QueryParser().parseQuery( queryString, createProcessingChain( session, unwrap( namedParameters ), fullTextSession ) ); log.createdQuery( queryString, parsingResult.getQuery() ); FullTextQuery fullTextQuery = fullTextSession.createFullTextQuery( parsingResult.getQuery(), parsingResult.getTargetEntity() ); if ( isTheTargetEntity( parsingResult.getProjections() ) ) { <START> fullTextQuery.setProjection( EMPTY_PROJECTION ); <END> } else { fullTextQuery.setProjection( parsingResult.getProjections().toArray( new String[parsingResult.getProjections().size()] ) ); } fullTextQuery.initializeObjectsWith( ObjectLookupMethod.SKIP, DatabaseRetrievalMethod.FIND_BY_ID ); return fullTextQuery; }</code><technical_language>Do set a project in this case</technical_language>

Target:
public Query getParsedQueryExecutor(OgmSession session, String queryString, Map<String, Object> namedParameters) { FullTextSession fullTextSession = Search.getFullTextSession( session ); LuceneQueryParsingResult parsingResult = new QueryParser().parseQuery( queryString, createProcessingChain( session, unwrap( namedParameters ), fullTextSession ) ); log.createdQuery( queryString, parsingResult.getQuery() ); FullTextQuery fullTextQuery = fullTextSession.createFullTextQuery( parsingResult.getQuery(), parsingResult.getTargetEntity() ); if ( requiresProjections( parsingResult.getProjections() ) ) { fullTextQuery.setProjection( parsingResult.getProjections().toArray( new String[parsingResult.getProjections().size()] ) ); } fullTextQuery.initializeObjectsWith( ObjectLookupMethod.SKIP, DatabaseRetrievalMethod.FIND_BY_ID ); return fullTextQuery; }
Source:
<code>private void closeFlushScheduler() { if (flushScheduler != null) { flushScheduler.shutdown(); try { <START> if (!flushScheduler.awaitTermination(1, TimeUnit.SECONDS)) { <END> flushScheduler.shutdownNow(); if (!flushScheduler.awaitTermination(1, TimeUnit.SECONDS)) { LOG.error("Flush scheduler did not terminate after trials of shutdown."); } } } catch (InterruptedException ie) { flushScheduler.shutdownNow(); Thread.currentThread().interrupt(); } } }</code><technical_language>nit: want multiple iterations(which 2 more) while loop instead of nested if conditionals</technical_language>

Target:
private void closeFlushScheduler() { if (flushScheduler != null) { flushScheduler.shutdown(); try { if (!flushScheduler.awaitTermination(2, TimeUnit.SECONDS)) { flushScheduler.shutdownNow(); } } catch (InterruptedException ie) { flushScheduler.shutdownNow(); Thread.currentThread().interrupt(); } } }
Source:
<code>public TimeoutCustomizationInterceptor(ClientBuilder.TimeoutOption connectTimeout, ClientBuilder.TimeoutOption readTimeout) { <START> this.connectTimeout = connectTimeout.asIntMillis(); <END> this.readTimeout = readTimeout.asIntMillis(); }</code><technical_language>NPE now, a local default this a bit awkward. set -1 apply a if is <0 of better, doc supplied TimeoutOption null</technical_language>

Target:
public TimeoutCustomizationInterceptor(ClientBuilder.TimeoutOption connectTimeout, ClientBuilder.TimeoutOption readTimeout) { if(connectTimeout != null && connectTimeout.asIntMillis() >= 0) { this.connectTimeout = connectTimeout.asIntMillis(); } else { throw new CouchDbException("Connection timeout cannot be null."); } if(readTimeout != null && readTimeout.asIntMillis() >= 0) { this.readTimeout = readTimeout.asIntMillis(); } else { throw new CouchDbException("Read timeout cannot be null."); } }
Source:
<code>protected String handleObjectPost(Object object) throws Exception { String workspace = getAttribute( "workspace"); String coveragestore = getAttribute( "coveragestore"); CoverageInfo coverage = (CoverageInfo) object; if ( coverage.getStore() == null ) { CoverageStoreInfo ds = catalog.getCoverageStoreByName( workspace, coveragestore ); coverage.setStore( ds ); } final boolean isNew = isNewCoverage(coverage); String name = coverage.getName(); CatalogBuilder builder = new CatalogBuilder(catalog); CoverageStoreInfo store = coverage.getStore(); builder.setStore(store); if (!isNew) { builder.initCoverage(coverage, name); } else { coverage = builder.buildCoverage(name); } NamespaceInfo ns = coverage.getNamespace(); if ( ns != null && !ns.getPrefix().equals( workspace ) ) { LOGGER.warning( "Namespace: " + ns.getPrefix() + " does not match workspace: " + workspace + ", overriding." ); ns = null; } if ( ns == null){ ns = catalog.getNamespaceByPrefix( workspace ); coverage.setNamespace( ns ); } coverage.setEnabled(true); <START> List<RuntimeException> validationErrors = catalog.validate(coverage, true); <END> if (!validationErrors.isEmpty()) { throw new RuntimeException("Validation failed"); } catalog.add( coverage ); catalog.add(builder.buildLayer(coverage)); LOGGER.info( "POST coverage " + coveragestore + "," + coverage.getName() ); return coverage.getName(); }</code><technical_language>This code block show a number of times. chance refactor a method in of parent resource classes</technical_language>

Target:
protected String handleObjectPost(Object object) throws Exception { String workspace = getAttribute( "workspace"); String coveragestore = getAttribute( "coveragestore"); CoverageInfo coverage = (CoverageInfo) object; if ( coverage.getStore() == null ) { CoverageStoreInfo ds = catalog.getCoverageStoreByName( workspace, coveragestore ); coverage.setStore( ds ); } final boolean isNew = isNewCoverage(coverage); String name = coverage.getName(); CatalogBuilder builder = new CatalogBuilder(catalog); CoverageStoreInfo store = coverage.getStore(); builder.setStore(store); if (!isNew) { builder.initCoverage(coverage, name); } else { coverage = builder.buildCoverage(name); } NamespaceInfo ns = coverage.getNamespace(); if ( ns != null && !ns.getPrefix().equals( workspace ) ) { LOGGER.warning( "Namespace: " + ns.getPrefix() + " does not match workspace: " + workspace + ", overriding." ); ns = null; } if ( ns == null){ ns = catalog.getNamespaceByPrefix( workspace ); coverage.setNamespace( ns ); } coverage.setEnabled(true); catalog.validate(coverage, true).throwIfInvalid(); catalog.add( coverage ); catalog.add(builder.buildLayer(coverage)); LOGGER.info( "POST coverage " + coveragestore + "," + coverage.getName() ); return coverage.getName(); }
Source:
<code>protected final void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException { JsonParser parser = new JsonParser(); JsonObject json = (JsonObject) parser.parse(req.getReader()); <START> String tokenString = json.get("_authKey").getAsString(); <END> CurrentUser user = currentUser.get(); Account.Id userId; if (user instanceof IdentifiedUser) { userId = ((IdentifiedUser) user).getAccountId(); } else { res.sendError(HttpServletResponse.SC_UNAUTHORIZED); return; } try { verifier.verify(userId, getReqUrl(req), tokenString); } catch (InvalidTokenException err) { handleError(err, req, res); return; } doRequest(req, res, json); }</code><technical_language>server NPEs a bad result for client if _authKey included in request body. handle this sort of case a handleError call do token valid</technical_language>

Target:
protected final void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { CurrentUser user = userProvider.get(); if (!(user instanceof IdentifiedUser)) { sendError(res, SC_UNAUTHORIZED, "API requires authentication"); return; } ParsedBody body; if (JSON_TYPE.equals(req.getContentType())) { body = parseJson(req, res); } else if (FORM_ENCODED.equals(req.getContentType())) { body = parseForm(req, res); } else { sendError(res, SC_BAD_REQUEST, String.format( "Expected Content-Type: %s or %s", JSON_TYPE, FORM_ENCODED)); return; } if (body == null) { return; } if (Strings.isNullOrEmpty(body._authkey)) { String h = req.getHeader(AUTHKEY_HEADER); if (Strings.isNullOrEmpty(h)) { sendError(res, SC_BAD_REQUEST, String.format( "Expected %s in request body or %s in HTTP headers", AUTHKEY_NAME, AUTHKEY_HEADER)); return; } body._authkey = URLDecoder.decode(h, UTF_8); } try { verifier.verify( ((IdentifiedUser) user).getAccountId(), computeUrl(req), body._authkey); } catch (InvalidTokenException err) { sendError(res, SC_BAD_REQUEST, String.format("Invalid or expired %s", AUTHKEY_NAME)); return; } doRequest(body.req, res, body.json); }
Source:
<code>Object asJSON() { <START> return this.value; <END> }</code><technical_language>If is Date, I understand need convert JSON date string</technical_language>

Target:
Object asJSON() { if (value instanceof Date) return DateUtils.toJson((Date) value); else return value; }
Source:
<code>public void testGetExpiredTimelines() { final DateTime now = new DateTime(); final DateTime tomorrow = now.plusDays(1); final DateTime yesterday = now.minusDays(1); final DateTime twoDaysAgo = now.minusDays(2); insertTimeline(tomorrow.toDate(), true, 0); insertTimeline(tomorrow.toDate(), false, 1); insertTimeline(yesterday.toDate(), true, 2); final Timeline t4 = insertTimeline(yesterday.toDate(), false, 3); final Timeline t5 = insertTimeline(twoDaysAgo.toDate(), false, 4); final List<Timeline> expiredTimelines = tRepository.getExpiredTimelines(); <START> Assert.assertEquals(2, expiredTimelines.size()); <END> Assert.assertEquals(ImmutableList.of(t4, t5), expiredTimelines); }</code><technical_language>happen if a timeline tl_cleanup_at is NULL</technical_language>

Target:
public void testGetExpiredTimelines() { final DateTime now = new DateTime(); final DateTime tomorrow = now.plusDays(1); final DateTime yesterday = now.minusDays(1); final DateTime twoDaysAgo = now.minusDays(2); insertTimeline(tomorrow.toDate(), true, 0); insertTimeline(tomorrow.toDate(), false, 1); insertTimeline(yesterday.toDate(), true, 2); final Timeline t4 = insertTimeline(yesterday.toDate(), false, 3); final Timeline t5 = insertTimeline(twoDaysAgo.toDate(), false, 4); insertTimeline(null, false, 5); final List<Timeline> expiredTimelines = tRepository.getExpiredTimelines(); Assert.assertEquals(2, expiredTimelines.size()); Assert.assertEquals(ImmutableList.of(t4, t5), expiredTimelines); }
Source:
<code>public List<Closeable> inject(ForkliftMessage msg, final Object instance) { final List<Closeable> closeMe = new ArrayList<>(); injectFields.keySet().stream().forEach(decorator -> { final Map<Class<?>, List<Field>> fields = injectFields.get(decorator); fields.keySet().stream().forEach(clazz -> { <START> fields.get(clazz).forEach(f -> { <END> log.trace("Inject target> Field: ({}) Decorator: ({})", f, decorator); try { Object value = getInjectableValue(f.getAnnotation(decorator), f.getName(), clazz, msg); if (value instanceof ForkliftProducerI) { closeMe.add((ForkliftProducerI)value); } if (value != null) { f.set(instance, value); } } catch (JsonMappingException | JsonParseException e) { log.warn("Unable to parse json for injection.", e); } catch (Exception e) { log.error("Error injecting data into Msg Handler", e); e.printStackTrace(); throw new RuntimeException("Error injecting data into Msg Handler"); } }); }); }); return closeMe; }</code><technical_language>this opportunity call this variable f</technical_language>

Target:
public List<Closeable> inject(ForkliftMessage msg, final Object instance) { final List<Closeable> closeMe = new ArrayList<>(); injectFields.keySet().stream().forEach(decorator -> { final Map<Class<?>, List<Field>> fields = injectFields.get(decorator); fields.keySet().stream().forEach(clazz -> { fields.get(clazz).forEach(field -> { log.trace("Inject target> Field: ({}) Decorator: ({})", field, decorator); try { Object value = getInjectableValue(field.getAnnotation(decorator), field.getName(), clazz, msg); if (value instanceof ForkliftProducerI) { closeMe.add((ForkliftProducerI)value); } if (value != null) { field.set(instance, value); } } catch (JsonMappingException | JsonParseException e) { log.warn("Unable to parse json for injection.", e); } catch (Exception e) { log.error("Error injecting data into Msg Handler", e); e.printStackTrace(); throw new RuntimeException("Error injecting data into Msg Handler"); } }); }); }); return closeMe; }
Source:
<code>public void InstallationRepositoriesEvent() throws Exception { GHEventPayload.InstallationRepositories event = GitHub.offline() .parseEventPayload(payload.asReader(), GHEventPayload.InstallationRepositories.class); assertThat(event.getAction(), is("added")); assertThat(event.getInstallation().getId(), is(957387L)); assertThat(event.getInstallation().getAccount().getLogin(), is("Codertocat")); assertThat(event.getRepositorySelection(), is("selected")); assertThat(event.getRepositoriesAdded().get(0).getId(), is(186853007L)); <START> assertThat(event.getRepositoriesAdded().get(0).getName(), is("Space")); <END> assertThat(event.getRepositoriesAdded().get(0).getFullName(), is("Codertocat/Space")); assertThat(event.getRepositoriesAdded().get(0).isPrivate(), is(false)); assertThat(event.getRepositoriesRemoved(), is(Collections.emptyList())); assertThat(event.getSender().getLogin(), is("Codertocat")); }</code><technical_language>remove these</technical_language>

Target:
public void InstallationRepositoriesEvent() throws Exception { GHEventPayload.InstallationRepositories event = GitHub.offline() .parseEventPayload(payload.asReader(), GHEventPayload.InstallationRepositories.class); assertThat(event.getAction(), is("added")); assertThat(event.getInstallation().getId(), is(957387L)); assertThat(event.getInstallation().getAccount().getLogin(), is("Codertocat")); assertThat(event.getRepositorySelection(), is("selected")); assertThat(event.getRepositoriesAdded().get(0).getId(), is(186853007L)); assertThat(event.getRepositoriesAdded().get(0).getNodeId(), is("MDEwOlJlcG9zaXRvcnkxODY4NTMwMDc=")); assertThat(event.getRepositoriesAdded().get(0).getName(), is("Space")); assertThat(event.getRepositoriesAdded().get(0).getFullName(), is("Codertocat/Space")); assertThat(event.getRepositoriesAdded().get(0).isPrivate(), is(false)); assertThat(event.getRepositoriesRemoved(), is(Collections.emptyList())); assertThat(event.getSender().getLogin(), is("Codertocat")); }
Source:
<code>protected void onResume() { super.onResume(); Disposable merlinDisposable = MerlinFlowable.from(this).subscribe(new Consumer<NetworkStatus.State>() { @Override public void accept(@NonNull NetworkStatus.State state) throws <START> Exception { <END> if (NetworkStatus.State.AVAILABLE == state) { networkStatusDisplayer.displayConnected(); } else { networkStatusDisplayer.displayDisconnected(); } } }); disposables.add(merlinDisposable); }</code><technical_language>Is Novoda style this Exception in a new line? If not, in line</technical_language>

Target:
protected void onResume() { super.onResume(); Disposable merlinDisposable = MerlinFlowable.from(this) .distinctUntilChanged() .subscribe(new NetworkConsumer(networkStatusDisplayer)); disposables.add(merlinDisposable); }
Source:
<code>private String colored(String message, Ansi.Color color, boolean addPrefix, Object ... params) { Ansi ansi = ansi().fg(color); message = ansi.a(format(evaluateEmphasis(message, color), params)).reset().toString(); <START> return addPrefix ? prefix + message : message; <END> }</code><technical_language>want prefix colored</technical_language>

Target:
private String colored(String message, Ansi.Color color, boolean addPrefix, Object ... params) { Ansi ansi = ansi().fg(color); String msgToPrint = addPrefix ? prefix + message : message; return ansi.a(format(evaluateEmphasis(msgToPrint, color), params)).reset().toString(); }
Source:
<code>private <T> Collection<Collection<T>> batch( Collection<T> collection, int batchSize ) { Collection<Collection<T>> batches = new ArrayList<>(); <START> Collection<T> batch = new ArrayList<>(); <END> int count = 0; for ( T t : collection ) { ( (ArrayList<T>) batch ).add( t ); count++; if ( count >= batchSize ) { ( (ArrayList<Collection<T>>) batches ).add( batch ); batch = new ArrayList<>(); count = 0; } } return batches; }</code><technical_language>nitpick. Suggest a init factor " new ArrayList<>(batchSize)"</technical_language>

Target:
private <T> Collection<Collection<T>> batch( Collection<T> collection, int batchSize ) { Collection<Collection<T>> batches = new ArrayList<>(); Collection<T> batch = new ArrayList<>( batchSize ); int count = 0; for ( T t : collection ) { ( (ArrayList<T>) batch ).add( t ); count++; if ( count >= batchSize ) { ( (ArrayList<Collection<T>>) batches ).add( batch ); batch = new ArrayList<>( batchSize ); count = 0; } } if ( batch != null && !batch.isEmpty() ) { ( (ArrayList<Collection<T>>) batches ).add( batch ); } return batches; }
Source:
<code><START> public IndexRecord(String msg, boolean isDeleted, boolean isExpired) { <END> this.message = msg; this.isDeleted = isDeleted; this.isExpired = isExpired; }</code><technical_language>Remove public</technical_language>

Target:
IndexRecord(String msg, boolean isDeleted, boolean isExpired) { this.message = msg; this.isDeleted = isDeleted; this.isExpired = isExpired; }
Source:
<code>public void testInspectDatastoreEntity() throws InterruptedException, ExecutionException, IOException { InspectDatastoreEntity.insepctDatastoreEntity( PROJECT_ID, datastoreNamespace, datastoreKind, TOPIC_ID, SUBSCRIPTION_ID); String output = bout.toString(); assertThat(output, containsString("Job created: ")); String jobId = output.split("Job created: ")[1].split("\n")[0]; <START> CancelDlpJobRequest request = CancelDlpJobRequest.newBuilder().setName(jobId).build(); try (DlpServiceClient client = DlpServiceClient.create()) { client.cancelDlpJob(request); } <END> }</code><technical_language>Fine if works, bet happen right other. (some hysteresis). (and a flaky test again)</technical_language>

Target:
public void testInspectDatastoreEntity() throws InterruptedException, ExecutionException, IOException { InspectDatastoreEntity.insepctDatastoreEntity( PROJECT_ID, datastoreNamespace, datastoreKind, TOPIC_ID, SUBSCRIPTION_ID); TimeUnit.SECONDS.sleep(3); String output = bout.toString(); assertThat(output, containsString("Job created: ")); String jobId = output.split("Job created: ")[1].split("\n")[0]; CancelDlpJobRequest request = CancelDlpJobRequest.newBuilder().setName(jobId).build(); try (DlpServiceClient client = DlpServiceClient.create()) { client.cancelDlpJob(request); } }
Source:
<code><START> public Object() { <END> this.timestampFormatter = new TimestampFormatter(); }</code><technical_language>Is this used? If not, private</technical_language>

Target:
private Object() { }
Source:
<code>private void setupSSLSocket() throws NoSuchAlgorithmException, IOException, KeyManagementException { <START> SSLContext sslContext = SSLContext.getInstance("TLSv1.2"); DnsTlsTrustManager trustManager = new DnsTlsTrustManager(new TrustManagerImpl(mKeyStore)); sslContext.init( null, new TrustManager[] { (TrustManager) trustManager }, new SecureRandom()); <END> mSslSocket = (SSLSocket) sslContext.getSocketFactory().createSocket(); mSslSocket.setSoTimeout(TCP_TIMEOUT); if (!TextUtils.isEmpty(mHostname)) { List<SNIServerName> names = new ArrayList<SNIServerName>(); names.add(new SNIHostName(mHostname)); SSLParameters params = mSslSocket.getSSLParameters(); params.setServerNames(names); mSslSocket.setSSLParameters(params); } }</code><technical_language>Is necessary do this work ourselves? buy compared simply calling SSLSocketFactory.getDefault()</technical_language>

Target:
private void setupSSLSocket() throws NoSuchAlgorithmException, IOException, KeyManagementException, KeyStoreException { String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); tmf.init(mKeyStore); SSLContext sslContext = SSLContext.getInstance("TLSv1.2"); sslContext.init(null, tmf.getTrustManagers(), new SecureRandom()); mSslSocket = (SSLSocket) sslContext.getSocketFactory().createSocket(); mSslSocket.setSoTimeout(TCP_TIMEOUT); if (!TextUtils.isEmpty(mHostname)) { List<SNIServerName> names = new ArrayList<SNIServerName>(); names.add(new SNIHostName(mHostname)); SSLParameters params = mSslSocket.getSSLParameters(); params.setServerNames(names); mSslSocket.setSSLParameters(params); } }
Source:
<code>public String getType() { if (fileName.endsWith(".mp3")) { return "audio/mp3"; } else if (fileName.endsWith(".png")) { <START> return "image/png"; <END> } else { return null; } }</code><technical_language>MimeTypeMap.getMimeTypeFromExtension? work for more file types, in case class for more later</technical_language>

Target:
public String getType() { String extension = MimeTypeMap.getFileExtensionFromUrl(fileName); return MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension); }
Source:
<code>public JSON toJSON() { if (values == null) { return null; } JSONObject jo = new JSONObject(); for (Entry<String, T> val : values.entrySet()) { T value = val.getValue(); <START> jo.put(val.getKey(), ApiUtil.getJsonFriendlyString((String) value)); <END> } return jo; }</code><technical_language>if is required, lead a ClassCastException (not ApiResponseSets Strings)</technical_language>

Target:
public JSON toJSON() { if (values == null) { return null; } JSONObject jo = new JSONObject(); for (Entry<String, T> val : values.entrySet()) { T value = val.getValue(); if (value instanceof String) { jo.put(val.getKey(), JsonUtil.getJsonFriendlyString((String) value)); } else { jo.put(val.getKey(), value); } } return jo; }
Source:
<code>public int getNumCores() { <START> if (getBoolean(JobConfig.JOB_AUTOSIZING_ENABLED, false) && containsKey(JobConfig.JOB_AUTOSIZING_CONTAINER_MAX_CORES)) { <END> return getInt(JobConfig.JOB_AUTOSIZING_CONTAINER_MAX_CORES); } else if (containsKey(CLUSTER_MANAGER_MAX_CORES)) { return getInt(CLUSTER_MANAGER_MAX_CORES); } else if (containsKey(CONTAINER_MAX_CPU_CORES)) { log.info("Configuration is deprecated. Please use {}", CONTAINER_MAX_CPU_CORES, CLUSTER_MANAGER_MAX_CORES); return getInt(CONTAINER_MAX_CPU_CORES); } else { return DEFAULT_CPU_CORES; } }</code><technical_language>this getAutosizingEnabled instead of checking config directly? if getAutosizingEnabled changed in future, this change</technical_language>

Target:
public int getNumCores() { if (new JobConfig(this).getAutosizingEnabled() && containsKey(JobConfig.JOB_AUTOSIZING_CONTAINER_MAX_CORES)) { return getInt(JobConfig.JOB_AUTOSIZING_CONTAINER_MAX_CORES); } else if (containsKey(CLUSTER_MANAGER_MAX_CORES)) { return getInt(CLUSTER_MANAGER_MAX_CORES); } else if (containsKey(CONTAINER_MAX_CPU_CORES)) { log.info("Configuration is deprecated. Please use {}", CONTAINER_MAX_CPU_CORES, CLUSTER_MANAGER_MAX_CORES); return getInt(CONTAINER_MAX_CPU_CORES); } else { return DEFAULT_CPU_CORES; } }
Source:
<code>protected boolean isKieContainerRemovalAllowed(ConfigMap cm, KieServerState newState) { KieServerState state = (KieServerState) xs.fromXML(cm.getData().get(CFG_MAP_DATA_KEY)); for (KieContainerResource container : state.getContainers()) { if (container.getStatus().equals(KieContainerStatus.STOPPED) && newState.getContainers().stream() <START> .filter(c -> c.getContainerId().equals(container.getContainerId())) <END> .collect(Collectors.toList()).isEmpty()) { logger.warn("Removing STOPPED KieContainer by KieServer process is not allowed."); return false; } } return true; }</code><technical_language>replaced .noneMatch(c -> c.getContainerId().equals(container.getContainerId())))</technical_language>

Target:
public boolean isKieContainerRemovalAllowed(ConfigMap cm, KieServerState newState) { KieServerState state = (KieServerState) xs.fromXML(cm.getData().get(CFG_MAP_DATA_KEY)); for (KieContainerResource container : state.getContainers()) { if (container.getStatus().equals(KieContainerStatus.STOPPED) && newState.getContainers().stream() .noneMatch(c -> c.getContainerId().equals(container.getContainerId()))) { logger.warn("Removing STOPPED KieContainer by KieServer process is not allowed."); return false; } } return true; }
Source:
<code>protected Partitioner.Partition<AbstractKafkaInputOperator> createPartition(Set<AbstractKafkaPartitioner.PartitionMeta> partitionAssignment) { Kryo kryo = new Kryo(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); Output output = new Output(bos); kryo.writeObject(output, prototypeOperator); output.close(); Input lInput = new Input(bos.toByteArray()); <START> Partitioner.Partition<AbstractKafkaInputOperator> p = new DefaultPartition<>(kryo.readObject(lInput, prototypeOperator.getClass())); <END> p.getPartitionedInstance().setAssignment(partitionAssignment); return p; }</code><technical_language>compile error in Eclipse code is littered type warnings</technical_language>

Target:
protected Partitioner.Partition<AbstractKafkaInputOperator> createPartition(Set<AbstractKafkaPartitioner.PartitionMeta> partitionAssignment) { Kryo kryo = new Kryo(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); Output output = new Output(bos); kryo.writeObject(output, prototypeOperator); output.close(); Input lInput = new Input(bos.toByteArray()); Partitioner.Partition<AbstractKafkaInputOperator> p = (Partitioner.Partition<AbstractKafkaInputOperator>) new DefaultPartition<>(kryo.readObject(lInput, prototypeOperator.getClass())); p.getPartitionedInstance().assign(partitionAssignment); return p; }
Source:
<code>public void onSelectionChanged(PreviewNode selectedNode) { Either<ResourceChange, TextEdit> data = selectedNode.getData(); if (data != null && data.isLeft()) { view.showDiff(null); return; } PreviewNode node = nodes.get(selectedNode.getUri()); List<TextEdit> edits = new ArrayList<>(); if (node.getId().equals(selectedNode.getId())) { for (PreviewNode child : node.getChildren()) { TextEdit right = child.getData().getRight(); if (child.isEnable()) { edits.add(right); } } } else if (data != null && selectedNode.isEnable()) { edits.add(data.getRight()); } Path path = toPath(selectedNode.getUri()).removeFirstSegments(1); Container workspaceRoot = appContext.getWorkspaceRoot(); Promise<Optional<File>> file = workspaceRoot.getFile(path); file.then( arg -> { if (!arg.isPresent()) { return; } <START> File existedFile = arg.get(); <END> existedFile .getContent() .then( content -> { ChangePreview changePreview = dtoFactory.createDto(ChangePreview.class); changePreview.setFileName(existedFile.getName()); changePreview.setOldContent(content); StringBuilder output = new StringBuilder(); new StringStreamEditor(edits, content, output).transform(); String result = output.toString(); changePreview.setNewContent(result); view.showDiff(changePreview); }); }); }</code><technical_language>"existingFile"</technical_language>

Target:
public void onSelectionChanged(PreviewNode selectedNode) { Either<ResourceChange, TextEdit> data = selectedNode.getData(); if (data != null && data.isLeft()) { view.showDiff(null); return; } List<TextEdit> edits = collectTextEditsForSelectedNode(selectedNode); updateContentInCompareWidget(selectedNode, edits); }