auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void testGetColumnsFromJSONElement() { String json = "{" + "\"value\": " + "\"test-value\"" + "}"; <START> YailList expecetdColumn = YailList.makeList(Arrays.asList("value", "test-value")); <END> YailList expected = YailList.makeList(Collections.singletonList(expecetdColumn)); YailList result = JsonUtil.getColumnsFromJSON(json); assertEquals(expected, result); }</code><technical_language>Ditto spelling</technical_language>

Target:
public void testGetColumnsFromJSONElement() { String json = "{" + "\"value\": " + "\"test-value\"" + "}"; YailList expectedColumn = YailList.makeList(Arrays.asList("value", "test-value")); YailList expected = YailList.makeList(Collections.singletonList(expectedColumn)); YailList result = JsonUtil.getColumnsFromJSON(json); assertEquals(expected, result); }
Source:
<code>protected void doStore() { IJavaDebugTarget target; IJavaThread thread; for (IDebugTarget <START> target2 : <END> getDebugTargets()) { target = target2.getAdapter(IJavaDebugTarget.class); if (target != null) { try { if (fThreadViewer.getChecked(target)) { for (IThread thread2 : target.getThreads()) { thread= (IJavaThread)thread2; if (fThreadViewer.getChecked(thread)) { fPage.getBreakpoint().setThreadFilter(thread); break; } } } else { fPage.getBreakpoint().removeThreadFilter(target); } } catch (CoreException e) { JDIDebugUIPlugin.log(e); } } } }</code><technical_language>rename debugTarget</technical_language>

Target:
protected void doStore() { IJavaDebugTarget target; IJavaThread thread; for (IDebugTarget debugTarget : getDebugTargets()) { target = debugTarget.getAdapter(IJavaDebugTarget.class); if (target != null) { try { if (fThreadViewer.getChecked(target)) { for (IThread targetThread : target.getThreads()) { thread= (IJavaThread)targetThread; if (fThreadViewer.getChecked(thread)) { fPage.getBreakpoint().setThreadFilter(thread); break; } } } else { fPage.getBreakpoint().removeThreadFilter(target); } } catch (CoreException e) { JDIDebugUIPlugin.log(e); } } } }
Source:
<code>public void setRangeNotifier( RangeNotifier notifier ) { <START> addRangeNotifier( notifier ); <END> }</code><technical_language>This compatible existing API if this method (and monitoring equivalent) simply replaced notifier</technical_language>

Target:
public void setRangeNotifier ( RangeNotifier notifier ) { synchronized ( rangeNotifiers ) { rangeNotifiers.clear(); rangeNotifiers.add( notifier ); } }
Source:
<code>public void testIndexCreationAndQueryDeterministicConcurrency() { Config config = getConfig(); HazelcastInstance node = createHazelcastInstance(config); IMap<Integer, Person> map = node.getMap(randomMapName()); for (int i = 0; i < 10000; ++i) { map.put(i, new Person(i)); } Person.accessCountDown = new AtomicLong(5000); AtomicReference<Throwable> exception = new AtomicReference<Throwable>(); Thread indexer = new Thread(new Runnable() { @Override public void run() { try { map.addIndex("age", true); } catch (Throwable t) { exception.compareAndSet(null, t); } } }); indexer.start(); assertOpenEventually(Person.queryLatch); Person.accessCountDown = null; Collection<Person> persons = map.values(new SqlPredicate("age >= 5000")); assertEquals(5000, persons.size()); persons = map.values(Predicates.equal("age", "20")); assertEquals(1, persons.size()); persons = map.values(Predicates.greaterThan("age", "5000")); <START> assertEquals(4999, persons.size()); <END> Person.indexerLatch.countDown(); assertJoinable(indexer); assertNull(exception.get()); }</code><technical_language>predicates checked, other types fail. E,g, AndPredicate, OrPredicate. extend check for built-in predicate types. Bitmap indexes generate predicates optimization process (EvaluatePredicate), a separate test for bitmaps is needed, matching predicate types</technical_language>

Target:
public void testIndexCreationAndQueryDeterministicConcurrency() { Config config = getConfig(); HazelcastInstance node = createHazelcastInstance(config); final IMap<Integer, Person> map = node.getMap(randomMapName()); for (int i = 0; i < 10000; ++i) { map.put(i, new Person(i)); } Person.accessCountDown = new AtomicLong(5000); final AtomicReference<Throwable> exception = new AtomicReference<Throwable>(); Thread indexer = new Thread(new Runnable() { @Override public void run() { try { boolean ordered = indexDefinition.contains("BITMAP") ? false : true; map.addIndex(indexDefinition, ordered); } catch (Throwable t) { exception.compareAndSet(null, t); } } }); indexer.start(); assertOpenEventually(Person.queryLatch); Person.accessCountDown = null; assertQuery(map, new SqlPredicate("age >= 5000"), 5000); assertQuery(map, equal("age", "6000"), 1); assertQuery(map, greaterThan("age", "6000"), 3999); assertQuery(map, and(greaterThan("age", 6000), lessThan("age", 7000)), 999); assertQuery(map, or(equal("age", 6000), equal("age", 7000)), 2); assertQuery(map, greaterEqual("age", 5000), 5000); assertQuery(map, lessThan("age", 9000), 9000); assertQuery(map, lessEqual("age", 9000), 9001); assertQuery(map, between("age", 9000, 10000), 1000); assertQuery(map, in("age", 5000, 6000, 7000, 11111), 3); assertQuery(map, equal("age", "6000"), 1); assertQuery(map, like("name", "9999"), 1); Person.indexerLatch.countDown(); assertJoinable(indexer); assertNull(exception.get()); }
Source:
<code>private void updateProgress() throws IOException, KeeperException, InterruptedException { Table snapshotTable = connection.getTable(masterSnapshotTable); Scan scan = new Scan(); try (ResultScanner scanner = snapshotTable.getScanner(scan)) { for (Result r : scanner) { byte[] rowKey = r.getRow(); long timestamp = new Long(new String(rowKey)); SpliceLogUtils.info(LOG, "Checking snapshot taken at %d", timestamp); CellScanner s = r.cellScanner(); long ts = -1; while (s.advance()) { Cell cell = s.current(); byte[] colName = CellUtil.cloneQualifier(cell); if(Arrays.equals(colName, HBaseConfiguration.REPLICATION_SNAPSHOT_TSCOL_BYTES)){ ts = Bytes.toLong(CellUtil.cloneValue(cell)); SpliceLogUtils.info(LOG, "Process snapshot take at %s", new DateTime(ts).toString()); } else { <START> String walName = Bytes.toString(CellUtil.cloneQualifier(cell)); <END> Long position = Bytes.toLong(CellUtil.cloneValue(cell)); if (replicationProgress.containsKey(walName)) { long appliedPosition = replicationProgress.get(walName); SpliceLogUtils.info(LOG, "WAL=%s, snapshot=%d, progress=%d", walName, position, appliedPosition); if (appliedPosition < position) { return; } } } } Delete d = new Delete(rowKey); snapshotTable.delete(d); SpliceLogUtils.info(LOG, "Deleted snapshot %d.", timestamp); ReplicationUtils.setTimestamp(timestamp); updateZkProgress(ts); } }finally { replicationProgress.clear(); } }</code><technical_language>call CellUtil.cloneQualifier(cell) redundant, colName</technical_language>

