auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public IterableStream<ServiceBusReceivedMessage> receive(int maxMessages) { <START> if (maxMessages <= 0) { <END> throw logger.logExceptionAsError(new IllegalArgumentException( "'maxMessages' cannot be less than or equal to 0. maxMessages: " + maxMessages)); } final Flux<ServiceBusReceivedMessage> messages = Flux.create(emitter -> queueWork(maxMessages, DEFAULT_RECEIVE_WAIT_TIME, emitter)); return new IterableStream<>(messages); }</code><technical_language>save duplicated logic, this method call maximal overload</technical_language>

Target:
public IterableStream<ServiceBusReceivedMessage> receive(int maxMessages) { return receive(maxMessages, operationTimeout); }
Source:
<code>public void testChecksumsForSourceFiles() { final ApiClient webClient = getWebClient(USER_2_USERNAME, testingPostgres); WorkflowsApi workflowsApi = new WorkflowsApi(webClient); Workflow workflow = workflowsApi.manualRegister("github", "DockstoreTestUser2/hello-dockstore-workflow", "/Dockstore.wdl", "", "wdl", "/test.json"); workflow = workflowsApi.refresh(workflow.getId()); List<WorkflowVersion> workflowVersions = workflow.getWorkflowVersions(); assertFalse(workflowVersions.isEmpty()); boolean testedWDL = false; for (WorkflowVersion workflowVersion : workflowVersions) { if (workflowVersion.getName().equals("testBoth") || workflowVersion.getName().equals("testWDL")) { testedWDL = true; <START> assertTrue(testedWDL); <END> assertNotNull(workflowVersion.getSourceFiles()); workflowVersion.getSourceFiles().stream().forEach(sourceFile -> assertNotNull("Should have checksums", sourceFile.getChecksums())); } workflowVersion.getSourceFiles(); } WorkflowVersion version = snapshotWorkflowVersion(workflowsApi, "dockstore-testing/hello_world", "/hello_world.cwl", "1.0.1"); assertNotNull(version.getSourceFiles()); version.getSourceFiles().stream().forEach(sourceFile -> assertNotNull("Should have checksums", sourceFile.getChecksums())); }</code><technical_language>testedWDL check is a bit strange, true checked if, for example workflow versions</technical_language>

Target:
public void testChecksumsForSourceFiles() { final ApiClient webClient = getWebClient(USER_2_USERNAME, testingPostgres); WorkflowsApi workflowsApi = new WorkflowsApi(webClient); Workflow workflow = workflowsApi.manualRegister("github", "DockstoreTestUser2/hello-dockstore-workflow", "/Dockstore.wdl", "", "wdl", "/test.json"); workflow = workflowsApi.refresh(workflow.getId()); List<WorkflowVersion> workflowVersions = workflow.getWorkflowVersions(); assertFalse(workflowVersions.isEmpty()); boolean testedWDL = false; for (WorkflowVersion workflowVersion : workflowVersions) { if (workflowVersion.getName().equals("testBoth") || workflowVersion.getName().equals("testWDL")) { testedWDL = true; assertNotNull(workflowVersion.getSourceFiles()); workflowVersion.getSourceFiles().stream().forEach(sourceFile -> assertFalse("Source file should have a checksum", sourceFile.getChecksums().get(0).toString().isEmpty())); } } assertTrue(testedWDL); Workflow workflow2 = manualRegisterAndPublish(workflowsApi, "dockstore-testing/hello_world", "", "cwl", SourceControl.GITHUB, "/hello_world.cwl", true); WorkflowVersion snapshotVersion = workflow2.getWorkflowVersions().stream().filter(v -> v.getName().equals("1.0.1")).findFirst().get(); assertNotNull(snapshotVersion.getSourceFiles()); snapshotVersion.setFrozen(true); workflowsApi.updateWorkflowVersion(workflow2.getId(), Collections.singletonList(snapshotVersion)); snapshotVersion.getSourceFiles().stream().forEach(sourceFile -> assertFalse("Source File should have a checksum", sourceFile.getChecksums().get(0).toString().isEmpty())); workflowsApi.refresh(workflow2.getId()); }
Source:
<code>public boolean onCreateOptionsMenu(Menu menu) { boolean ret = super.onCreateOptionsMenu(menu); ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true); <START> actionBar.setHomeAsUpIndicator(getResources().getDrawable(R.drawable.ic_done_white_24dp)); <END> actionBar.setTitle(R.string.title_activity_recaptcha); actionBar.setSubtitle(R.string.subtitle_activity_recaptcha); } return ret; }</code><technical_language>I able get a reCAPTCHA while visiting peertube.co.uk, I test PR. I reading code, is theme handling in toolbar. Please ensure correct button color light theme</technical_language>

Target:
public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_recaptcha, menu); ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(false); actionBar.setTitle(R.string.title_activity_recaptcha); actionBar.setSubtitle(R.string.subtitle_activity_recaptcha); } return true; }
Source:
<code>public void shouldParseFormsEventAttributesProperly() { String eventSubject = formsEvent.getSubject(); Map<String, Object> eventParameters = formsEvent.getParameters(); Map<String, Object> parsedParameters = formsEventParser.parseEventParameters(eventSubject, eventParameters); assertTrue(parsedParameters.containsKey("/data/case/@case_id")); assertTrue(parsedParameters.containsKey("/data/case/@user_id")); assertTrue(parsedParameters.containsKey("/data/case/@date_modified")); assertTrue(parsedParameters.containsKey("/data/case/@xmlns")); assertEquals(CASE_ID, parsedParameters.get("/data/case/@case_id")); assertEquals(USER_ID, parsedParameters.get("/data/case/@user_id")); assertEquals(DATE_MODIFIED, parsedParameters.get("/data/case/@date_modified")); <START> assertEquals(XMLNS, parsedParameters.get("/data/case/@xmlns")); <END> }</code><technical_language>modify sample XML, attributes varying levels of XML tree (and test here)</technical_language>

