auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void close(final boolean clean) { switch (state()) { case CREATED: case SUSPENDED: if (clean) { stateMgr.checkpoint(Collections.emptyMap()); offsetSnapshotSinceLastCommit = new HashMap<>(stateMgr.changelogOffsets()); } executeAndMaybeSwallow( clean, () -> StateManagerUtil.closeStateManager( log, logPrefix, clean, eosEnabled, stateMgr, stateDirectory, TaskType.STANDBY ), "state manager close", log ); break; case CLOSED: log.trace("Skip closing since state is {}", state()); return; <START> case RESTORING: END> case RUNNING: throw new IllegalStateException("Illegal state " + state() + " while closing standby task " + id); default: throw new IllegalStateException("Unknown state " + state() + " while closing standby task " + id); } closeTaskSensor.record(); transitionTo(State.CLOSED); }</code><technical_language>a standby task is in</technical_language>

Target:
private void close(final boolean clean) { switch (state()) { case CREATED: case SUSPENDED: executeAndMaybeSwallow( clean, () -> StateManagerUtil.closeStateManager( log, logPrefix, clean, eosEnabled, stateMgr, stateDirectory, TaskType.STANDBY ), "state manager close", log ); break; case CLOSED: log.trace("Skip closing since state is {}", state()); return; case RESTORING: case RUNNING: throw new IllegalStateException("Illegal state " + state() + " while closing standby task " + id); default: throw new IllegalStateException("Unknown state " + state() + " while closing standby task " + id); } closeTaskSensor.record(); transitionTo(State.CLOSED); }
Source:
<code>private void backgroundOperationsLoop() { while ( !Thread.interrupted() ) { OperationAndData<?> operationAndData; try { operationAndData = backgroundOperations.take(); if ( debugListener != null ) { debugListener.listen(operationAndData); } } catch ( InterruptedException ignored ) { break; <START> } <END> performBackgroundOperation(operationAndData); } }</code><technical_language>This is correct. _Always_ re-set interrupted state of threads. break statement exits while condition</technical_language>

Target:
private void backgroundOperationsLoop() { while ( !Thread.currentThread().isInterrupted() ) { OperationAndData<?> operationAndData; try { operationAndData = backgroundOperations.take(); if ( debugListener != null ) { debugListener.listen(operationAndData); } } catch ( InterruptedException e ) { Thread.currentThread().interrupt(); break; } performBackgroundOperation(operationAndData); } }
Source:
<code><START> public void getDesignProcessDefinition_Should_Return_Design() throws Exception{ <END> int processDefinitionId = 123; when(tenantAccessor.getProcessDefinitionService()).thenReturn(processDefinitionService); doReturn(processDefinitionService).when(tenantAccessor).getProcessDefinitionService(); DesignProcessDefinition designProcessDefinition = mock(DesignProcessDefinition.class); when(processDefinitionService.getDesignProcessDefinition(processDefinitionId)).thenReturn(designProcessDefinition); DesignProcessDefinition designProcessDefinitionResult = processAPI.getDesignProcessDefinition(processDefinitionId); assertThat(designProcessDefinitionResult).isSameAs(designProcessDefinition); }</code><technical_language>this test "API.getDesignProcessDefinition() call service.getDesignProcessDefinition()" ? In case, suppose verify(service).getDesignProcessDefinition();</technical_language>

Target:
public void getDesignProcessDefinition_Should_Return_Design() throws Exception { int processDefinitionId = 123; when(tenantAccessor.getProcessDefinitionService()).thenReturn(processDefinitionService); doReturn(processDefinitionService).when(tenantAccessor).getProcessDefinitionService(); DesignProcessDefinition designProcessDefinition = mock(DesignProcessDefinition.class); when(processDefinitionService.getDesignProcessDefinition(processDefinitionId)).thenReturn(designProcessDefinition); DesignProcessDefinition designProcessDefinitionResult = processAPI.getDesignProcessDefinition(processDefinitionId); assertThat(designProcessDefinitionResult).isSameAs(designProcessDefinition); verify(processDefinitionService).getDesignProcessDefinition(processDefinitionId); }
Source:
<code>public static RpcMetrics createRpcMetrics(MethodDescriptor<?, ?> descriptor) { String fullMethodName = descriptor.getFullMethodName(); MetricRegistry debugRegistry = getMetricRegistry(MetricLevel.Debug); MetricRegistry infoRegistry = getMetricRegistry(MetricLevel.Info); return new RpcMetrics( <START> infoRegistry.createTimer(fullMethodName + ".operation.latency"), <END> debugRegistry.createTimer(fullMethodName + ".rpc.latency"), infoRegistry.createCounter(fullMethodName + ".retry.count"), infoRegistry.createCounter(fullMethodName + ".failure.count"), infoRegistry.createCounter(fullMethodName + ".retries.exhausted.count")); }</code><technical_language>Suggested this out-of-band @sduskis nice handle this instead createTimer, createCounter methods metric string name return registry. For example append ".loglevel" end of strings in slf4j config</technical_language>

Target:
public static RpcMetrics createRpcMetrics(MethodDescriptor<?, ?> descriptor) { String fullMethodName = descriptor.getFullMethodName(); return new RpcMetrics( BigtableClientMetrics.timer(MetricLevel.Info, fullMethodName + ".operation.latency"), BigtableClientMetrics.timer(MetricLevel.Debug, fullMethodName + ".rpc.latency"), BigtableClientMetrics.counter(MetricLevel.Info, fullMethodName + ".retry.count"), BigtableClientMetrics.counter(MetricLevel.Info, fullMethodName + ".failure.count"), BigtableClientMetrics.counter(MetricLevel.Info, fullMethodName + ".retries.exhausted.count")); }
Source:
<code>public List<UpdateSite.Warning> getActiveCoreWarnings() { List<UpdateSite.Warning> CoreWarnings = new ArrayList<>(); for (UpdateSite.Warning warning : getActiveWarnings()) { if (!UpdateSite.Warning.TYPE_CORE.equals(warning.type) <START> || !UpdateSite.Warning.NAME_CORE.equals(warning.name)) { <END> continue; } CoreWarnings.add(warning); } return CoreWarnings; }</code><technical_language>do care about, type name? Pick consistent</technical_language>