Target:
private void updateProgress() throws IOException, KeeperException, InterruptedException { Table snapshotTable = connection.getTable(masterSnapshotTable); Scan scan = new Scan(); try (ResultScanner scanner = snapshotTable.getScanner(scan)) { for (Result r : scanner) { byte[] rowKey = r.getRow(); long timestamp = new Long(new String(rowKey)); SpliceLogUtils.info(LOG, "Checking snapshot taken at %d", timestamp); CellScanner s = r.cellScanner(); long ts = -1; while (s.advance()) { Cell cell = s.current(); byte[] colName = CellUtil.cloneQualifier(cell); if(Arrays.equals(colName, HBaseConfiguration.REPLICATION_SNAPSHOT_TSCOL_BYTES)){ ts = Bytes.toLong(CellUtil.cloneValue(cell)); SpliceLogUtils.info(LOG, "Process snapshot take at %s", new DateTime(ts).toString()); } else { String walName = Bytes.toString(colName); Long position = Bytes.toLong(CellUtil.cloneValue(cell)); if (replicationProgress.containsKey(walName)) { long appliedPosition = replicationProgress.get(walName); SpliceLogUtils.info(LOG, "WAL=%s, snapshot=%d, progress=%d", walName, position, appliedPosition); if (appliedPosition < position) { return; } } } } Delete d = new Delete(rowKey); snapshotTable.delete(d); SpliceLogUtils.info(LOG, "Deleted snapshot %d.", timestamp); ReplicationUtils.setTimestamp(timestamp); updateZkProgress(ts); } }finally { replicationProgress.clear(); } }
Source:
<code><START> private String getCamelEndpointId(WorkItem workItem) { <END> String workItemCamelEndpointId = (String) workItem.getParameter(CAMEL_ENDPOINT_ID_PARAM); if (camelEndpointId != null && !camelEndpointId.isEmpty()) { if (workItemCamelEndpointId != null && !workItemCamelEndpointId.isEmpty()) { logger.debug( "The Camel Endpoint ID has been set on both the WorkItemHanlder and WorkItem. The camel-endpoint-id configured on the WorkItem overrides the global configuation."); } else { workItemCamelEndpointId = camelEndpointId; } } if (workItemCamelEndpointId == null || workItemCamelEndpointId.isEmpty()) { throw new IllegalArgumentException( "No Camel Endpoint ID specified. Please configure the 'camel-endpoint-id' in either the constructor of this WorkItemHandler, or pass it via the " + CAMEL_ENDPOINT_ID_PARAM + "' WorkItem parameter."); } return workItemCamelEndpointId; }</code><technical_language>protected overridden</technical_language>

Target:
protected String getCamelEndpointId(WorkItem workItem) { String workItemCamelEndpointId = (String) workItem.getParameter(JBPMConstants.CAMEL_ENDPOINT_ID_WI_PARAM); if (camelEndpointId != null && !camelEndpointId.isEmpty()) { if (workItemCamelEndpointId != null && !workItemCamelEndpointId.isEmpty()) { logger.debug( "The Camel Endpoint ID has been set on both the WorkItemHanlder and WorkItem. The '" + JBPMConstants.CAMEL_ENDPOINT_ID_WI_PARAM + "' configured on the WorkItem overrides the global configuation."); } else { workItemCamelEndpointId = camelEndpointId; } } if (workItemCamelEndpointId == null || workItemCamelEndpointId.isEmpty()) { throw new IllegalArgumentException( "No Camel Endpoint ID specified. Please configure the '" + JBPMConstants.CAMEL_ENDPOINT_ID_WI_PARAM + "' in either the constructor of this WorkItemHandler, or pass it via the " + JBPMConstants.CAMEL_ENDPOINT_ID_WI_PARAM + "' WorkItem parameter."); } return workItemCamelEndpointId; }
Source:
<code>protected ReftableBatchRefUpdate(DfsReftableDatabase refdb, DfsObjDatabase odb) { super(refdb); this.refdb = refdb; this.odb = odb; lock = refdb.getLock(); Config cfg = refdb.getRepository().getConfig(); reftableConfig = new ReftableConfig(); <START> if (refdb instanceof InMemoryRepository.MemRefDatabase) { <END> reftableConfig.setAlignBlocks(false); reftableConfig.setIndexObjects(false); } reftableConfig.fromConfig(cfg); }</code><technical_language>This feels a layering violation. Is e.g. a method in DfsReftableDatabase handle this</technical_language>

Target:
protected ReftableBatchRefUpdate(DfsReftableDatabase refdb, DfsObjDatabase odb) { super(refdb); this.refdb = refdb; this.odb = odb; lock = refdb.getLock(); reftableConfig = refdb.getReftableConfig(); }
Source:
<code>public void run() { try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .childHandler(channelInitializer); Channel ch = b.bind(port).sync().channel(); logger.info("netty httpserver start"); ch.closeFuture().sync(); } catch (InterruptedException e) { logger.info("netty httpserver interrupted"); <START> logger.error(e.getMessage(), e); <END> } finally { shutdown(); } }</code><technical_language>I a test, do Thread.currentThread.interrupt</technical_language>