Target:
public void shouldParseFormsEventAttributesProperly() { String eventSubject = formsEvent.getSubject(); Map<String, Object> eventParameters = formsEvent.getParameters(); Map<String, Object> parsedParameters = formsEventParser.parseEventParameters(eventSubject, eventParameters); assertTrue(parsedParameters.containsKey("/data/case/@case_id")); assertTrue(parsedParameters.containsKey("/data/case/@user_id")); assertTrue(parsedParameters.containsKey("/data/case/@date_modified")); assertTrue(parsedParameters.containsKey("/data/case/@xmlns")); assertTrue(parsedParameters.containsKey("/data/case/update/@date")); assertTrue(parsedParameters.containsKey("/data/case/update/number/@attr")); assertEquals(CASE_ID, parsedParameters.get("/data/case/@case_id")); assertEquals(USER_ID, parsedParameters.get("/data/case/@user_id")); assertEquals(DATE_MODIFIED, parsedParameters.get("/data/case/@date_modified")); assertEquals(XMLNS, parsedParameters.get("/data/case/@xmlns")); assertEquals(DATE, parsedParameters.get("/data/case/update/@date")); assertEquals(ATTR, parsedParameters.get("/data/case/update/number/@attr")); }
Source:
<code>private void discardReadBytesIfNecessary(ByteBuf buffer) { int bufferUsageRatio = clientOptions.getBufferUsageRatio(); <START> if (buffer.writerIndex() * (bufferUsageRatio + 1) >= buffer.capacity() * bufferUsageRatio) { <END> if (buffer.refCnt() != 0) { buffer.discardReadBytes(); } } }</code><technical_language>This calculation is prone for integer overflow. I sense discard more customizable. do providing a BiConsumer<ByteBuf, DecodeProgress> handles discard? consumer accept buffer enum (whether discard happened decoding a command/after decoding a command/after decoding a batch) implementation decide time of release. cleaner consumer returned ClientOptions</technical_language>

Target:
private void discardReadBytesIfNecessary(ByteBuf buffer) { int bufferUsageRatio = clientOptions.getBufferUsageRatio(); if ((float)buffer.writerIndex() / buffer.capacity() >= (float)bufferUsageRatio / (bufferUsageRatio + 1)) { if (buffer.refCnt() != 0) { buffer.discardReadBytes(); } } }
Source:
<code>public static void createTestBucketOrDirectory(final MantaClient client, final String testPath, final String testType) throws IOException { if ("buckets".equals(testType)) { final String bucketPath = parseBucketPath(testPath); try { client.createBucket(bucketPath); } catch (MantaClientHttpResponseException e) { if (e.getServerCode().equals(MantaErrorCode.BUCKET_EXISTS_ERROR)) { LOG.error("Test Bucket named already exists leading to {}" , integrationTestBucket, e.getStatusMessage()); e.setContextValue("Creating test bucket failed at :", testPath); throw e; <START> } <END> } } else { client.putDirectory(testPath, true); } }</code><technical_language>is exception swallowed thrown? If is problem creating a bucket, exception for problem is lost this point</technical_language>

Target:
public static void createTestBucketOrDirectory(final MantaClient client, final String testPath, final String testType) throws IOException { if ("buckets".equals(testType)) { final String bucket_path = parseBucketPath(testPath); try { client.createBucket(bucket_path); } catch (MantaClientHttpResponseException e) { if (!e.getServerCode().equals(MantaErrorCode.BUCKET_EXISTS_ERROR)) { e.setContextValue("Creating test bucket failed at :", testPath); throw e; } } catch (IOException e) { throw new MantaIOException("Unable to create test bucket", e); } } else { client.putDirectory(testPath, true); } }
Source:
<code>private void undistributeParcels(ApiClient apiClient, ParcelResourceApi parcelResourceApi, Stack stack, Map<String, String> parcels) { Set<String> failedDistribution = new HashSet<>(); for (Map.Entry<String, String> distributedComponent : parcels.entrySet()) { try { parcelResourceApi.startRemovalOfDistributionCommand(stack.getName(), distributedComponent.getKey(), distributedComponent.getValue()); } catch (ApiException e) { String product = "[" + distributedComponent.getKey() + ":" + distributedComponent.getValue() + "]"; LOGGER.info(String.format("Unable to undistribute product: %s", product), e); failedDistribution.add(product); } } if (!failedDistribution.isEmpty()) { <START> throw new ClouderaManagerOperationFailedException(String.format("Undistribution failed on the following products: %s", failedDistribution)); <END> } PollingResult pollingResult = clouderaManagerPollingServiceProvider.startPollingCmParcelStatus(stack, apiClient, parcels, ParcelStatus.DOWNLOADED); if (isExited(pollingResult)) { throw new CancellationException("Cluster was terminated while waiting for parcels undistribution"); } else if (isTimeout(pollingResult)) { throw new ClouderaManagerOperationFailedException("Timeout while Cloudera Manager undistribute parcels."); } }</code><technical_language>log nice</technical_language>

Target:
private void undistributeParcels(ApiClient apiClient, ParcelResourceApi parcelResourceApi, Stack stack, Map<String, String> parcels) { Set<String> failedDistribution = new HashSet<>(); for (Map.Entry<String, String> distributedComponent : parcels.entrySet()) { String product = "[" + distributedComponent.getKey() + ":" + distributedComponent.getValue() + "]"; try { LOGGER.debug("Undistributing product", product); parcelResourceApi.startRemovalOfDistributionCommand(stack.getName(), distributedComponent.getKey(), distributedComponent.getValue()); } catch (ApiException e) { LOGGER.info(String.format("Unable to undistribute product: %s", product), e); failedDistribution.add(product); } } if (!failedDistribution.isEmpty()) { throw new ClouderaManagerOperationFailedException(String.format("Undistribution failed on the following products: %s", failedDistribution)); } PollingResult pollingResult = clouderaManagerPollingServiceProvider.startPollingCmParcelStatus(stack, apiClient, parcels, ParcelStatus.DOWNLOADED); if (isExited(pollingResult)) { throw new CancellationException("Cluster was terminated while waiting for parcels undistribution"); } else if (isTimeout(pollingResult)) { throw new ClouderaManagerOperationFailedException("Timeout while Cloudera Manager undistribute parcels."); } }
Source:
<code>public PsychicPurge(UUID ownerId, CardSetInfo setInfo) { <START> super(ownerId, setInfo, new CardType[]{CardType.INSTANT}, "{U}"); <END> this.getSpellAbility().addEffect(new DamageTargetEffect(1)); this.getSpellAbility().addTarget(new TargetCreatureOrPlayer()); Ability ability = new PsychicPurgeTriggeredAbility(); this.addAbility(ability); }</code><technical_language>This needs a sorcery</technical_language>