Target:
public List<UpdateSite.Warning> getActiveCoreWarnings() { List<UpdateSite.Warning> CoreWarnings = new ArrayList<>(); for (UpdateSite.Warning warning : getActiveWarnings()) { if (warning.type != UpdateSite.Warning.Type.CORE) { continue; } CoreWarnings.add(warning); } return CoreWarnings; }
Source:
<code>public AccountService getAccountService() { try { long startTimeMs = System.currentTimeMillis(); logger.info("Starting a MySqlAccountService"); <START> ScheduledExecutorService scheduler = <END> accountServiceConfig.updaterPollingIntervalMs > 0 ? Utils.newScheduler(1, MYSQL_ACCOUNT_UPDATER_PREFIX, false) : null; MySqlAccountService mySqlAccountService = new MySqlAccountService(accountServiceMetrics, accountServiceConfig, scheduler); long spentTimeMs = System.currentTimeMillis() - startTimeMs; logger.info("MySqlAccountService started, took ms", spentTimeMs); accountServiceMetrics.startupTimeInMs.update(spentTimeMs); return mySqlAccountService; } catch (Exception e) { throw new IllegalStateException("Could not instantiate MySqlAccountService", e); } }</code><technical_language>advantage of creating scheduler in factory instead of in service itself</technical_language>

Target:
public AccountService getAccountService() { try { long startTimeMs = System.currentTimeMillis(); logger.info("Starting a MySqlAccountService"); MySqlAccountStore mySqlAccountStore = null; try { mySqlAccountStore = new MySqlAccountStore(accountServiceConfig); } catch (SQLException e) { logger.error("MySQL account store creation failed", e); } MySqlAccountService mySqlAccountService = new MySqlAccountService(accountServiceMetrics, accountServiceConfig, mySqlAccountStore); long spentTimeMs = System.currentTimeMillis() - startTimeMs; logger.info("MySqlAccountService started, took ms", spentTimeMs); accountServiceMetrics.startupTimeInMs.update(spentTimeMs); return mySqlAccountService; } catch (Exception e) { throw new IllegalStateException("Could not instantiate MySqlAccountService", e); } }
Source:
<code>public static Iterable<? extends Object> parameters() { return Arrays.asList( <START> new Object[]{"BOOLEAN", Schema.create(Schema.Type.BOOLEAN), new SqoopOptions()}, <END> new Object[]{"INT", Schema.create(Schema.Type.INT), new SqoopOptions()}, new Object[]{"BIGINT", Schema.create(Schema.Type.LONG), new SqoopOptions()}, new Object[]{"FLOAT", Schema.create(Schema.Type.FLOAT), new SqoopOptions()}, new Object[]{"DOUBLE", Schema.create(Schema.Type.DOUBLE), new SqoopOptions()}, new Object[]{"STRING", Schema.createEnum("ENUM", "doc", "namespce", new ArrayList<>()), new SqoopOptions()}, new Object[]{"STRING", Schema.create(Schema.Type.STRING), new SqoopOptions()}, new Object[]{"BINARY", Schema.create(Schema.Type.BYTES), new SqoopOptions()}, new Object[]{"BINARY", Schema.createFixed("Fixed", "doc", "space", 1), new SqoopOptions()}, new Object[]{"BINARY", createDecimal(20, 10), new SqoopOptions()}, new Object[]{"DECIMAL (20, 10)", createDecimal(20, 10), createSqoopOptionsWithLogicalTypesEnabled()} ); }</code><technical_language>static import create methods Schema lines shorter</technical_language>

Target:
public static Iterable<? extends Object> parameters() { return Arrays.asList( new Object[]{"BOOLEAN", create(Type.BOOLEAN), new SqoopOptions()}, new Object[]{"INT", create(Type.INT), new SqoopOptions()}, new Object[]{"BIGINT", create(Type.LONG), new SqoopOptions()}, new Object[]{"FLOAT", create(Type.FLOAT), new SqoopOptions()}, new Object[]{"DOUBLE", create(Type.DOUBLE), new SqoopOptions()}, new Object[]{"STRING", createEnum("ENUM", "doc", "namespace", new ArrayList<>()), new SqoopOptions()}, new Object[]{"STRING", create(Type.STRING), new SqoopOptions()}, new Object[]{"BINARY", create(Type.BYTES), new SqoopOptions()}, new Object[]{"BINARY", createFixed("Fixed", "doc", "space", 1), new SqoopOptions()}, new Object[]{"BINARY", createDecimal(20, 10), new SqoopOptions()}, new Object[]{"BINARY", create(Type.BYTES), createSqoopOptionsWithLogicalTypesEnabled()}, new Object[]{"DECIMAL (20, 10)", createDecimal(20, 10), createSqoopOptionsWithLogicalTypesEnabled()} ); }
Source:
<code>private Path checkRootDir(final Path rd, final Configuration c, final FileSystem fs) throws IOException { FSUtils.waitOnSafeMode(c, c.getInt(HConstants.THREAD_WAKE_FREQUENCY, 10 * 1000)); FileStatus status; try { status = fs.getFileStatus(rd); } catch (FileNotFoundException e) { status = null; } try { if (status == null) { if (!fs.mkdirs(rd)) { throw new IOException("Can not create root dir: " + rd); } FSUtils.setVersion(fs, rd, c.getInt(HConstants.THREAD_WAKE_FREQUENCY, 10 * 1000), c.getInt( HConstants.VERSION_FILE_WRITE_ATTEMPTS, HConstants.DEFAULT_VERSION_FILE_WRITE_ATTEMPTS)); } else { if (!status.isDirectory()) { throw new IllegalArgumentException(rd + " is not a directory"); } FSUtils.checkVersion(fs, rd, true, c.getInt(HConstants.THREAD_WAKE_FREQUENCY, 10 * 1000), c.getInt(HConstants.VERSION_FILE_WRITE_ATTEMPTS, HConstants.DEFAULT_VERSION_FILE_WRITE_ATTEMPTS)); } } catch (DeserializationException de) { LOG.error(HBaseMarkers.FATAL, "Please fix invalid configuration for " + HConstants.HBASE_DIR, de); throw new IOException(de); } catch (IllegalArgumentException iae) { LOG.error(HBaseMarkers.FATAL, <START> "Please fix invalid configuration for " + HConstants.HBASE_DIR + " " + rd.toString(), iae); <END> throw iae; } if (!FSUtils.checkClusterIdExists(fs, rd, c.getInt(HConstants.THREAD_WAKE_FREQUENCY, 10 * 1000))) { FSUtils.setClusterId(fs, rd, new ClusterId(), c.getInt(HConstants.THREAD_WAKE_FREQUENCY, 10 * 1000)); } clusterId = FSUtils.getClusterId(fs, rd); return rd; }</code><technical_language>placeholders for HConstants.HBASE_DIR rd.toString()? Also, suffice</technical_language>