Target:
public void run() { try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .childHandler(channelInitializer); Channel ch = b.bind(port).sync().channel(); logger.info("netty httpserver start"); ch.closeFuture().sync(); } catch (InterruptedException e) { logger.info("netty httpserver interrupted"); logger.error(e.getMessage(), e); Thread.currentThread().interrupt(); } finally { shutdown(); } }
Source:
<code><START> protected boolean shouldDoFakeParticles() { <END> if(ConfigHandler.staticWandBeam) return true; ChunkCoordinates coords = getBurstSourceChunkCoordinates(); TileEntity tile = worldObj.getTileEntity(coords.posX, coords.posY, coords.posZ); if(tile != null && tile instanceof IManaSpreader) return getMana() != getStartingMana() && fullManaLastTick || Math.abs(((IManaSpreader) tile).getBurstParticleTick() - getTicksExisted()) < 4; return false; }</code><technical_language>If public</technical_language>

Target:
public boolean shouldDoFakeParticles() { if(ConfigHandler.staticWandBeam) return true; ChunkCoordinates coords = getBurstSourceChunkCoordinates(); TileEntity tile = worldObj.getTileEntity(coords.posX, coords.posY, coords.posZ); if(tile != null && tile instanceof IManaSpreader) return getMana() != getStartingMana() && fullManaLastTick || Math.abs(((IManaSpreader) tile).getBurstParticleTick() - getTicksExisted()) < 4; return false; }
Source:
<code>private PrintRequest createPrintRequest(ActionParameters params) throws ActionException { PrintRequest request = new PrintRequest(); request.setSrsName(params.getRequiredParam(PARM_SRSNAME)); request.setResolution(params.getRequiredParamDouble(PARM_RESOLUTION)); request.setTitle(params.getHttpParam(PARM_TITLE)); request.setShowLogo(params.getHttpParam(PARM_LOGO, false)); request.setShowScale(params.getHttpParam(PARM_SCALE, false)); request.setShowDate(params.getHttpParam(PARM_DATE, false)); request.setScaleText(params.getHttpParam(PARM_SCALE_TEXT, "")); setPagesize(params, request); setCoordinates(params.getRequiredParam(PARM_COORD), request); setFormat(params.getRequiredParam(PARM_FORMAT), request); <START> request.setUseConfiguredScale(params.getHttpParam(PARM_USE_CONFIGURED_SCALE, false)); <END> List<PrintLayer> layers = getLayers(params.getRequiredParam(PARM_MAPLAYERS), params.getUser()); layers = filterLayersWithZeroOpacity(layers); if(request.isUseConfiguredScale()) { layers = filterLayersWithSupportOwnScale(layers); } request.setLayers(layers); setTiles(layers, params.getHttpParam(PARM_TILES)); return request; }</code><technical_language>I a reason for parameters trigger UseConfiguredScale-mode</technical_language>

Target:
private PrintRequest createPrintRequest(ActionParameters params) throws ActionException { PrintRequest request = new PrintRequest(); request.setSrsName(params.getRequiredParam(PARM_SRSNAME)); request.setResolution(params.getRequiredParamDouble(PARM_RESOLUTION)); request.setTitle(params.getHttpParam(PARM_TITLE)); request.setShowLogo(params.getHttpParam(PARM_LOGO, false)); request.setShowScale(params.getHttpParam(PARM_SCALE, false)); request.setShowDate(params.getHttpParam(PARM_DATE, false)); request.setScaleText(params.getHttpParam(PARM_SCALE_TEXT, "")); setPagesize(params, request); setCoordinates(params.getRequiredParam(PARM_COORD), request); setFormat(params.getRequiredParam(PARM_FORMAT), request); List<PrintLayer> layers = getLayers(params.getRequiredParam(PARM_MAPLAYERS), params.getUser()); if(request.isScaleText()) { layers = filterLayersWithSupportOwnScale(layers); } request.setLayers(layers); setTiles(layers, params.getHttpParam(PARM_TILES)); return request; }
Source:
<code>protected void onMethodInvocationFound(MethodInvocationTree mit) { ExpressionTree arg = mit.arguments().get(0); String domain = ConstantUtils.resolveAsStringConstant(arg); <START> if (domain != null && !domain.substring(1).contains(".")) { <END> reportIssue(arg, "Specify at least a second-level cookie domain."); } }</code><technical_language>Check crash if code contains a call setDomain method empty string myCookie.setDomain("");</technical_language>

Target:
protected void onMethodInvocationFound(MethodInvocationTree mit) { ExpressionTree arg = mit.arguments().get(0); String domain = ConstantUtils.resolveAsStringConstant(arg); if (domain != null && !domain.isEmpty() && !domain.substring(1).contains(".")) { reportIssue(arg, "Specify at least a second-level cookie domain."); } }
Source:
<code>private void handleEvent(LogEvent event) throws InterruptedException { if (usingAsyncLogger) { sendEventToSystemProducer(encodeLogEventToBytes(event)); return; } if (!logQueue.offer(encodeLogEventToBytes(event), queueTimeoutS, TimeUnit.SECONDS)) { int messagesDropped = logQueue.drainTo(new ArrayList<>()) + 1; <START> log.warn(String.format("Exceeded timeout %ss while trying to log to %s. Dropping %d log messages.", queueTimeoutS, systemStream.toString(), messagesDropped)); <END> metrics.logMessagesDropped.inc(messagesDropped); } metrics.bufferFillPct.set(Math.round(100f * logQueue.size() / DEFAULT_QUEUE_SIZE)); }</code><technical_language>Capturing offline conversation - "We need this replaced System.err recursion drop this message in event of able acquire lock timeout"</technical_language>

Target:
private void handleEvent(LogEvent event) throws InterruptedException { if (usingAsyncLogger) { sendEventToSystemProducer(encodeLogEventToBytes(event)); return; } if (!logQueue.offer(encodeLogEventToBytes(event), queueTimeoutS, TimeUnit.SECONDS)) { int messagesDropped = logQueue.drainTo(new ArrayList<>()) + 1; System.err.println(String.format("Exceeded timeout %ss while trying to log to %s. Dropping %d log messages.", queueTimeoutS, systemStream.toString(), messagesDropped)); metrics.logMessagesDropped.inc(messagesDropped); } metrics.bufferFillPct.set(Math.round(100f * logQueue.size() / DEFAULT_QUEUE_SIZE)); }
Source:
<code>void setSelectedGame(Game game) { gameDetailController.setGame(game); if (game == null) { gameDetailPane.setVisible(false); return; } if (preferencesService.getPreferences().isShowGameDetailsSidePane()) { <START> gameDetailPane.setVisible(true); <END> } }</code><technical_language>bind properties</technical_language>