Target:
public PsychicPurge(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.SORCERY}, "{U}"); this.getSpellAbility().addEffect(new DamageTargetEffect(1)); this.getSpellAbility().addTarget(new TargetCreatureOrPlayer()); Ability ability = new PsychicPurgeTriggeredAbility(); this.addAbility(ability); }
Source:
<code>public final Void execute(RepositoryContext context) { <START> CodeSystem primaryCodeSystem = createPrimaryCodeSystem(); <END> if (primaryCodeSystem != null) { CodeSystems codeSystems = CodeSystemRequests.prepareSearchCodeSystem() .filterById(primaryCodeSystem.getShortName()) .setLimit(0) .build() .execute(context); if (codeSystems.getTotal() < 1) { CodeSystemRequests.prepareNewCodeSystem() .setName(primaryCodeSystem.getName()) .setOid(primaryCodeSystem.getOid()) .setLanguage(primaryCodeSystem.getPrimaryLanguage()) .setLink(primaryCodeSystem.getOrganizationLink()) .setCitation(primaryCodeSystem.getCitation()) .setIconPath(primaryCodeSystem.getIconPath()) .setTerminologyId(primaryCodeSystem.getTerminologyId()) .setShortName(primaryCodeSystem.getShortName()) .setRepositoryUuid(context.id()) .setBranchPath(Branch.MAIN_PATH) .build(context.id(), Branch.MAIN_PATH, User.SYSTEM.getUsername(), "Create primary code system for repository") .getRequest() .execute(context); } } return null; }</code><technical_language>a sidenote: thinking removing repository initializer functionality completely support full customization of default Code Systems in a tooling (for example create SNOMEDCT-UK-EDITION instead of SNOMEDCT MAIN branch)</technical_language>

Target:
public final Void execute(RepositoryContext context) { CodeSystem primaryCodeSystem = createPrimaryCodeSystem(); if (primaryCodeSystem != null) { CodeSystems codeSystems = CodeSystemRequests.prepareSearchCodeSystem() .filterById(primaryCodeSystem.getShortName()) .setLimit(0) .build() .execute(context); if (codeSystems.getTotal() < 1) { CodeSystemRequests.prepareNewCodeSystem() .setName(primaryCodeSystem.getName()) .setOid(primaryCodeSystem.getOid()) .setLanguage(primaryCodeSystem.getPrimaryLanguage()) .setLink(primaryCodeSystem.getOrganizationLink()) .setCitation(primaryCodeSystem.getCitation()) .setIconPath(primaryCodeSystem.getIconPath()) .setTerminologyId(primaryCodeSystem.getTerminologyId()) .setShortName(primaryCodeSystem.getShortName()) .setRepositoryId(context.id()) .setBranchPath(Branch.MAIN_PATH) .build(context.id(), Branch.MAIN_PATH, User.SYSTEM.getUsername(), "Create primary code system for repository") .getRequest() .execute(context); } } return null; }
Source:
<code><START> public void testMultipleLinksToFolder() throws Exception { <END> if (!canCreateSymLinks()) return; IFileStore tempStore = getTempStore(); createFileInFileSystem(tempStore.getChild("foo.txt")); IPath tempFolderPath = URIUtil.toPath(tempStore.toURI()); IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); IProject projectA = root.getProject(getUniqueString()); IProject projectB = root.getProject(getUniqueString()); try { create(projectA, true); create(projectB, true); } catch (CoreException e) { fail("1.0", e); } symLinkAndRefresh(projectA, "folderA", tempFolderPath); symLinkAndRefresh(projectB, "folderB", tempFolderPath); }</code><technical_language>throws clause is needed here</technical_language>

Target:
public void testMultipleLinksToFolder() { if (!canCreateSymLinks()) return; IFileStore tempStore = getTempStore(); createFileInFileSystem(tempStore.getChild("foo.txt")); IPath tempFolderPath = URIUtil.toPath(tempStore.toURI()); IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); IProject projectA = root.getProject(getUniqueString()); IProject projectB = root.getProject(getUniqueString()); try { create(projectA, true); create(projectB, true); } catch (CoreException e) { fail("1.0", e); } symLinkAndRefresh(projectA, "folderA", tempFolderPath); symLinkAndRefresh(projectB, "folderB", tempFolderPath); }
Source:
<code>public void finishJob() { log.info("Shutting down..."); shuttingDown = true; for (final Map.Entry<Long, Sink> entry : sinks.entrySet()) { persistAndMerge(entry.getKey(), entry.getValue()); } while (!sinks.isEmpty()) { try { log.info( "Cannot shut down yet! Sinks remaining: %s", Joiner.on(", ").join( Iterables.transform( sinks.values(), new Function<Sink, String>() { @Override public String apply(Sink input) { return input.getSegment().getIdentifier(); } } ) ) ); synchronized (handoffCondition) { while (!sinks.isEmpty()) { handoffCondition.wait(config.getHandoffConditionTimeout()); } } } catch (InterruptedException e) { <START> throw new ISE("Failed to wait for segment handoff.", e); <END> } } handoffNotifier.stop(); shutdownExecutors(); stopped = true; if (!cleanShutdown) { throw new ISE("Exception occurred during persist and merge."); } }</code><technical_language>Wait timeout throw InterruptedException</technical_language>

Target:
public void finishJob() { log.info("Shutting down..."); shuttingDown = true; for (final Map.Entry<Long, Sink> entry : sinks.entrySet()) { persistAndMerge(entry.getKey(), entry.getValue()); } final long forceEndWaitTime = System.currentTimeMillis() + config.getHandoffConditionTimeout(); while (!sinks.isEmpty()) { try { log.info( "Cannot shut down yet! Sinks remaining: %s", Joiner.on(", ").join( Iterables.transform( sinks.values(), new Function<Sink, String>() { @Override public String apply(Sink input) { return input.getSegment().getIdentifier(); } } ) ) ); synchronized (handoffCondition) { while (!sinks.isEmpty()) { if (config.getHandoffConditionTimeout() == 0) { handoffCondition.wait(); } else { long curr = System.currentTimeMillis(); if (forceEndWaitTime - curr > 0) { handoffCondition.wait(forceEndWaitTime - curr); } else { throw new ISE( "Segment handoff wait timeout. [%s] segments might not have completed handoff.", sinks.size() ); } } } } } catch (InterruptedException e) { throw Throwables.propagate(e); } } handoffNotifier.stop(); shutdownExecutors(); stopped = true; if (!cleanShutdown) { throw new ISE("Exception occurred during persist and merge."); } }
Source:
<code>private void advanceLocation() { ParticleEffect.FIREWORKS_SPARK.display(this.location, 2, .001, .001, .001, 0); <START> ParticleEffect.CRIT.display(this.location, 3, Math.random() * 2, Math.random() * 2, Math.random() * 2, 0); <END> playCombustionSound(this.location); this.location = this.location.add(this.direction.clone().multiply(this.speedFactor)); }</code><technical_language>reason for this change? imo fire particles fine if blue fire</technical_language>