Target:
private void checkRootDir(final Path rd, final Configuration c, final FileSystem fs) throws IOException { int threadWakeFrequency = c.getInt(HConstants.THREAD_WAKE_FREQUENCY, 10 * 1000); FSUtils.waitOnSafeMode(c, threadWakeFrequency); FileStatus status; try { status = fs.getFileStatus(rd); } catch (FileNotFoundException e) { status = null; } int versionFileWriteAttempts = c.getInt(HConstants.VERSION_FILE_WRITE_ATTEMPTS, HConstants.DEFAULT_VERSION_FILE_WRITE_ATTEMPTS); try { if (status == null) { if (!fs.mkdirs(rd)) { throw new IOException("Can not create configured '" + HConstants.HBASE_DIR + "' " + rd); } FSUtils.setVersion(fs, rd, threadWakeFrequency, versionFileWriteAttempts); } else { if (!status.isDirectory()) { throw new IllegalArgumentException( "Configured '" + HConstants.HBASE_DIR + "' " + rd + " is not a directory."); } FSUtils.checkVersion(fs, rd, true, threadWakeFrequency, versionFileWriteAttempts); } } catch (DeserializationException de) { LOG.error(HBaseMarkers.FATAL, "Please fix invalid configuration for '{}' {}", HConstants.HBASE_DIR, rd, de); throw new IOException(de); } catch (IllegalArgumentException iae) { LOG.error(HBaseMarkers.FATAL, "Please fix invalid configuration for '{}' {}", HConstants.HBASE_DIR, rd, iae); throw iae; } if (!FSUtils.checkClusterIdExists(fs, rd, threadWakeFrequency)) { FSUtils.setClusterId(fs, rd, new ClusterId(), threadWakeFrequency); } clusterId = FSUtils.getClusterId(fs, rd); }
Source:
<code>private Collection<FeedbackResponseComment> getFeedbackResponseCommentEntitiesForQuestionInSection( String questionId, String section) { Map<Long, FeedbackResponseComment> comments = new HashMap<>(); List<FeedbackResponseComment> firstQueryResponseComments = load() .filter("feedbackQuestionId =", questionId) .filter("giverSection =", section) .list(); for (FeedbackResponseComment comment : firstQueryResponseComments) { comments.put(comment.getFeedbackResponseCommentId(), comment); } List<FeedbackResponseComment> secondQueryResponseComments = load() .filter("feedbackQuestionId =", questionId) .filter("receiverSection =", section) <START> .list(); <END> for (FeedbackResponseComment comment : secondQueryResponseComments) { comments.put(comment.getFeedbackResponseCommentId(), comment); } return comments.values(); }</code><technical_language>Instead of prefixing name of 2 lists first, second, give more meaningful prefixes giver, receiver, is true intention here</technical_language>

Target:
private Collection<FeedbackResponseComment> getFeedbackResponseCommentEntitiesForQuestionInSection( String questionId, String section) { Map<Long, FeedbackResponseComment> comments = new HashMap<>(); List<FeedbackResponseComment> responseCommentsFromSection = load() .filter("feedbackQuestionId =", questionId) .filter("giverSection =", section) .list(); for (FeedbackResponseComment comment : responseCommentsFromSection) { comments.put(comment.getFeedbackResponseCommentId(), comment); } List<FeedbackResponseComment> responseCommentsToSection = load() .filter("feedbackQuestionId =", questionId) .filter("receiverSection =", section) .list(); for (FeedbackResponseComment comment : responseCommentsToSection) { comments.put(comment.getFeedbackResponseCommentId(), comment); } return comments.values(); }
Source:
<code>public boolean equals(Object obj) { <START> if (this == obj) <END> return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; TestWithParameters other = (TestWithParameters) obj; if (fName == null) { if (other.fName != null) return false; } else if (!fName.equals(other.fName)) return false; return Arrays.equals(fParameters, other.fParameters) && fTestClass.equals(other.fTestClass); }</code><technical_language>Please braces</technical_language>

Target:
public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } TestWithParameters other = (TestWithParameters) obj; return fName.equals(other.fName) && fParameters.equals(other.fParameters) && fTestClass.equals(other.fTestClass); }
Source:
<code>public int getMaxCapacity() { <START> readLock.lock(); <END> try { return maxCapacity; } finally { readLock.unlock(); } }</code><technical_language>add lock here</technical_language>

Target:
public int getMaxCapacity() { return maxCapacity; }
Source:
<code>public void performOperations(List<LuceneWork> workList, IndexingMonitor monitor) { if (this.cache.getCacheConfiguration().clustering().cacheMode().isClustered()) { readLock.lock(); <START> Address localAddress = rpcManager.getAddress(); <END> try { Map<Address, List<LuceneWork>> workByAddress = partitionWorkByAddress(workList); logDebug("Applying work @ %s, workMap is %s", localAddress, workByAddress); List<LuceneWork> localWork = workByAddress.get(localAddress); if (localWork != null && !localWork.isEmpty()) { logDebug("About to apply work locally %s, hasOwnership=%s", localWork, hasOwnership); super.performOperations(localWork, monitor); logDebug("Work applied"); workByAddress.remove(localAddress); } workByAddress.entrySet().stream().forEach(entry -> this.sendWork(entry.getValue(), entry.getKey())); } finally { readLock.unlock(); } } else { super.performOperations(workList, monitor); } }</code><technical_language>put this in try, a bit cleaner lock :)</technical_language>

Target:
public void performOperations(List<LuceneWork> workList, IndexingMonitor monitor) { if (this.cache.getCacheConfiguration().clustering().cacheMode().isClustered()) { readLock.lock(); try { Address localAddress = rpcManager.getAddress(); Map<Address, List<LuceneWork>> workByAddress = partitionWorkByAddress(workList); logDebug("Applying work @ %s, workMap is %s", localAddress, workByAddress); List<LuceneWork> localWork = workByAddress.get(localAddress); if (localWork != null && !localWork.isEmpty()) { logDebug("About to apply work locally %s, hasOwnership=%s", localWork, hasOwnership); super.performOperations(localWork, monitor); logDebug("Work applied"); workByAddress.remove(localAddress); } workByAddress.entrySet().forEach(entry -> this.sendWork(entry.getValue(), entry.getKey())); } finally { readLock.unlock(); } } else { super.performOperations(workList, monitor); } }
Source:
<code>private String[] getMessages(MultipartBody inputDataMap) { try { <START> if(inputDataMap.getAttachmentObject("messageIds", String.class) != null) { <END> String messageIds = inputDataMap.getAttachmentObject("messageIds", String.class); return messageIds.split(","); } } catch (Exception e) { throw new ApiException(e); } return null; }</code><technical_language>resolveStringFromMap applies</technical_language>