Target:
void setSelectedGame(Game game) { gameDetailController.setGame(game); }
Source:
<code>private synchronized void loadSettings() { try (InputStream is = settingsFacade.getRawConfig(SETTINGS_FILE_NAME)) { String jsonText = IOUtils.toString(is); LOGGER.debug("Loading DHIS2 settings..."); Gson gson = new Gson(); settings = gson.fromJson(jsonText, Settings.class); <START> String URI = settings.getServerURI(); <END> if(settings.getServerURI().endsWith("/")) { settings.setServerURI(URI.substring(0,URI.length()-1)); } } catch (Exception e) { String message = "There was an error loading json from the DHIS2 settings."; LOGGER.debug(message); throw new JsonIOException(message, e); } }</code><technical_language>local variable name capitalized</technical_language>

Target:
private synchronized void loadSettings() { try (InputStream is = settingsFacade.getRawConfig(SETTINGS_FILE_NAME)) { String jsonText = IOUtils.toString(is); LOGGER.debug("Loading DHIS2 settings..."); Gson gson = new Gson(); settings = gson.fromJson(jsonText, Settings.class); if (settings.getServerURI() != null) { settings.setServerURI(removeTrailingSlash()); } } catch (Exception e) { String message = "There was an error loading json from the DHIS2 settings."; LOGGER.debug(message); throw new JsonIOException(message, e); } }
Source:
<code>public LinkedHashMap<String, String> getLanguageList() { LinkedHashMap<String, String> languageArray = new LinkedHashMap<>(); for (Map.Entry<String, String> entry : this.entrySet()) { if (entry.getValue() != null) { <START> final Locale locale = new Locale(entry.getKey()); <END> languageArray.put(entry.getKey(), locale.getDisplayLanguage()); } } return this.size() == 0 ? null : languageArray; }</code><technical_language>This a good place LocaleUtils class instead</technical_language>

Target:
public LinkedHashMap<String, String> getLanguageList() { LinkedHashMap<String, String> languageArray = new LinkedHashMap<>(); for (Map.Entry<String, String> entry : this.entrySet()) { if (entry.getValue() != null) { try { languageArray.put(entry.getKey(), LocaleUtils.getLanguageNameFromCode(entry.getKey())); } catch (InvalidLocaleException e) { logger.error(e, true); } } } return this.size() == 0 ? null : languageArray; }
Source:
<code>public AddApiVersionToRequest(@ApiVersion String apiVersion) { <START> this.apiVersion = checkNotNull(apiVersion, "apiVersion"); <END> }</code><technical_language>Remove public modifier constructor remove null check</technical_language>

Target:
AddApiVersionToRequest(@ApiVersion String apiVersion) { this.apiVersion = apiVersion; }
Source:
<code>protected void unbindEventService(EventService eventService) { <START> eventService.unregisterListener(EventConfigUpdate.class, this); <END> }</code><technical_language>eventService.unregisterListener(EventConfigUpdate.class, this); this.eventService = null;</technical_language>

Target:
protected void unbindEventService(EventService eventService) { eventService.unregisterListener(EventConfigUpdate.class, this); this.eventService = null; }
Source:
<code>private StartIdentifiedAtlasDbTransactionResponse startTransactionResponseWith(LockToken lockToken) { return StartIdentifiedAtlasDbTransactionResponse.of( LockImmutableTimestampResponse.of(1L, lockToken), mock(TimestampAndPartition.class) <START> ); <END> }</code><technical_language>prefer putting braces next line; style AtlasDB (and Palantir in general) close braces once</technical_language>

Target:
private StartIdentifiedAtlasDbTransactionResponse startTransactionResponseWith(LockToken lockToken) { return StartIdentifiedAtlasDbTransactionResponse.of( LockImmutableTimestampResponse.of(1L, lockToken), timestampAndPartition); }
Source:
<code>private static String fullyQualifiedModuleName(String fileName, String packageName) { int extensionIndex = fileName.lastIndexOf('.'); <START> String moduleName = fileName.substring(0, extensionIndex); <END> return packageName.isEmpty() ? moduleName : (packageName + "." + moduleName); }</code><technical_language>if fileName .</technical_language>

Target:
private static String fullyQualifiedModuleName(String fileName, String packageName) { int extensionIndex = fileName.lastIndexOf('.'); String moduleName = extensionIndex > 0 ? fileName.substring(0, extensionIndex) : fileName; return packageName.isEmpty() ? moduleName : (packageName + "." + moduleName); }
Source:
<code><START> public void shouldWaitForFunctionsWorkerStarted() { <END> try (PulsarContainer pulsar = new PulsarContainer().withFunctionsWorker()) { pulsar.start(); } }</code><technical_language>Is assert ensure works? Otherwise, this test pass if I withFunctionsWorker NO-OP</technical_language>

Target:
public void shouldWaitForFunctionsWorkerStarted() throws Exception { try (PulsarContainer pulsar = new PulsarContainer("2.5.1").withFunctionsWorker()) { pulsar.start(); PulsarAdmin pulsarAdmin = PulsarAdmin.builder() .serviceHttpUrl(pulsar.getHttpServiceUrl()) .build(); assertThat(pulsarAdmin.functions().getFunctions("public", "default")).hasSize(0); } }
Source:
<code>public Object evaluate(Object feature) { Map map = getExpression(0).evaluate(feature, Map.class); String key = getExpression(1).evaluate(feature, String.class); <START> if (map.containsKey(key)) { <END> return map.get(key); } return null; }</code><technical_language>NPE prone, check if map is null. Also, need check if map contains, simply call get: suggestion if (map != null) { return map.get(key); }</technical_language>

Target:
public Object evaluate(Object feature) { Map map = getExpression(0).evaluate(feature, Map.class); String key = getExpression(1).evaluate(feature, String.class); if (map != null) { return map.get(key); } return null; }
Source:
<code>public void hook(ExtensionHook extensionHook) { super.hook(extensionHook); <START> extensionHook.addSessionListener(this); <END> if (getView() != null) { extensionHook.getHookMenu().addToolsMenuItem(getMenuReload()); hookView = extensionHook.getHookView(); hookView.addStatusPanel(getStatusPanel()); } }</code><technical_language>moved if</technical_language>

Target:
public void hook(ExtensionHook extensionHook) { super.hook(extensionHook); if (getView() != null) { extensionHook.addSessionListener(this); hookView = extensionHook.getHookView(); eventConsumerImpl = new EventConsumerImpl(getNotesTableModel()); hookView.addStatusPanel(getStatusPanel()); ZAP.getEventBus() .registerConsumer( eventConsumerImpl, HistoryReferenceEventPublisher.getPublisher().getPublisherName()); } }
Source:
<code><START> private Object next() { <END> if (this.iterator == null || !this.iterator.hasNext()) { this.iterator = this.listeners.iterator(); } return this.iterator.next(); }</code><technical_language>I suggest making this method synchronized</technical_language>