Target:
private void advanceLocation() { ParticleEffect.FIREWORKS_SPARK.display(this.location, 2, .001, .001, .001, 0); if(explosionCount % 5 == 0) ParticleEffect.EXPLOSION_LARGE.display(this.location, 1, .001, .001, .001, 0); playCombustionSound(this.location); this.location = this.location.add(this.direction.clone().multiply(this.speedFactor)); this.explosionCount++; }
Source:
<code>public void reuseSession() { if (getSessionId() != null) { RestApiSessionAcquiredEvent.fire(eventBus, getSessionId()); <START> scheduleKeepAliveHeartbeat(); <END> } else { getSessionId(new StorageCallback() { @Override public void onSuccess(String result) { if (result != null) { restApiSessionId = result; RestApiSessionAcquiredEvent.fire(eventBus, result); scheduleKeepAliveHeartbeat(); } else { RestApiSessionManager.logger.severe("Engine REST API session ID is not available"); } } @Override public void onFailure(Throwable caught) { RestApiSessionManager.logger.severe("Engine REST API session ID is not available"); } }); } }</code><technical_language>Hm, avoid duplicating code, I suggest create small methods: void processSessionId(String sessionId) { assert sessionId != null : "Session ID null"; RestApiSessionAcquiredEvent.fire(eventBus, sessionId); scheduleKeepAliveHeartbeat(); } void processSessionIdError(Throwable t) { RestApiSessionManager.logger.log(Level.SEVERE, "Session ID is available, this break UI plugins", t); }</technical_language>

Target:
public void reuseSession() { if (getSessionId() != null) { processSessionId(getSessionId()); } else { getSessionId(new StorageCallback() { @Override public void onSuccess(String result) { if (result != null) { restApiSessionId = result; processSessionId(result); } else { processSessionIdException(); } } @Override public void onFailure(Throwable caught) { processSessionIdException(); } private void processSessionIdException() { RestApiSessionManager.logger.severe("Engine REST API session ID is not available"); } }); } }
Source:
<code>private <T> T proxy(Class<T> clazz) { final T result0 = ProxyFactory.create(clazz, target, clientExecutor); return (T) Proxy.newProxyInstance(clazz.getClassLoader(), new Class<?>[] { clazz }, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { try { Object result1 = method.invoke(result0, args); Class<?> type = String.class; if (result1 instanceof Response) { <START> if(((Response)result1).getStatus()/100 == 2) { <END> String responseClass = method.getAnnotation(ApiOperation.class).responseClass(); type = Class.forName(responseClass); } result1 = BuiltResponsePreservingError.copyResponseAndClose((Response) result1, type); } return result1; } catch (Throwable e) { if (e instanceof InvocationTargetException) { e = ((InvocationTargetException)e).getTargetException(); } throw Exceptions.propagate(e); } } }); }</code><technical_language>HttpTool.isStatusCodeHealthy</technical_language>

Target:
private <T> T proxy(Class<T> clazz) { final T result0 = ProxyFactory.create(clazz, target, clientExecutor); return (T) Proxy.newProxyInstance(clazz.getClassLoader(), new Class<?>[] { clazz }, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { try { Object result1 = method.invoke(result0, args); Class<?> type = String.class; if (result1 instanceof Response) { Response resp = (Response)result1; if(isStatusCodeHealthy(resp.getStatus()) && method.isAnnotationPresent(ApiOperation.class)) { type = getClassFromMethodAnnotationOrDefault(method, type); } result1 = BuiltResponsePreservingError.copyResponseAndClose(resp, type); } return result1; } catch (Throwable e) { if (e instanceof InvocationTargetException) { e = ((InvocationTargetException)e).getTargetException(); } throw Exceptions.propagate(e); } } private boolean isStatusCodeHealthy(int code) { return (code>=200 && code<=299); } private Class<?> getClassFromMethodAnnotationOrDefault(Method method, Class<?> def){ Class<?> type; try{ String responseClass = method.getAnnotation(ApiOperation.class).responseClass(); type = Class.forName(responseClass); } catch (Exception e) { type = def; LOG.debug("Unable to get class from annotation: {}. Defaulting to {}", e.getMessage(), def.getName()); Exceptions.propagateIfFatal(e); } return type; } }); }
Source:
<code>public boolean validate(AttributedDocumentEvent event) { KualiDecimal sourceTotalAmount = accountingDocumentForValidation.getSourceTotal(); KualiDecimal targetTotalAmount = accountingDocumentForValidation.getTargetTotal(); boolean ret = true; <START> if(sourceTotalAmount == null || !sourceTotalAmount.isNonZero()){ <END> GlobalVariables.getMessageMap().putError(KFSConstants.AMOUNT_PROPERTY_NAME, CUKFSKeyConstants.ERROR_ZERO_AMOUNT_TOTAL, "From", sourceTotalAmount.toString()); ret = false; } if(targetTotalAmount == null || !targetTotalAmount.isNonZero()){ GlobalVariables.getMessageMap().putError(KFSConstants.AMOUNT_PROPERTY_NAME, CUKFSKeyConstants.ERROR_ZERO_AMOUNT_TOTAL, "To", targetTotalAmount.toString()); ret = false; } return ret; }</code><technical_language>Please ObjectUtils check for nulls</technical_language>