Target:
private String[] getMessages(MultipartBody inputDataMap) { String[] msgArr = null; try { msgArr = resolveStringFromMap(inputDataMap, "message").map(messageIds -> { return messageIds.split(","); }).orElse(null); } catch (Exception e) { throw new ApiException(e); } return msgArr; }
Source:
<code>public void fails_with_ISE_when_default_organization_does_not_exist_in_table_ORGANIZATIONS() throws SQLException { <START> insertDefaultOrganizationUuid("blabla"); <END> expectedException.expect(IllegalStateException.class); expectedException.expectMessage("Default organization with uuid 'blabla' does not exist in table ORGANIZATIONS"); underTest.execute(); }</code><technical_language>method name is misleading. insert a default organization uuid failing. Why</technical_language>

Target:
public void fails_with_ISE_when_default_organization_does_not_exist_in_table_ORGANIZATIONS() throws SQLException { setDefaultOrganizationProperty("blabla"); expectedException.expect(IllegalStateException.class); expectedException.expectMessage("Default organization with uuid 'blabla' does not exist in table ORGANIZATIONS"); underTest.execute(); }
Source:
<code>protected static byte[] getSignedContent(String queryString) throws SecurityPolicyException { log.debug("Constructing signed content string from URL query string "+queryString ); String constructed = buildSignedContentString(queryString); if (DatatypeHelper.isEmpty(constructed)) { throw new SecurityPolicyException( "Could not extract signed content string from query string"); } <START> log.debug("Constructed signed content string for HTTP-Redirect DEFLATE "+ constructed); <END> try { return constructed.getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { if (log.isDebugEnabled()) { log.debug("Encoding not supported.", e); } return new byte[0]; } }</code><technical_language>Please add isDebugEnabled() spacing "+"</technical_language>

Target:
protected static byte[] getSignedContent(String queryString) throws SecurityPolicyException { if (log.isDebugEnabled()) { log.debug("Constructing signed content string from URL query string " + queryString); } String constructed = buildSignedContentString(queryString); if (DatatypeHelper.isEmpty(constructed)) { throw new SecurityPolicyException( "Could not extract signed content string from query string"); } if (log.isDebugEnabled()) { log.debug("Constructed signed content string for HTTP-Redirect DEFLATE " + constructed); } try { return constructed.getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { if (log.isDebugEnabled()) { log.debug("Encoding not supported.", e); } return new byte[0]; } }
Source:
<code>int invalidMethodReturningPrimitive() { <START> assertTrue(false); <END> return 1; }</code><technical_language>Instead of assertTrue(false), recommend invoking fail() failure message, do for rest of this test class</technical_language>

Target:
int invalidMethodReturningPrimitive() { fail("This method should never have been called."); return 1; }
Source:
<code>public ArrayList<DiskErrorPolicy> getDiskErrorPolicyList() { ArrayList<DiskErrorPolicy> diskErrorPolicy = new ArrayList<>( Arrays.asList(new DiskErrorPolicy[] { DiskErrorPolicy.REPORT, DiskErrorPolicy.ENOSPC, DiskErrorPolicy.STOP, DiskErrorPolicy.IGNORE })); <START> return diskErrorPolicy; <END> }</code><technical_language>I think: return Arrays.asList({DiskErrorPolicy.REPORT, DiskErrorPolicy.ENOSPC, DiskErrorPolicy.STOP, DiskErrorPolicy.IGNORE}); Is more concise create array lists</technical_language>

Target:
public List<DiskErrorPolicy> getDiskErrorPolicyList() { return Arrays.asList( DiskErrorPolicy.REPORT, DiskErrorPolicy.ENOSPC, DiskErrorPolicy.STOP, DiskErrorPolicy.IGNORE ); }
Source:
<code>public void testResourceMetadataXML() throws Exception { XMLUnit.setXpathNamespaceContext(NS_XML); <START> Document doc = getAsDOM("/rest/resource/mydir/myres?operation=metadata&format=xml"); <END> XMLAssert.assertXpathEvaluatesTo("myres", "/ResourceMetadata/name", doc); XMLAssert.assertXpathEvaluatesTo("/mydir", "/ResourceMetadata/parent/path", doc); XMLAssert.assertXpathEvaluatesTo("http://localhost:8080/geoserver/rest/resources/mydir?format=xml", "/ResourceMetadata/parent/atom:link/@href", doc); XMLAssert.assertXpathEvaluatesTo(FORMAT.format(myRes.lastmodified()), "/ResourceMetadata/lastModified", doc); }</code><technical_language>@NielsCharlier change this operation=mEtAdATa test case insensitivity</technical_language>

Target:
public void testResourceMetadataXML() throws Exception { XMLUnit.setXpathNamespaceContext(NS_XML); Document doc = getAsDOM("/rest/resource/mydir/myres?operation=mEtAdATa&format=xml"); XMLAssert.assertXpathEvaluatesTo("myres", "/ResourceMetadata/name", doc); XMLAssert.assertXpathEvaluatesTo("/mydir", "/ResourceMetadata/parent/path", doc); XMLAssert.assertXpathEvaluatesTo("http://localhost:8080/geoserver/rest/resources/mydir?format=xml", "/ResourceMetadata/parent/atom:link/@href", doc); XMLAssert.assertXpathEvaluatesTo(FORMAT.format(myRes.lastmodified()), "/ResourceMetadata/lastModified", doc); }
Source:
<code>public void refresh() { AccountDiffPreference diffPrefs; if (patchTable == null) { <START> diffPrefs = (new ListenableAccountDiffPreference()).get(); <END> } else { diffPrefs = patchTable.getPreferences().get(); } Util.DETAIL_SVC.patchSetDetail(patchSet.getId(), diffBaseId, diffPrefs, new GerritCallback<PatchSetDetail>() { @Override public void onSuccess(PatchSetDetail result) { if (patchSet.getId().equals(diffBaseId)) { patchTable.setVisible(false); actionsPanel.setVisible(false); } else { if (patchTable != null) { patchTable.removeFromParent(); } patchTable = new PatchTable(); patchTable.setPatchSetIdToCompareWith(diffBaseId); patchTable.display(result); body.add(patchTable); for (ClickHandler clickHandler : registeredClickHandler) { patchTable.addClickHandler(clickHandler); } } } }); }</code><technical_language>Style-nit: Parens necessary new operator</technical_language>

Target:
public void refresh() { AccountDiffPreference diffPrefs; if (patchTable == null) { diffPrefs = new ListenableAccountDiffPreference().get(); } else { diffPrefs = patchTable.getPreferences().get(); } Util.DETAIL_SVC.patchSetDetail(patchSet.getId(), diffBaseId, diffPrefs, new GerritCallback<PatchSetDetail>() { @Override public void onSuccess(PatchSetDetail result) { if (patchSet.getId().equals(diffBaseId)) { patchTable.setVisible(false); actionsPanel.setVisible(false); } else { if (patchTable != null) { patchTable.removeFromParent(); } patchTable = new PatchTable(); patchTable.setPatchSetIdToCompareWith(diffBaseId); patchTable.display(result); body.add(patchTable); for (ClickHandler clickHandler : registeredClickHandler) { patchTable.addClickHandler(clickHandler); } } } }); }
Source:
<code>public void iterableRemoves(Iterable<?> iterable, Object value) { if (iterable == null) return; if (iterable instanceof Collection) { <START> ((Collection<?>) iterable).removeIf(o -> comparator.compare(o, value) == 0); <END> } Iterator<?> iterator = iterable.iterator(); while (iterator.hasNext()) { if (comparator.compare(iterator.next(), value) == 0) { iterator.remove(); } } }</code><technical_language>I run ContainsOnlyPerfTest changes, is faster, I fail is O(n2), enlighten please ;-)</technical_language>

Target:
public void iterableRemoves(Iterable<?> iterable, Object value) { if (iterable == null) return; if (iterable instanceof Collection) { ((Collection<?>) iterable).removeIf(o -> comparator.compare(o, value) == 0); } else { Iterator<?> iterator = iterable.iterator(); while (iterator.hasNext()) { if (comparator.compare(iterator.next(), value) == 0) { iterator.remove(); } } } }
Source:
<code>private void marshallAttributes(XMLExtendedStreamWriter writer, ModelNode model, Collection<AttributeDefinition> attributes, String group) throws XMLStreamException { boolean started = false; boolean possibleElements = attributes.stream().filter(attributeDefinition -> attributeDefinition.getParser().isParseAsElement()).count() > 0; for (AttributeDefinition ad : attributes.stream().sorted((o1, o2) -> o1.getParser().isParseAsElement() ? 1 : -1).collect(Collectors.toList())) { AttributeMarshaller marshaller = attributeMarshallers.getOrDefault(ad.getName(), ad.getAttributeMarshaller()); <START> if (marshaller.isMarshallable(ad, model, true)) { <END> if (!started && group != null) { if (possibleElements) { writer.writeStartElement(group); } else { writer.writeEmptyElement(group); } started = true; } marshaller.marshall(ad, model, marshallDefaultValues, writer); } } if (possibleElements && started) { writer.writeEndElement(); } }</code><technical_language>this if (marshaller.isMarshallable(ad, model, marshallDefaultValues)) {</technical_language>

Target:
private void marshallAttributes(XMLExtendedStreamWriter writer, ModelNode model, Collection<AttributeDefinition> attributes, String group) throws XMLStreamException { boolean started = false; boolean possibleElements = attributes.stream().filter(attributeDefinition -> attributeDefinition.getParser().isParseAsElement()).count() > 0; for (AttributeDefinition ad : attributes.stream().sorted((o1, o2) -> o1.getParser().isParseAsElement() ? 1 : -1).collect(Collectors.toList())) { AttributeMarshaller marshaller = attributeMarshallers.getOrDefault(ad.getName(), ad.getAttributeMarshaller()); if (marshaller.isMarshallable(ad, model, marshallDefaultValues)) { if (!started && group != null) { if (possibleElements) { writer.writeStartElement(group); } else { writer.writeEmptyElement(group); } started = true; } marshaller.marshall(ad, model, marshallDefaultValues, writer); } } if (possibleElements && started) { writer.writeEndElement(); } }
Source:
<code>public CoordinatorBasicAuthenticatorCacheNotifier( AuthenticatorMapper authenticatorMapper, DruidNodeDiscoveryProvider discoveryProvider, @EscalatedClient HttpClient httpClient ) { userCacheNotifier = new CommonCacheNotifier( <START> initAuthenticatorConfigMap(authenticatorMapper), <END> discoveryProvider, httpClient, "/druid-ext/basic-security/authentication/listen/%s", "CoordinatorBasicAuthenticatorCacheNotifier" ); configCacheNotifier = new CommonCacheNotifier( initAuthenticatorConfigMap(authenticatorMapper), discoveryProvider, httpClient, "/druid-ext/basic-security/authentication/listen/config/%s", "CoordinatorBasicAuthenticatorCacheNotifier" ); }</code><technical_language>this initAuthenticatorUserMap instead of configMap</technical_language>

Target:
public CoordinatorBasicAuthenticatorCacheNotifier( AuthenticatorMapper authenticatorMapper, DruidNodeDiscoveryProvider discoveryProvider, @EscalatedClient HttpClient httpClient ) { userCacheNotifier = new CommonCacheNotifier( initAuthenticatorConfigMap(authenticatorMapper), discoveryProvider, httpClient, "/druid-ext/basic-security/authentication/listen/%s", "CoordinatorBasicAuthenticatorCacheNotifier" ); }
Source:
<code>public static Slice emptyApproxSet(@SqlType(StandardTypes.DOUBLE) double maxStandardError) <START> { <END> return HyperLogLog.newInstance(ApproximateCountDistinctAggregation.standardErrorToBuckets(maxStandardError)).serialize(); }</code><technical_language>overkill: empty HLL "unknown" bucket count. bucket count remains unknown merging unknown-bucket HLL coalesced other bucket count. complication, I strong opinion this</technical_language>

Target:
public static Slice emptyApproxSet(@SqlType(StandardTypes.DOUBLE) double maxStandardError) { return HyperLogLog.newInstance(standardErrorToBuckets(maxStandardError)).serialize(); }
Source:
<code>protected boolean isOkToCreateFile(File sourceFile) { String fname = sourceFile.getName(); if (fname.equals(TEMPLATE_ACTIVATOR_FILENAME)) return mustGenerateActivator; if (fname.equals(TEMPLATE_LIFECYCLE_FILENAME)) return getBooleanOption(KEY_CREATE_LIFE_CYCLE); if (fname.endsWith(E4_MODEL_FILE)) { boolean createSampleContent = getBooleanOption(KEY_CREATE_SAMPLE_CONTENT); <START> if (sourceFile.getAbsolutePath().contains(BIN_FOLDER)) { <END> return !createSampleContent; } return createSampleContent; } return super.isOkToCreateFile(sourceFile); }</code><technical_language>This is bad. If "bin" appears in path, matches, e.g. if of directories is called "ichbin"</technical_language>

Target:
protected boolean isOkToCreateFile(File sourceFile) { String fname = sourceFile.getName(); if (fname.equals(TEMPLATE_ACTIVATOR_FILENAME)) return mustGenerateActivator; if (fname.equals(TEMPLATE_LIFECYCLE_FILENAME)) return getBooleanOption(KEY_CREATE_LIFE_CYCLE); if (fname.endsWith(E4_MODEL_FILE)) { if (sourceFile.getAbsolutePath().endsWith(EMPTY_E4_MODEL_FILE)) return !getBooleanOption(KEY_CREATE_SAMPLE_CONTENT); return getBooleanOption(KEY_CREATE_SAMPLE_CONTENT); } return super.isOkToCreateFile(sourceFile); }
Source:
<code>public void flush() { network.setDataCenterId(getSelectedDc().getId()); network.setName(getName().getEntity()); network.setStp(getIsStpEnabled().getEntity()); network.setDescription(getDescription().getEntity()); network.setComment(getComment().getEntity()); network.setVmNetwork(getIsVmNetwork().getEntity()); String label = getNetworkLabel().getSelectedItem(); network.setLabel(label == null || !label.isEmpty() ? label : null); network.setMtu(0); <START> if (getMtu().getIsChangable() && isCustomMtu()) <END> { network.setMtu(Integer.parseInt(getMtu().getEntity().toString())); } network.setVlanId(null); if (getHasVLanTag().getEntity()) { network.setVlanId(Integer.parseInt(getVLanTag().getEntity().toString())); } for (VnicProfileModel profileModel : getProfiles().getItems()) { profileModel.flush(); } if (getQos().getIsChangable()) { NetworkQoS qos = getQos().getSelectedItem(); network.setQosId(qos == NetworkQoSModel.EMPTY_QOS ? null : qos.getId()); } }</code><technical_language>If mistaken, if getMtu().getIsChangable() necessarily isCustomMtu()?... I check is redundant</technical_language>

Target:
public void flush() { network.setDataCenterId(getSelectedDc().getId()); network.setName(getName().getEntity()); network.setStp(getIsStpEnabled().getEntity()); network.setDescription(getDescription().getEntity()); network.setComment(getComment().getEntity()); network.setVmNetwork(getIsVmNetwork().getEntity()); String label = getNetworkLabel().getSelectedItem(); network.setLabel(label == null || !label.isEmpty() ? label : null); network.setMtu(0); if (getMtu().getIsChangable()) { network.setMtu(Integer.parseInt(getMtu().getEntity().toString())); } network.setVlanId(null); if (getHasVLanTag().getEntity()) { network.setVlanId(Integer.parseInt(getVLanTag().getEntity().toString())); } for (VnicProfileModel profileModel : getProfiles().getItems()) { profileModel.flush(); } if (getQos().getIsChangable()) { NetworkQoS qos = getQos().getSelectedItem(); network.setQosId(qos == NetworkQoSModel.EMPTY_QOS ? null : qos.getId()); } }
Source:
<code>public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; LoggingEventKey that = (LoggingEventKey) o; return level == that.level && Objects.equals(message, that.message) && Arrays.equals(params, that.params) && <START> Objects.equals(marker, that.marker); <END> }</code><technical_language>this Arrays.equals. wdyt</technical_language>

Target:
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; LoggingEventKey that = (LoggingEventKey) o; return level == that.level && Objects.equals(message, that.message) && Objects.equals(marker, that.marker) && Arrays.equals(params, that.params); }
Source:
<code>public void testLogManager() throws Exception { <START> System.setProperty("test.log.file", "test-hc-jbl.log"); <END> if (isIbmJdk()) { try (InputStream in = getClass().getResourceAsStream("/jbl-logging.properties")) { Assert.assertNotNull("Failed to find the logging.properties file", in); LogManager.getLogManager().readConfiguration(in); } } System.setProperty("logging.configuration", getClass().getResource("/jbl-logging.properties").toExternalForm()); System.setProperty("java.util.logging.manager", "org.jboss.logmanager.LogManager"); testHostController(Configuration.LoggerHint.JBOSS_LOG_MANAGER, "test-standalone-jbl.log", "[jboss-logmanager]"); }</code><technical_language>changed this is test is failing. I L49 needs changed match</technical_language>