Target:
private synchronized Object next() { if (this.iterator == null || !this.iterator.hasNext()) { this.iterator = this.listeners.iterator(); } return this.iterator.next(); }
Source:
<code>public InstructorCourseEnrollPageData(AccountAttributes account, String courseId, String enrollStudents) { super(account); this.courseId = Sanitizer.sanitizeForHtml(courseId); <START> this.enrollStudents = Sanitizer.sanitizeForHtml(enrollStudents); <END> }</code><technical_language>I sanitizeForHtml() is availabe PageData, need for static reference Sanitizer</technical_language>

Target:
public InstructorCourseEnrollPageData(AccountAttributes account, String courseId, String enrollStudents) { super(account); this.courseId = sanitizeForHtml(courseId); this.enrollStudents = sanitizeForHtml(enrollStudents); }
Source:
<code><START> public static String getPermissionStringValue(LabelledPermission labelledPermission) { <END> PermissionSet permissionSet = labelledPermission.getPermission(); if (permissionSet != null) { int mask = permissionSet.getMask(); switch (mask) { case READ_META_MASK: return READMETA; case COUNT_MASK: return COUNT; case READ_MASK: return READ; case WRITE_MASK: return WRITE; case WRITEMETA_MASK: return WRITEMETA; default: throw new IllegalArgumentException(format("Unexpected mask '%d'", mask)); } } return null; }</code><technical_language>Return Optional for methods return null</technical_language>

Target:
public static Optional<String> getPermissionStringValue(LabelledPermission labelledPermission) { PermissionSet permissionSet = labelledPermission.getPermission(); if (permissionSet != null) { int mask = permissionSet.getMask(); switch (mask) { case READ_META_MASK: return Optional.of(READMETA); case COUNT_MASK: return Optional.of(COUNT); case READ_MASK: return Optional.of(READ); case WRITE_MASK: return Optional.of(WRITE); case WRITEMETA_MASK: return Optional.of(WRITEMETA); default: throw new IllegalArgumentException(format(UNEXPECTED_MASK_MESSAGE, mask)); } } return Optional.empty(); }
Source:
<code>public Boolean call() throws Exception { RequestContext context = new RequestContext() { @Override public CurrentUser getCurrentUser() { return identifiedUserFactory.create(change.getOwner()); } @Override public Provider<ReviewDb> getReviewDbProvider() { return new Provider<ReviewDb>() { @Override public ReviewDb get() { if (reviewDb == null) { try { reviewDb = schemaFactory.open(); } catch (OrmException e) { throw new ProvisionException("Cannot open ReviewDb", e); } } return reviewDb; } }; } }; RequestContext old = tl.setContext(context); ReviewDb db = context.getReviewDbProvider().get(); try { PatchSet ps = db.patchSets().get(change.currentPatchSetId()); MergeableInfo info = <START> mergeable.get().apply(new <END> RevisionResource(new ChangeResource( changeControlFactory.controlFor(change, context.getCurrentUser())), ps)); return change.isMergeable() != info.mergeable; } finally { tl.setContext(old); if (reviewDb != null) { reviewDb.close(); reviewDb = null; } } }</code><technical_language>Throws ResourceConflictException closed changes. I callers care, return false that</technical_language>