Target:
public boolean validate(AttributedDocumentEvent event) { KualiDecimal sourceTotalAmount = accountingDocumentForValidation.getSourceTotal(); KualiDecimal targetTotalAmount = accountingDocumentForValidation.getTargetTotal(); boolean ret = true; if (ObjectUtils.isNull(sourceTotalAmount) || sourceTotalAmount.isZero()) { addGlobalThresholdValidationError("From", sourceTotalAmount); ret = false; } if(ObjectUtils.isNull(targetTotalAmount) || targetTotalAmount.isZero()){ addGlobalThresholdValidationError("To", targetTotalAmount); ret = false; } return ret; }
Source:
<code>public synchronized void takeSnapshot(List<LookupBean> lookups) { try { String lookupsSnapshot = objectMapper.writeValueAsString(lookups); <START> Files.write((StringUtils.toUtf8(lookupsSnapshot)), persistFile); <END> } catch (IOException e) { LOGGER.error(e, "Exception during serialization of lookups"); Throwables.propagate(e); } }</code><technical_language>ObjectMapper read write a File this in a streaming manner, I recommend instead of materializing a String. a big deal, though</technical_language>

Target:
public synchronized void takeSnapshot(List<LookupBean> lookups) { try { objectMapper.writeValue(persistFile, lookups); } catch (IOException e) { throw new ISE(e, "Exception during serialization of lookups using file [%s]", persistFile.getAbsolutePath()); } }
Source:
<code>@Test public void deleteBuildsManyShouldSuccessEvenTheFirstAndLastBuildDoesNotExist() throws Exception { FreeStyleProject project = j.createFreeStyleProject("aProject"); <START> project.scheduleBuild2(0).get(); <END> project.scheduleBuild2(0).get(); project.scheduleBuild2(0).get(); project.scheduleBuild2(0).get(); project.scheduleBuild2(0).get(); project.getBuildByNumber(1).delete(); project.getBuildByNumber(3).delete(); project.getBuildByNumber(5).delete(); assertThat(((FreeStyleProject) j.jenkins.getItem("aProject")).getBuilds().size(), equalTo(2)); CLICommandInvoker.Result result = command .authorizedTo(Jenkins.READ, Job.READ, Run.DELETE) .invokeWithArgs("aProject", "1,2,3"); assertThat(result, succeeded()); assertThat(result.stdout(), containsString("Deleted 1 builds")); assertThat(((FreeStyleProject) j.jenkins.getItem("aProject")).getBuilds().size(), equalTo(1)); result = command .authorizedTo(Jenkins.READ, Job.READ, Run.DELETE) .invokeWithArgs("aProject", "3-5"); assertThat(result, succeeded()); assertThat(result.stdout(), containsString("Deleted 1 builds")); assertThat(((FreeStyleProject) j.jenkins.getItem("aProject")).getBuilds().size(), equalTo(0)); }</code><technical_language>j.buildAndAssertSuccess hide some implementation details. important</technical_language>

Target:
@Test public void deleteBuildsManyShouldSuccessEvenTheFirstAndLastBuildDoesNotExist() throws Exception { FreeStyleProject project = j.createFreeStyleProject("aProject"); j.buildAndAssertSuccess(project); j.buildAndAssertSuccess(project); j.buildAndAssertSuccess(project); j.buildAndAssertSuccess(project); j.buildAndAssertSuccess(project); project.getBuildByNumber(1).delete(); project.getBuildByNumber(3).delete(); project.getBuildByNumber(5).delete(); assertThat(((FreeStyleProject) j.jenkins.getItem("aProject")).getBuilds(), hasSize(2)); CLICommandInvoker.Result result = command .authorizedTo(Jenkins.READ, Job.READ, Run.DELETE) .invokeWithArgs("aProject", "1,2,3"); assertThat(result, succeeded()); assertThat(result.stdout(), containsString("Deleted 1 builds")); assertThat(((FreeStyleProject) j.jenkins.getItem("aProject")).getBuilds(), hasSize(1)); result = command .authorizedTo(Jenkins.READ, Job.READ, Run.DELETE) .invokeWithArgs("aProject", "3-5"); assertThat(result, succeeded()); assertThat(result.stdout(), containsString("Deleted 1 builds")); assertThat(((FreeStyleProject) j.jenkins.getItem("aProject")).getBuilds(), hasSize(0)); }
Source:
<code>public final ChannelHandlerContext context(String name) { if (name == null) { throw new NullPointerException("name"); } synchronized (handlers) { int idx = findCtxIdx((ctx) -> ctx.name().equals(name)); if (idx == -1) { return null; } <START> return handlers.get(idx); <END> } }</code><technical_language>simplify return idx == -1 ? null : handlers.get(idx)? (same for other similar places)</technical_language>

Target:
public final ChannelHandlerContext context(String name) { if (name == null) { throw new NullPointerException("name"); } synchronized (handlers) { return findCtx(ctx -> ctx.name().equals(name)); } }
Source:
<code>public void testGetPreferredNameEmpty() { DoorsTableRowCollector dtc = new DoorsTableRowCollector(extractor); DoorsTableRow dtr = new DoorsTableRow(); dtc.getPreferredName(dtr); <START> Assert.fail(); <END> }</code><technical_language>fail is unecesary if exception happen test fail</technical_language>

Target:
public void testGetPreferredNameEmpty() { DoorsTableRowCollector dtc = new DoorsTableRowCollector(extractor); DoorsTableRow dtr = new DoorsTableRow(); dtc.getPreferredName(dtr); }
Source:
<code>private void renderHeader(String header) throws IOException { int lf = header.indexOf('\n'); String first; String rest; if (0 <= lf) { first = header.substring(0, lf); rest = header.substring(lf + 1); } else { first = header; rest = ""; } List<Map<String, String>> parts = Lists.newArrayListWithCapacity(4); <START> for (String part : SPACE.split(first)) { <END> if (part.startsWith("a/")) { parts.add(ImmutableMap.of( "text", part, "url", revisionUrl(view.getOldRevision(), part.substring(2)))); } else if (part.startsWith("b/")) { parts.add(ImmutableMap.of( "text", part, "url", revisionUrl(view.getRevision(), part.substring(2)))); } else { parts.add(ImmutableMap.of("text", part)); } } getOutputStream().write(renderer.newRenderer("gitiles.diffHeader") .setData(ImmutableMap.of("firstParts", parts, "rest", rest, "fileIndex", fileIndex)) .render() .getBytes(Charsets.UTF_8)); }</code><technical_language>if a path contains a space? Is some convince jgit provide a patch in some structured form reparsed here? Git's t/t4135-apply-weird-filenames.sh some example patches involving filenames special characters</technical_language>