Target:
public void testLogManager() throws Exception { System.setProperty("test.log.file", "test-hc-jbl.log"); if (isIbmJdk()) { try (InputStream in = getClass().getResourceAsStream("/jbl-logging.properties")) { Assert.assertNotNull("Failed to find the logging.properties file", in); LogManager.getLogManager().readConfiguration(in); } } System.setProperty("logging.configuration", getClass().getResource("/jbl-logging.properties").toExternalForm()); System.setProperty("java.util.logging.manager", "org.jboss.logmanager.LogManager"); testHostController(Configuration.LoggerHint.JBOSS_LOG_MANAGER, "test-hc-jbl.log", "[jboss-logmanager]"); }
Source:
<code>public static List<String> extractBaseImages(File dockerFile, FixedStringSearchInterpolator interpolator) throws IOException { List<String[]> fromLines = extractLines(dockerFile, "FROM", interpolator); LinkedList<String> result = new LinkedList<>(); <START> Map<String, String> fromAlias = new HashMap<>(); <END> for (String[] fromLine : fromLines) { if (fromLine.length > 1) { if (fromLine.length == 2) { result.add(fromLine[1]); } else if (fromLine.length == 4) { if (!fromAlias.containsKey(fromLine[1])) { result.add(fromLine[1]); } fromAlias.put(fromLine[3], fromLine[1]); } } } return result; }</code><technical_language>logic below, this a set</technical_language>