Target:
public Boolean call() throws Exception { RequestContext context = new RequestContext() { @Override public CurrentUser getCurrentUser() { return identifiedUserFactory.create(change.getOwner()); } @Override public Provider<ReviewDb> getReviewDbProvider() { return new Provider<ReviewDb>() { @Override public ReviewDb get() { if (reviewDb == null) { try { reviewDb = schemaFactory.open(); } catch (OrmException e) { throw new ProvisionException("Cannot open ReviewDb", e); } } return reviewDb; } }; } }; RequestContext old = tl.setContext(context); ReviewDb db = context.getReviewDbProvider().get(); try { PatchSet ps = db.patchSets().get(change.currentPatchSetId()); MergeableInfo info = mergeable.get().apply(new RevisionResource(new ChangeResource( changeControlFactory.controlFor(change, context.getCurrentUser())), ps)); return change.isMergeable() != info.mergeable; } catch (ResourceConflictException e) { return false; } finally { tl.setContext(old); if (reviewDb != null) { reviewDb.close(); reviewDb = null; } } }
Source:
<code>public CompletableFuture<Void> createJobManagerComponent(KubernetesJobManagerSpecification kubernetesJMSpec) { final Deployment deployment = kubernetesJMSpec.getDeployment(); final List<HasMetadata> accompanyingResources = kubernetesJMSpec.getAccompanyingResources(); LOG.debug("Start to create deployment with spec {}", deployment.getSpec().toString()); <START> return CompletableFuture.runAsync(() -> { <END> final Deployment createdDeployment = this.internalClient .apps() .deployments() .inNamespace(this.nameSpace) .create(deployment); setOwnerReference(createdDeployment, accompanyingResources); this.internalClient .resourceList(accompanyingResources) .inNamespace(this.nameSpace) .createOrReplace(); }, executorWrapper.getExecutor()); }</code><technical_language>suggestion return CompletableFuture.runAsync( () -> { Flink codestyle is put function argument new line if line breaks</technical_language>

Target:
public void createJobManagerComponent(KubernetesJobManagerSpecification kubernetesJMSpec) { final Deployment deployment = kubernetesJMSpec.getDeployment(); final List<HasMetadata> accompanyingResources = kubernetesJMSpec.getAccompanyingResources(); LOG.debug("Start to create deployment with spec {}", deployment.getSpec().toString()); final Deployment createdDeployment = this.internalClient .apps() .deployments() .inNamespace(this.nameSpace) .create(deployment); setOwnerReference(createdDeployment, accompanyingResources); this.internalClient .resourceList(accompanyingResources) .inNamespace(this.nameSpace) .createOrReplace(); }
Source:
<code>public boolean has_finished( int sample_idx ) { if( loop_length <= 1 && sample_idx > loop_start ) { return true; } else { <START> return false; <END> } }</code><technical_language>This shows optimization all</technical_language>

Target:
public boolean has_finished( int sample_idx ) { return loop_length <= 1 && sample_idx > loop_start; }
Source:
<code>protected void onResume() { super.onResume(); EventBus.getDefault().register(this); mDispatcher.register(this); <START> if (mPost == null) { <END> finish(); return; } mPost = mPostStore.getPostByLocalPostId(mPost.getId()); if (hasPreviewFragment()) { refreshPreview(); } else { showPreviewFragment(); } showMessageViewIfNecessary(); }</code><technical_language>this null check getPostByLocalPostId() call below</technical_language>

Target:
protected void onResume() { super.onResume(); EventBus.getDefault().register(this); mDispatcher.register(this); if (mPost == null || (mPost = mPostStore.getPostByLocalPostId(mPost.getId())) == null) { finish(); return; } if (hasPreviewFragment()) { refreshPreview(); } else { showPreviewFragment(); } showMessageViewIfNecessary(); }
Source:
<code>public InputStream openClasspathResource(Class<?> baseClass, String path) { <START> Preconditions.notBlank(path, "Classpath resource [" + path + "] must not be null or blank"); <END> InputStream inputStream = baseClass.getResourceAsStream(path); return Preconditions.notNull(inputStream, () -> "Classpath resource [" + path + "] does not exist"); }</code><technical_language>suggestion Preconditions.notBlank(path, () -> "Classpath resource [" + path + "] null blank");</technical_language>

Target:
public InputStream openClasspathResource(Class<?> baseClass, String path) { Preconditions.notBlank(path, () -> "Classpath resource [" + path + "] must not be null or blank"); InputStream inputStream = baseClass.getResourceAsStream(path); return Preconditions.notNull(inputStream, () -> "Classpath resource [" + path + "] does not exist"); }
Source:
<code>public void testValidHostedFileNames() throws IOException { HostedApi api = new HostedApi(getWebClient(ADMIN_USERNAME, testingPostgres)); Workflow hostedWorkflow = api <START> .createHostedWorkflow("awesomeTool", null, DescriptorLanguage.WDL.toString().toLowerCase(), null, null); <END> SourceFile file = new SourceFile(); file.setContent(FileUtils.readFileToString(new File(ResourceHelpers.resourceFilePath("metadata_example2.wdl")), StandardCharsets.UTF_8)); file.setType(SourceFile.TypeEnum.DOCKSTORE_WDL); file.setPath("/Dockstore.wdl"); SourceFile file2 = new SourceFile(); file2.setContent(FileUtils.readFileToString(new File(ResourceHelpers.resourceFilePath("metadata_example2.wdl")), StandardCharsets.UTF_8)); file2.setPath("/"); List sourceFiles = new ArrayList(); sourceFiles.add(file); sourceFiles.add(file2); thrown.expectMessage("Files must have a name"); Workflow workflow = api.editHostedWorkflow(hostedWorkflow.getId(), sourceFiles); sourceFiles.remove(file2); file2.setPath("folder/"); sourceFiles.add(file2); thrown.expectMessage("Files must have a name"); workflow = api.editHostedWorkflow(hostedWorkflow.getId(), sourceFiles); sourceFiles.remove(file2); file2.setPath("/name.wdl"); workflow = api.editHostedWorkflow(hostedWorkflow.getId(), sourceFiles); }</code><technical_language>need lowercase</technical_language>

Target:
public void testValidHostedFileNames() throws IOException { HostedApi api = new HostedApi(getWebClient(ADMIN_USERNAME, testingPostgres)); Workflow hostedWorkflow = api .createHostedWorkflow("awesomeTool", null, DescriptorLanguage.WDL.toString(), null, null); SourceFile file = new SourceFile(); file.setContent(FileUtils.readFileToString(new File(ResourceHelpers.resourceFilePath("metadata_example2.wdl")), StandardCharsets.UTF_8)); file.setType(SourceFile.TypeEnum.DOCKSTORE_WDL); file.setPath("/Dockstore.wdl"); SourceFile file2 = new SourceFile(); file2.setContent(FileUtils.readFileToString(new File(ResourceHelpers.resourceFilePath("metadata_example2.wdl")), StandardCharsets.UTF_8)); file2.setPath("/"); List sourceFiles = new ArrayList(); sourceFiles.add(file); sourceFiles.add(file2); String msg = "Files must have a name"; thrown.expectMessage(msg); Workflow workflow = api.editHostedWorkflow(hostedWorkflow.getId(), sourceFiles); sourceFiles.remove(file2); file2.setPath("folder/"); sourceFiles.add(file2); thrown.expectMessage(msg); workflow = api.editHostedWorkflow(hostedWorkflow.getId(), sourceFiles); sourceFiles.remove(file2); file2.setPath("/name.wdl"); workflow = api.editHostedWorkflow(hostedWorkflow.getId(), sourceFiles); }
Source:
<code>public void close() { <START> if (isConsumed) return; <END> isConsumed = true; responseQueueReader.close(); }</code><technical_language>Please add brackets return;</technical_language>

Target:
public void close() { if (isConsumed) { return; } isConsumed = true; responseQueueReader.close(); }
Source:
<code>public void testCamelLastExchangFailureTimestamp() throws Exception{ String rulePattern = "\n---\nrules:\n- pattern: 'org.apache.camel<context=([^,]+), type=routes, name=\"([^\"]+)\"><>LastExchangeFailureTimestamp'\n" + " name: org.apache.camel.LastExchangeFailureTimestamp\n" + " help: Exchanges Last Failure Timestamps\n" + " type: UNTYPED\n" + " labels:\n" + " context: \"$1\"\n" + " route: \"$2\"\n" + " type: routes"; JmxCollector jc = new JmxCollector(rulePattern).register(registry); <START> assertEquals(Double.valueOf((double)Camel.EXPECTED_DATE_IN_MILLISECONDS / 1000), registry.getSampleValue("org_apache_camel_LastExchangeFailureTimestamp", new String[]{"context", "route", "type"}, new String[]{"my-camel-context", "my-route-name", "routes"})); <END> }</code><technical_language>Check for actual literal float value</technical_language>

Target:
public void testCamelLastExchangFailureTimestamp() throws Exception{ String rulePattern = "\n---\nrules:\n- pattern: 'org.apache.camel<context=([^,]+), type=routes, name=\"([^\"]+)\"><>LastExchangeFailureTimestamp'\n" + " name: org.apache.camel.LastExchangeFailureTimestamp\n" + " help: Exchanges Last Failure Timestamps\n" + " type: UNTYPED\n" + " labels:\n" + " context: \"$1\"\n" + " route: \"$2\"\n" + " type: routes"; JmxCollector jc = new JmxCollector(rulePattern).register(registry); Double actual = registry.getSampleValue("org_apache_camel_LastExchangeFailureTimestamp", new String[]{"context", "route", "type"}, new String[]{"my-camel-context", "my-route-name", "routes"}); assertEquals(Camel.EXPECTED_SECONDS, actual, 0); }
Source:
<code>public @Nullable Object resolve(@NonNull ISegment segment) { if (segment instanceof ICalledFunction) { ICalledFunction calledFunction = (ICalledFunction) segment; ITmfTrace trace = TmfTraceManager.getInstance().getActiveTrace(); if (trace != null) { String symbolText; Object symbol = calledFunction.getSymbol(); if (symbol instanceof Long) { Long longAddress = (Long) symbol; Collection<ISymbolProvider> providers = SymbolProviderManager.getInstance().getSymbolProviders(trace); <START> symbolText = providers.stream().map(p -> p.getSymbolText(longAddress)) .filter(s -> s != null) .findFirst().orElse(null); <END> if (symbolText == null) { return "0x" + Long.toHexString(longAddress); } long time = segment.getStart(); int pid = calledFunction.getProcessId(); if (pid > 0) { String text = providers.stream().map(p -> p.getSymbolText(pid, time, longAddress)) .filter(s -> s != null) .findFirst().orElse(null); if (text != null) { return text; } } return symbolText; } return String.valueOf(symbol); } } return null; }</code><technical_language>streams? in hot path too</technical_language>

Target:
public @Nullable Object resolve(@NonNull ISegment segment) { if (segment instanceof ICalledFunction) { ICalledFunction calledFunction = (ICalledFunction) segment; ITmfTrace trace = TmfTraceManager.getInstance().getActiveTrace(); if (trace != null) { String symbolText = null; Object symbol = calledFunction.getSymbol(); if (symbol instanceof Long) { Long longAddress = (Long) symbol; Collection<ISymbolProvider> providers = SymbolProviderManager.getInstance().getSymbolProviders(trace); for (ISymbolProvider provider: providers) { symbolText = provider.getSymbolText(longAddress); if (symbolText != null) { break; } } if (symbolText == null) { return "0x" + Long.toHexString(longAddress); } long time = segment.getStart(); int pid = calledFunction.getProcessId(); if (pid > 0) { for (ISymbolProvider provider: providers) { String text = provider.getSymbolText(pid, time, longAddress); if (text != null) { return text; } } } return symbolText; } return String.valueOf(symbol); } } return null; }
Source:
<code>private void accumulateSlowOperationTracking(String actionName, Stopwatch stopwatch, Optional<Exception> failure) { if (stopwatchDescribesSlowOperation(stopwatch)) { slowestOperation.accumulateAndGet( Optional.of(ImmutableActionProfile.of(actionName, stopwatch.elapsed(), failure)), <START> (existing, update) -> !existing.isPresent() <END> || existing.get().duration().compareTo(stopwatch.elapsed()) < 0 ? update : existing); } }</code><technical_language>I understand this, I prefer for this written a single expression (obviously in lambda)</technical_language>

Target:
private void accumulateSlowOperationTracking(String actionName, Stopwatch stopwatch, Optional<Exception> failure) { if (stopwatchDescribesSlowOperation(stopwatch)) { slowestOperation.accumulateAndGet( Optional.of(ImmutableActionProfile.of(actionName, stopwatch.elapsed(), failure)), (existing, update) -> { if (!existing.isPresent()) { return update; } return existing.get().duration().compareTo(stopwatch.elapsed()) < 0 ? update : existing; }); } }
Source:
<code>private int getGaugeValueForTimeLockResource(String gaugeName) { Object value = Optional.ofNullable(metricsManager.getRegistry() .getGauges() <START> .get(new StringJoiner(".").add(TimeLockResource.class.getCanonicalName()) <END> .add(gaugeName) .toString()) .getValue()) .orElseThrow(() -> new IllegalStateException("Gauge with gauge name " + gaugeName + " did not exist.")); return (int) value; }</code><technical_language>Surely String concatenation is cleaner StringJoiner in this instance</technical_language>

Target:
private int getGaugeValueForTimeLockResource(String gaugeName) { Object value = Optional.ofNullable(metricsManager.getRegistry() .getGauges() .get(TimeLockResource.class.getCanonicalName() + "." + gaugeName) .getValue()) .orElseThrow(() -> new IllegalStateException("Gauge with gauge name " + gaugeName + " did not exist.")); return (int) value; }
Source:
<code><START> public CEPOperatorsDropdown getNewOperatorDropdown(String[] operators, <END> SingleFieldConstraint constraint) { return new CEPOperatorsDropdown(operators, constraint); }</code><technical_language>want this ideally package protected</technical_language>

Target:
CEPOperatorsDropdown getNewOperatorDropdown(String[] operators, SingleFieldConstraint constraint) { return new CEPOperatorsDropdown(operators, constraint); }
Source:
<code>private IdentifiedUser(final AccessPath accessPath, final AuthConfig authConfig, final Provider<String> canonicalUrl, final Realm realm, final AccountCache accountCache, final StarredChangesCache starredChangesCache, @Nullable final Provider<SocketAddress> remotePeerProvider, @Nullable final Provider<ReviewDb> dbProvider, final Account.Id id) { super(accessPath, authConfig); this.canonicalUrl = canonicalUrl; this.realm = realm; this.accountCache = accountCache; this.remotePeerProvider = remotePeerProvider; this.dbProvider = dbProvider; this.accountId = id; <START> this.starredChangesCache = starredChangesCache; <END> }</code><technical_language>Style-nit: this.accountCache = accountCache</technical_language>

Target:
private IdentifiedUser(final AccessPath accessPath, final AuthConfig authConfig, final Provider<String> canonicalUrl, final Realm realm, final AccountCache accountCache, final StarredChangesCache starredChangesCache, @Nullable final Provider<SocketAddress> remotePeerProvider, @Nullable final Provider<ReviewDb> dbProvider, final Account.Id id) { super(accessPath, authConfig); this.canonicalUrl = canonicalUrl; this.realm = realm; this.accountCache = accountCache; this.starredChangesCache = starredChangesCache; this.remotePeerProvider = remotePeerProvider; this.dbProvider = dbProvider; this.accountId = id; }
Source:
<code>public void onIdealStateChange(List<IdealState> idealState, NotificationContext changeContext) <START> throws InterruptedException { <END> if (!idealStateInitialized.get()) { logger.info("Received initial notification for IdealState change from {}", dcName); idealStateInitialized.set(true); } else { logger.info("IdealState change triggered from {}", dcName); } logger.debug("Detailed ideal states in are: {}", dcName, idealState); ConcurrentHashMap<String, String> partitionToResourceMap = new ConcurrentHashMap<>(); for (IdealState state : idealState) { String resourceName = state.getResourceName(); state.getPartitionSet().forEach(partitionName -> partitionToResourceMap.put(partitionName, resourceName)); } partitionNameToResource = partitionToResourceMap; helixClusterManagerMetrics.idealStateChangeTriggerCount.inc(); }</code><technical_language>throws InterruptedException removed</technical_language>

Target:
public void onIdealStateChange(List<IdealState> idealState, NotificationContext changeContext) { if (!idealStateInitialized) { logger.info("Received initial notification for IdealState change from {}", dcName); idealStateInitialized = true; } else { logger.info("IdealState change triggered from {}", dcName); } logger.debug("Detailed ideal states in are: {}", dcName, idealState); ConcurrentHashMap<String, String> partitionToResourceMap = new ConcurrentHashMap<>(); for (IdealState state : idealState) { String resourceName = state.getResourceName(); state.getPartitionSet().forEach(partitionName -> partitionToResourceMap.put(partitionName, resourceName)); } partitionNameToResource = partitionToResourceMap; helixClusterManagerMetrics.idealStateChangeTriggerCount.inc(); }
Source:
<code>private static <K, V> V get(LoadingCache<K, V> cache, K key) { try { return cache.getUnchecked(key); } catch (UncheckedExecutionException e) { <START> throwIfUnchecked(e.getCause()); <END> throw e; } }</code><technical_language>I do this a lot, i is right unwrap. <LINK_0></technical_language>

Target:
private static <K, V> V get(LoadingCache<K, V> cache, K key) { try { return cache.getUnchecked(key); } catch (UncheckedExecutionException e) { throwIfInstanceOf(e.getCause(), PrestoException.class); throw e; } }
Source:
<code>private static DefaultCharset initializeDefaultCharsetSingleton() { Charset charset = Charset.defaultCharset(); String declaredCharsetName = System.getProperty(Constants.CLIENT_OPTION_CHARSET); <START> if(declaredCharsetName != null && !declaredCharsetName.isEmpty()) <END> { charset = Charset.forName(declaredCharsetName); } return new DefaultCharset(charset); }</code><technical_language>if ( This in places</technical_language>

Target:
private static DefaultCharset initializeDefaultCharsetSingleton() { Charset charset; final Charset systemDefault = Charset.defaultCharset(); final String declaredCharsetName = System.getProperty(Constants.CLIENT_OPTION_CHARSET); if (declaredCharsetName != null && !declaredCharsetName.isEmpty()) { try { charset = Charset.forName(declaredCharsetName); } catch (Exception ex) { charset = systemDefault; logger.warn("Requested charset '{}' is not available, the default charset '{}' will be used", declaredCharsetName, charset.name()); } } else { logger.info("No desired charset found in system properties, the default charset '{}' will be used", systemDefault.name()); charset = systemDefault; } return new DefaultCharset(charset); }
Source:
<code>protected boolean isEnabled() { <START> return fFormatBlocks; <END> }</code><technical_language>preference is checked in constructor, toggling of checkboxes effect for newly opened editors? Is consistent other checkboxes in formatter preferences</technical_language>

Target:
protected boolean isEnabled() { boolean formatBlocks = false; if (fProject == null) { formatBlocks = DefaultCodeFormatterConstants.TRUE .equals(CCorePlugin.getOption(DefaultCodeFormatterConstants.FORMATTER_COMMENT_BLOCK)); } else { formatBlocks = DefaultCodeFormatterConstants.TRUE .equals(fProject.getOption(DefaultCodeFormatterConstants.FORMATTER_COMMENT_BLOCK, true)); } return formatBlocks; }
Source:
<code>private List<CertifiedProductSearchDetails> getCertifiedProductDetailsForAll( final List<CertifiedProductFlatSearchResult> certifiedProducts) { List<CertifiedProductSearchDetails> details = new ArrayList<CertifiedProductSearchDetails>(); List<Future<CertifiedProductSearchDetails>> futures = new ArrayList<Future<CertifiedProductSearchDetails>>(); for (CertifiedProductFlatSearchResult certifiedProduct : certifiedProducts) { try { futures.add(cpsdAsync.getCertifiedProductDetail(certifiedProduct.getId(), certifiedProductDetailsManager)); } catch (EntityRetrievalException e) { LOGGER.error("Could not retrieve certified product details for id: " + certifiedProduct.getId(), e); } } Date startTime = new Date(); for (Future<CertifiedProductSearchDetails> future : futures) { try { <START> CertifiedProductSearchDetails currDetails = future.get(); <END> details.add(future.get()); } catch (InterruptedException | ExecutionException e) { LOGGER.error("Could not retrieve certified product details for unknown id.", e); } } Date endTime = new Date(); LOGGER.info("Time to retrieve details: " + (endTime.getTime() - startTime.getTime())); return details; }</code><technical_language>currDetails anywhere, right? needed</technical_language>

Target:
private List<CertifiedProductSearchDetails> getCertifiedProductDetailsForAll( final List<CertifiedProductFlatSearchResult> certifiedProducts) { List<CertifiedProductSearchDetails> details = new ArrayList<CertifiedProductSearchDetails>(); List<Future<CertifiedProductSearchDetails>> futures = new ArrayList<Future<CertifiedProductSearchDetails>>(); for (CertifiedProductFlatSearchResult certifiedProduct : certifiedProducts) { try { futures.add(cpsdAsync.getCertifiedProductDetail(certifiedProduct.getId(), certifiedProductDetailsManager)); } catch (EntityRetrievalException e) { LOGGER.error("Could not retrieve certified product details for id: " + certifiedProduct.getId(), e); } } Date startTime = new Date(); for (Future<CertifiedProductSearchDetails> future : futures) { try { details.add(future.get()); } catch (InterruptedException | ExecutionException e) { LOGGER.error("Could not retrieve certified product details for unknown id.", e); } } Date endTime = new Date(); LOGGER.info("Time to retrieve details: " + (endTime.getTime() - startTime.getTime())); return details; }