Target:
private void renderHeader(String header) throws IOException { int lf = header.indexOf('\n'); String rest = 0 <= lf ? header.substring(lf + 1) : ""; List<Map<String, String>> parts = Lists.newArrayListWithCapacity(3); parts.add(ImmutableMap.of("text", "diff --git")); if (entry.getChangeType() != ChangeType.ADD) { parts.add(ImmutableMap.of( "text", GIT_PATH.quote(getOldPrefix() + entry.getOldPath()), "url", revisionUrl(view.getOldRevision(), entry.getOldPath()))); } else { parts.add(ImmutableMap.of( "text", GIT_PATH.quote(getOldPrefix() + entry.getNewPath()))); } if (entry.getChangeType() != ChangeType.DELETE) { parts.add(ImmutableMap.of( "text", GIT_PATH.quote(getNewPrefix() + entry.getNewPath()), "url", revisionUrl(view.getRevision(), entry.getNewPath()))); } else { parts.add(ImmutableMap.of( "text", GIT_PATH.quote(getNewPrefix() + entry.getOldPath()))); } getOutputStream().write(renderer.newRenderer("gitiles.diffHeader") .setData(ImmutableMap.of("firstParts", parts, "rest", rest, "fileIndex", fileIndex)) .render() .getBytes(Charsets.UTF_8)); }
Source:
<code>private Object loadFile(String fileName) { byte[] fileByteContent = safelyLoadFileBytes(fileName); <START> Object parsedObject; <END> parsedObject = getBatchInputFileService().parse(getBatchInputFileType(), fileByteContent); return parsedObject; }</code><technical_language>lines combined in one. need for a declaration a separate line</technical_language>

Target:
private Object loadFile(String fileName) { byte[] fileByteContent = safelyLoadFileBytes(fileName); Object parsedObject = getBatchInputFileService().parse(getBatchInputFileType(), fileByteContent); return parsedObject; }
Source:
<code>public void testGetInstanceObservationUnitRowsMap() { Map<Integer, List<ObservationUnitRow>> instanceObsUnitRowMap = this.datasetService.getInstanceIdToObservationUnitRowsMap(this.studyId, this.subObsDatasetId, this.instanceIds); List<ObservationUnitRow> observationUnitRows = instanceObsUnitRowMap.get(instanceIds.get(0)); Assert.assertNotNull(observationUnitRows); Assert.assertEquals(40, observationUnitRows.size()); final ObservationUnitRow observationUnitRow = observationUnitRows.get(0); this.verifyObservationUnitRowValues(observationUnitRow); Assert.assertNotNull(observationUnitRow.getVariables().get("STUDY_INSTITUTE")); Assert.assertNotNull(observationUnitRow.getVariables().get("STUDY_BM_CODE")); <START> Assert.assertNotNull(observationUnitRow.getVariables().get("SITE_ALT")); <END> }</code><technical_language>verify other special factors: Site Lat, Site Lon Site Datum</technical_language>

Target:
public void testGetInstanceObservationUnitRowsMap() { Map<Integer, List<ObservationUnitRow>> instanceObsUnitRowMap = this.datasetService.getInstanceIdToObservationUnitRowsMap(this.studyId, this.subObsDatasetId, this.instanceIds); List<ObservationUnitRow> observationUnitRows = instanceObsUnitRowMap.get(instanceIds.get(0)); Assert.assertNotNull(observationUnitRows); Assert.assertEquals(40, observationUnitRows.size()); final ObservationUnitRow observationUnitRow = observationUnitRows.get(0); this.verifyObservationUnitRowValues(observationUnitRow); Assert.assertNotNull(observationUnitRow.getVariables().get("STUDY_INSTITUTE")); Assert.assertNotNull(observationUnitRow.getVariables().get("STUDY_BM_CODE")); Assert.assertNotNull(observationUnitRow.getVariables().get("SITE_ALT")); Assert.assertNotNull(observationUnitRow.getVariables().get("SITE_LAT")); Assert.assertNotNull(observationUnitRow.getVariables().get("SITE_LONG")); Assert.assertNotNull(observationUnitRow.getVariables().get("SITE_DATUM")); }
Source:
<code>public static TurboLabel getFirstMatchingTurboLabel(List<TurboLabel> labels, String labelName) { Optional<TurboLabel> firstMatchingLabel = getMatchedLabels(labels, labelName).stream().findFirst(); <START> assert firstMatchingLabel.isPresent(); <END> return firstMatchingLabel.get(); }</code><technical_language>@dariusf assertions enabled in released version</technical_language>

Target:
public static final TurboLabel getFirstMatchingTurboLabel(List<TurboLabel> labels, String labelName) { Optional<TurboLabel> firstMatchingLabel = getMatchedLabels(labels, labelName).stream().findFirst(); assert firstMatchingLabel.isPresent(); return firstMatchingLabel.get(); }
Source:
<code>private Collection<ClusterTemplate> createAll(Iterable<ClusterTemplate> clusterTemplates) { User user = userService.getOrCreate(legacyRestRequestThreadLocalService.getCloudbreakUser()); <START> return StreamSupport.stream(clusterTemplates.spliterator(), true) <END> .map(ct -> { try { return measure(() -> create(ct, ct.getWorkspace(), user), LOGGER, "Cluster template created in {}ms"); } catch (DuplicateClusterTemplateException duplicateClusterTemplateException) { LOGGER.info("Template was found, try to get it", duplicateClusterTemplateException); return getByNameForWorkspace(ct.getName(), ct.getWorkspace()); } catch (BadRequestException badRequestException) { LOGGER.info("Template save failed, but try to get it", badRequestException); try { return getByNameForWorkspace(ct.getName(), ct.getWorkspace()); } catch (NotFoundException notFoundException) { LOGGER.info("Template was not found", notFoundException); throw notFoundException; } } }) .collect(Collectors.toList()); }</code><technical_language>set false was? I is a good idea parallal streams in a multithreaded web based application high load for request application able serve request time</technical_language>