Target:
public static List<String> extractBaseImages(File dockerFile, FixedStringSearchInterpolator interpolator) throws IOException { List<String[]> fromLines = extractLines(dockerFile, "FROM", interpolator); Set<String> result = new LinkedHashSet<>(); Set<String> fromAlias = new HashSet<>(); for (String[] fromLine : fromLines) { if (fromLine.length > 1) { if (fromLine.length == 2) { result.add(fromLine[1]); } else if (fromLine.length == 4) { if (!fromAlias.contains(fromLine[1])) { result.add(fromLine[1]); } fromAlias.add(fromLine[3]); } } } return result.stream().collect(Collectors.toList()); }
Source:
<code>public int hashCode() { <START> return element.hashCode(); <END> }</code><technical_language>missing is check if element is null. I probability is low, still..</technical_language>

Target:
public int hashCode() { if (element == null) { return super.hashCode(); } return element.hashCode(); }
Source:
<code>public void testRequirements() { IKernelTrace trace = fTrace; assertNotNull(trace); IKernelAnalysisEventLayout layout = trace.getKernelEventLayout(); Set<String> expected = ImmutableSet.of(layout.eventSchedSwitch()); Iterable<TmfAnalysisRequirement> requirements = fModule.getAnalysisRequirements(); Set<String> actual = new HashSet<>(); for (TmfAnalysisRequirement req : requirements) { actual.addAll(req.getValues()); <START> } <END> assertEquals(expected, actual); }</code><technical_language>If want some stream magic: Set<String> actual = StreamSupport.stream(fModule.getAnalysisRequirements().spliterator(), false) .flatMap(req -> req.getValues().stream()) .collect(Collectors.toSet()); avoids intermediate data structure</technical_language>