Target:
private Collection<ClusterTemplate> createAll(Iterable<ClusterTemplate> clusterTemplates) { User user = userService.getOrCreate(legacyRestRequestThreadLocalService.getCloudbreakUser()); return StreamSupport.stream(clusterTemplates.spliterator(), false) .map(ct -> { try { return measure(() -> create(ct, ct.getWorkspace(), user), LOGGER, "Cluster template created in {}ms"); } catch (DuplicateClusterTemplateException duplicateClusterTemplateException) { LOGGER.info("Template was found, try to get it", duplicateClusterTemplateException); return getByNameForWorkspace(ct.getName(), ct.getWorkspace()); } catch (BadRequestException badRequestException) { LOGGER.info("Template save failed, but try to get it", badRequestException); try { return getByNameForWorkspace(ct.getName(), ct.getWorkspace()); } catch (NotFoundException notFoundException) { LOGGER.info("Template was not found", notFoundException); throw notFoundException; } } }) .collect(Collectors.toList()); }
Source:
<code>private static PlanNode planTableScan( TableScanNode node, Expression predicate, Session session, TypeProvider types, PlanNodeIdAllocator idAllocator, Metadata metadata, SqlParser parser, DomainTranslator domainTranslator) { <START> return AddExchanges.pickTableLayout( <END> node, predicate, false, session, types, idAllocator, metadata, parser, domainTranslator) .get(0); }</code><technical_language>I do idea PickTableLayout is AddExchanges directly. I provide some more generic 3rd component</technical_language>

Target:
private static PlanNode planTableScan( TableScanNode node, Expression predicate, Session session, TypeProvider types, PlanNodeIdAllocator idAllocator, Metadata metadata, SqlParser parser, DomainTranslator domainTranslator) { return listTableLayouts( node, predicate, false, session, types, idAllocator, metadata, parser, domainTranslator) .get(0); }
Source:
<code>public void testJdbcDrivers() throws Exception { String driverName = DEPLOYMENT + ".jar"; ModelNode address = new ModelNode().add(SUBSYSTEM, "datasources"); ModelNode operation = new ModelNode(); operation.get(OP).set("get-installed-driver"); operation.get(OP_ADDR).set(address); operation.get("driver-name").set(driverName); ModelNode result = executeOperation(operation).asList().get(0); <START> System.out.println("\n\n\n Result is: " + result + "\n\n\n"); <END> Assert.assertEquals(driverName, result.get("driver-name").asString()); Assert.assertEquals(driverName, result.get("deployment-name").asString()); Assert.assertEquals(TestDriver.class.getName(), result.get("driver-class-name").asString()); Assert.assertEquals(1, result.get("driver-major-version").asInt()); Assert.assertEquals(0, result.get("driver-minor-version").asInt()); Assert.assertFalse(result.get("jdbc-compliant").asBoolean()); String driver2 = driverName + "_" + TestDriver2.class.getName() + "_1_1"; operation.get("driver-name").set(driver2); result = executeOperation(operation).asList().get(0); Assert.assertEquals(driver2, result.get("driver-name").asString()); Assert.assertEquals(driver2, result.get("deployment-name").asString()); Assert.assertEquals(TestDriver2.class.getName(), result.get("driver-class-name").asString()); Assert.assertEquals(1, result.get("driver-major-version").asInt()); Assert.assertEquals(1, result.get("driver-minor-version").asInt()); Assert.assertTrue(result.get("jdbc-compliant").asBoolean()); }</code><technical_language>@gaol Please remove println</technical_language>

Target:
public void testJdbcDrivers() throws Exception { String driverName = DEPLOYMENT + ".jar"; ModelNode address = new ModelNode().add(SUBSYSTEM, "datasources"); ModelNode operation = new ModelNode(); operation.get(OP).set("get-installed-driver"); operation.get(OP_ADDR).set(address); operation.get("driver-name").set(driverName); ModelNode result = executeOperation(operation).asList().get(0); Assert.assertEquals(driverName, result.get("driver-name").asString()); Assert.assertEquals(driverName, result.get("deployment-name").asString()); Assert.assertEquals(TestDriver.class.getName(), result.get("driver-class-name").asString()); Assert.assertEquals(1, result.get("driver-major-version").asInt()); Assert.assertEquals(0, result.get("driver-minor-version").asInt()); Assert.assertFalse(result.get("jdbc-compliant").asBoolean()); String driver2 = driverName + "_" + TestDriver2.class.getName() + "_1_1"; operation.get("driver-name").set(driver2); result = executeOperation(operation).asList().get(0); Assert.assertEquals(driver2, result.get("driver-name").asString()); Assert.assertEquals(driver2, result.get("deployment-name").asString()); Assert.assertEquals(TestDriver2.class.getName(), result.get("driver-class-name").asString()); Assert.assertEquals(1, result.get("driver-major-version").asInt()); Assert.assertEquals(1, result.get("driver-minor-version").asInt()); Assert.assertTrue(result.get("jdbc-compliant").asBoolean()); }
Source:
<code>private void triggerTimer(TimerInstance timerInstance) { for (Map.Entry<Timer, DroolsAction> entry : getEventBasedNode().getTimers().entrySet()) { if (entry.getKey().getId() == timerInstance.getTimerId()) { executeAction((Action) entry.getValue().getMetaData("Action")); if (!(timerInstance.getJobHandle() instanceof DefaultJobHandle)) { return; } <START> DefaultTimerJobInstance defaultTimerInstance = (DefaultTimerJobInstance) ((DefaultJobHandle) timerInstance.getJobHandle()).getTimerJobInstance(); <END> if (defaultTimerInstance.getTrigger().hasNextFireTime() == null) { timerInstances.remove(timerInstance.getId()); } return; } } }</code><technical_language>Is casting DefaultTimerJobInstance needed? For example, replacing _defaultTimerInstance_ in next line _((DefaultJobHandle) timerInstance.getJobHandle()).getTimerJobInstance()_ need this variable</technical_language>

Target:
private void triggerTimer(TimerInstance timerInstance) { for (Map.Entry<Timer, DroolsAction> entry : getEventBasedNode().getTimers().entrySet()) { if (entry.getKey().getId() == timerInstance.getTimerId()) { executeAction((Action) entry.getValue().getMetaData("Action")); if (!(timerInstance.getJobHandle() instanceof DefaultJobHandle)) { return; } TimerJobInstance defaultTimerInstance = ((DefaultJobHandle) timerInstance.getJobHandle()).getTimerJobInstance(); if (defaultTimerInstance.getTrigger().hasNextFireTime() == null) { timerInstances.remove(timerInstance.getId()); } return; } } }
Source:
<code>public void seek(Range range, Collection<ByteSequence> columnFamilies, boolean inclusive) throws IOException { Set<ByteSequence> cfSet; if (columnFamilies.size() > 0) if (columnFamilies instanceof Set<?>) { cfSet = (Set<ByteSequence>) columnFamilies; } else { cfSet = new HashSet<>(); cfSet.addAll(columnFamilies); } else cfSet = Collections.emptySet(); if (lastUsed != null && cfSet.equals(lastColumnFamilies) && inclusive == lastInclusive) { clear(); for (LocalityGroup lgr : lastUsed) { lgr.getIterator().seek(range, EMPTY_CF_SET, false); addSource(lgr.getIterator()); } } else { if (lastUsed == null) { lastUsed = new ArrayList<LocalityGroup>(lgContext.groups.length); } else { lastUsed.clear(); <START> } <END> lastColumnFamilies = cfSet; lastInclusive = inclusive; seek(this, lgContext, range, columnFamilies, inclusive, lastUsed); } }</code><technical_language>Need careful this, a ref a set a user passed. user call seek(setA) modify setA call seek(setA). In this case wrong loc groups used</technical_language>