Target:
public void testRequirements() { IKernelTrace trace = fTrace; assertNotNull(trace); IKernelAnalysisEventLayout layout = trace.getKernelEventLayout(); Set<String> expected = ImmutableSet.of(layout.eventSchedSwitch()); Set<String> actual = StreamSupport.stream(fModule.getAnalysisRequirements().spliterator(), false) .flatMap(req -> req.getValues().stream()) .collect(Collectors.toSet()); assertEquals(expected, actual); }
Source:
<code>public void verifyPagination(){ waitForElementByElement(paginationContainer); <START> for (WebElement elem:paginationPages){ <END> } }</code><technical_language>?? is empty for loop github is showing full code</technical_language>

Target:
public void verifyPagination() { waitForElementByElement(paginationContainer); int i=1; for (WebElement elem:paginationPages) { Assertion.assertEquals(Integer.toString(i), elem.getText()); i++; } }
Source:
<code>private void handleMetadata(BufferedInputStream parser, ITmfTrace trace, String dir) throws IOException { List<String> processes = new ArrayList<>(); String processString = JsonTrace.readNextEventString(() -> (char) parser.read()); while (processString != null) { processes.add(processString); processString = JsonTrace.readNextEventString(() -> (char) parser.read()); if (processString == null) { break; } } if (!processes.isEmpty()) { <START> String filePath = trace.getPath().replaceAll(".json", "Processes.json"); <END> File processFile = new File(dir + File.separator + new File(filePath).getName()); processFile.createNewFile(); try (PrintWriter tempWriter = new PrintWriter(processFile)) { tempWriter.println('['); for (int j = 0; j < processes.size() - 1; j++) { tempWriter.println(processes.get(j) + ','); } tempWriter.println(processes.get(processes.size() - 1) + "\n]"); } } }</code><technical_language>this is opentracing specific.Thoughts</technical_language>

Target:
protected abstract void handleMetadata(BufferedInputStream parser, ITmfTrace trace, String dir) throws IOException; private static @Nullable Pair readNextEvent(BufferedInputStream parser, String key, int i) throws IOException { String event = JsonTrace.readNextEventString(() -> (char) parser.read()); return event == null ? null : new Pair(key, event, i); }
Source:
<code>public boolean isModified(DirCacheEntry entry, boolean forceContentCheck) { <START> return isModified(null, false, null); <END> }</code><technical_language>pass null instead of entry here</technical_language>

Target:
public boolean isModified(DirCacheEntry entry, boolean forceContentCheck) { return isModified(entry, false, null); }
Source:
<code>protected DocumentModel createPrincipal(Map<String, Serializable> attributes) { DocumentModel userModel = getUserManager().getBareUserModel(); userModel.getDataModel(getUserManager().getUserSchemaName()).setMap((Map) attributes); <START> return getUserManager().createUser(userModel); <END> }</code><technical_language>Factorize userManager a local variable</technical_language>

Target:
protected DocumentModel createPrincipal(Map<String, Serializable> attributes) { UserManager userManager = getUserManager(); DocumentModel userModel = userManager.getBareUserModel(); userModel.getDataModel(userManager.getUserSchemaName()).setMap((Map) attributes); return userManager.createUser(userModel); }
Source:
<code>protected Traverser.Admin<E> processNextStart() { while (true) { if (this.iterator.hasNext()) { return this.head.split(this.iterator.next(), this); } else { this.head = this.starts.next(); <START> closeIterator(); <END> this.iterator = this.flatMap(this.head); } } }</code><technical_language>This this.starts.next() if this.starts.next() is empty, throw FastNoSuchElementException previous iterator closed</technical_language>

Target:
protected Traverser.Admin<E> processNextStart() { while (true) { if (this.iterator.hasNext()) { return this.head.split(this.iterator.next(), this); } else { closeIterator(); this.head = this.starts.next(); this.iterator = this.flatMap(this.head); } } }
Source:
<code>protected void setNoCache(final HttpServletResponse response) { <START> response.setHeader("Cache-Control", "no-cache"); <END> }</code><technical_language>NB: no-cache is a in requests, responses. of effect in this case. safe side, update this read private, max-age=0 instead</technical_language>

Target:
protected void setNoCache(final HttpServletResponse response) { response.setHeader("Cache-Control", "max-age=0, must-revalidate, no-cache, no-store"); }
Source:
<code><START> public ArrayList<WebLocation> getBookmarks() <END> { return bookmarksData; }</code><technical_language>List interface</technical_language>