Target:
public void seek(Range range, Collection<ByteSequence> columnFamilies, boolean inclusive) throws IOException { lgCache = seek(this, lgContext, range, columnFamilies, inclusive, lgCache); }
Source:
<code>public EventBookingDTO recordAttendance(final IsaacEventPageDTO event, final RegisteredUserDTO userDTO, final boolean attended) throws SegueDatabaseException, EventBookingUpdateException { final EventBookingDTO eventBooking = this.bookingPersistenceManager.getBookingByEventIdAndUserId( event.getId(), userDTO.getId()); if (null == eventBooking) { throw new EventBookingUpdateException("Unable to record attendance for booking that doesn't exist."); } BookingStatus attendanceStatus = attended ? BookingStatus.ATTENDED : BookingStatus.ABSENT; if (attendanceStatus.equals(eventBooking.getBookingStatus())) { throw new EventBookingUpdateException("Booking attendance is already registered."); } <START> UserSummaryDTO reservedBy = this.bookingPersistenceManager <END> .getBookingByEventIdAndUserId(event.getId(), userDTO.getId()).getReservedBy(); Long reservedById = reservedBy == null ? null : reservedBy.getId(); EventBookingDTO updatedStatus = this.bookingPersistenceManager.updateBookingStatus(eventBooking.getEventId(), userDTO.getId(), reservedById, attendanceStatus, eventBooking.getAdditionalInformation()); return updatedStatus; }</code><technical_language>Do event booking eventBooking anyway? do need load again</technical_language>

Target:
public EventBookingDTO recordAttendance(final IsaacEventPageDTO event, final RegisteredUserDTO userDTO, final boolean attended) throws SegueDatabaseException, EventBookingUpdateException { final EventBookingDTO eventBooking = this.bookingPersistenceManager.getBookingByEventIdAndUserId( event.getId(), userDTO.getId()); if (null == eventBooking) { throw new EventBookingUpdateException("Unable to record attendance for booking that doesn't exist."); } BookingStatus attendanceStatus = attended ? BookingStatus.ATTENDED : BookingStatus.ABSENT; if (attendanceStatus.equals(eventBooking.getBookingStatus())) { throw new EventBookingUpdateException("Booking attendance is already registered."); } EventBookingDTO updatedStatus = this.bookingPersistenceManager.updateBookingStatus(eventBooking.getEventId(), userDTO.getId(), attendanceStatus, eventBooking.getAdditionalInformation()); return updatedStatus; }
Source:
<code>private String <START> escapeComma(String <END> s) { if ((s.indexOf(',') < 0) && (s.indexOf('\\') < 0) && s.indexOf('\n') < 0 && s.indexOf('\r') < 0) return s; StringBuffer sb= new StringBuffer(s.length()+10); for (int i= 0; i < s.length(); i++) { char c= s.charAt(i); if (c == ',') sb.append("\\,"); else if (c == '\\') sb.append("\\\\"); else if (c == '\n' || c == '\r') sb.append(" "); else sb.append(c); } return sb.toString(); }</code><technical_language>name is longer accurate. replace line delimiters this method</technical_language>

Target:
private String escapeComma(String s) { if ((s.indexOf(',') < 0) && (s.indexOf('\\') < 0)) return s; StringBuffer sb= new StringBuffer(s.length()+10); for (int i= 0; i < s.length(); i++) { char c= s.charAt(i); if (c == ',') sb.append("\\,"); else if (c == '\\') sb.append("\\\\"); else sb.append(c); } return sb.toString(); }
Source:
<code>private void setSameTopic(GerritClient gerritClient, ChangeInfo element) { ListIterator<ChangeInfo> litr; WritableList writeInfoList; ChangeInfo[] sameTopicChangeInfo = null; fSameTopicChangeInfo.clear(); if (element.getTopic() != null) { try { sameTopicChangeInfo = querySameTopic(gerritClient, element.getTopic(), new NullProgressMonitor()); } catch (MalformedURLException e) { EGerritCorePlugin.logError(e.getMessage()); } litr = Arrays.asList(sameTopicChangeInfo).listIterator(); while (litr.hasNext()) { ChangeInfo cur = litr.next(); if (fChangeInfo.getId().compareTo(cur.getId()) != 0) { ChangeInfo item = new ChangeInfo(); <START> item.setChange_id(cur.getId()); <END> item.setSubject(cur.getSubject()); fSameTopicChangeInfo.add(item); } } writeInfoList = new WritableList(fSameTopicChangeInfo, ReviewerInfo.class); tableSameTopicViewer.setInput(writeInfoList); } }</code><technical_language>setId instead of setChangeId !!</technical_language>

Target:
private void setSameTopic(GerritClient gerritClient, ChangeInfo element) { ListIterator<ChangeInfo> litr; WritableList writeInfoList; ChangeInfo[] sameTopicChangeInfo = null; fSameTopicChangeInfo.clear(); if (element.getTopic() != null) { try { sameTopicChangeInfo = querySameTopic(gerritClient, element.getTopic(), new NullProgressMonitor()); } catch (MalformedURLException e) { EGerritCorePlugin.logError(e.getMessage()); } litr = Arrays.asList(sameTopicChangeInfo).listIterator(); while (litr.hasNext()) { ChangeInfo cur = litr.next(); if (fChangeInfo.getId().compareTo(cur.getId()) != 0) { ChangeInfo item = new ChangeInfo(); item.setChange_id(cur.getChange_id()); item.setSubject(cur.getSubject()); fSameTopicChangeInfo.add(item); } } writeInfoList = new WritableList(fSameTopicChangeInfo, ReviewerInfo.class); tableSameTopicViewer.setInput(writeInfoList); } }