Target:
public List<Bookmark> getBookmarks() { return bookmarks; }
Source:
<code>private final void closeStatements() { final int size = openStatements.size(); if (size > 0) { for (int i = 0; i < size; i++) { try { final Statement statement = openStatements.get(i); if (statement != null) { statement.close(); } } catch (SQLException e) { checkException(e); if (delegate == ClosedConnection.CLOSED_CONNECTION) { <START> break; END> } } } openStatements.clear(); } }</code><technical_language>I this is more efficient, is optimizing a case rare I care performance. additional code adds cognitive load messy method</technical_language>

Target:
private final void closeStatements() { final int size = openStatements.size(); if (size > 0) { for (int i = 0; i < size && delegate != ClosedConnection.CLOSED_CONNECTION; i++) { try { final Statement statement = openStatements.get(i); if (statement != null) { statement.close(); } } catch (SQLException e) { checkException(e); } } openStatements.clear(); } }
Source:
<code>private Collection<ModuleDeploymentStatus> processResults(CuratorFramework client, ResultCollector collector) throws InterruptedException { Collection<ModuleDeploymentStatus> statuses = collector.getResults(); for (ModuleDeploymentStatus deploymentStatus : statuses) { if (deploymentStatus.getState() != ModuleDeploymentStatus.State.deployed) { <START> logger.trace("Unsuccessful deployment: {}", deploymentStatus); <END> String path = new ModuleDeploymentsPath() .setContainer(deploymentStatus.getContainer()) .setStreamName(deploymentStatus.getKey().getGroup()) .setModuleType(deploymentStatus.getKey().getType().toString()) .setModuleLabel(deploymentStatus.getKey().getLabel()).build(); try { client.delete().deletingChildrenIfNeeded().forPath(path); } catch (InterruptedException e) { throw e; } catch (KeeperException.NoNodeException e) { } catch (Exception e) { logger.warn("Error while cleaning up failed deployment " + path, e); } } } return statuses; }</code><technical_language>this debug() level instead of trace()</technical_language>

Target:
private Collection<ModuleDeploymentStatus> processResults(CuratorFramework client, ResultCollector collector) throws InterruptedException { Collection<ModuleDeploymentStatus> statuses = collector.getResults(); for (ModuleDeploymentStatus deploymentStatus : statuses) { if (deploymentStatus.getState() != ModuleDeploymentStatus.State.deployed) { String path = new ModuleDeploymentsPath() .setContainer(deploymentStatus.getContainer()) .setStreamName(deploymentStatus.getKey().getGroup()) .setModuleType(deploymentStatus.getKey().getType().toString()) .setModuleLabel(deploymentStatus.getKey().getLabel()).build(); logger.debug("Unsuccessful deployment: {}; removing path {}", deploymentStatus, path); try { client.delete().deletingChildrenIfNeeded().forPath(path); } catch (InterruptedException e) { throw e; } catch (KeeperException.NoNodeException e) { } catch (Exception e) { logger.warn("Error while cleaning up failed deployment " + path, e); } } } return statuses; }
Source:
<code>private void privateAssertLine(final String tag, final int status, final int missedBranches, final int coveredBranches) { final int nr = source.getLineNumber(tag); final ILine line = sourceCoverage.getLine(nr); final String lineMsg = String.format("line %s: %s", Integer.valueOf(nr), source.getLine(nr)); final int insnStatus = line.getInstructionCounter().getStatus(); <START> assertEquals("Status in " + lineMsg, STATUS_NAME[status], <END> STATUS_NAME[insnStatus]); assertEquals("Branches in " + lineMsg, CounterImpl.getInstance(missedBranches, coveredBranches), line.getBranchCounter()); }</code><technical_language>assertion message unambiguous I change "status" "instructions"</technical_language>

Target:
private void privateAssertLine(final String tag, final int status, final int missedBranches, final int coveredBranches) { final int nr = source.getLineNumber(tag); final ILine line = sourceCoverage.getLine(nr); final String lineMsg = String.format("line %s: %s", Integer.valueOf(nr), source.getLine(nr)); final int insnStatus = line.getInstructionCounter().getStatus(); assertEquals("Instructions in " + lineMsg, STATUS_NAME[status], STATUS_NAME[insnStatus]); assertEquals("Branches in " + lineMsg, CounterImpl.getInstance(missedBranches, coveredBranches), line.getBranchCounter()); }
Source:
<code>public void gotoClass(String packagePath, int line) { lastWentLine = line; final Project project = appContext.getRootProject(); <START> String testSrcPath = project.getPath() + "/src/test/java/"; <END> appContext.getWorkspaceRoot().getFile(testSrcPath + packagePath).then(new Operation<Optional<File>>() { @Override public void apply(Optional<File> file) throws OperationException { if (file.isPresent()) { eventBus.fireEvent(FileEvent.createOpenFileEvent(file.get())); Timer t = new Timer() { @Override public void run() { EditorPartPresenter editorPart = editorAgent.getActiveEditor(); Document doc = ((TextEditor) editorPart).getDocument(); doc.setCursorPosition(new TextPosition(lastWentLine - 1, 0)); } }; t.schedule(500); } } }).catchError(new Operation<PromiseError>() { @Override public void apply(PromiseError error) throws OperationException { Log.info(TestResultViewImpl.class, error); } }); }</code><technical_language>I good hardcode path tests classes. some attributes projecttype</technical_language>

Target:
public void gotoClass(String packagePath, int line) { lastWentLine = line; final Project project = appContext.getRootProject(); String testSrcPath = Paths.get(project.getPath(), MavenAttributes.DEFAULT_TEST_SOURCE_FOLDER).toString(); appContext.getWorkspaceRoot().getFile(testSrcPath + packagePath).then(new Operation<Optional<File>>() { @Override public void apply(Optional<File> file) throws OperationException { if (file.isPresent()) { eventBus.fireEvent(FileEvent.createOpenFileEvent(file.get())); Timer t = new Timer() { @Override public void run() { EditorPartPresenter editorPart = editorAgent.getActiveEditor(); Document doc = ((TextEditor) editorPart).getDocument(); doc.setCursorPosition(new TextPosition(lastWentLine - 1, 0)); } }; t.schedule(500); } } }).catchError(new Operation<PromiseError>() { @Override public void apply(PromiseError error) throws OperationException { Log.info(TestResultViewImpl.class, error); } }); }