auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public boolean alreadyHaveOpennetNode(SimpleFieldSet fs) { try { OpennetPeerNode pn = new OpennetPeerNode(fs, node, crypto, this, node.peers, false, crypto.packetMangler); boolean isLong = pn.isLongDistance(); <START> LRUQueue<OpennetPeerNode> peersLRU = isLong ? peersLRULong : peersLRUShort; <END> if(peersLRU.contains(pn)) { if(logMINOR) Logger.minor(this, "Not adding "+pn.userToString()+" to opennet list as already there"); return true; } return false; } catch (Throwable t) { Logger.error(this, "Caught "+t+" parsing opennet node from fieldset", t); return false; } }</code><technical_language>this is idiom repeated I if moving addition LRU based link length a function checks sense</technical_language>

Target:
public boolean alreadyHaveOpennetNode(SimpleFieldSet fs) { try { OpennetPeerNode pn = new OpennetPeerNode(fs, node, crypto, this, node.peers, false, crypto.packetMangler); if(lruQueue(pn).contains(pn)) { if(logMINOR) Logger.minor(this, "Not adding "+pn.userToString()+" to opennet list as already there"); return true; } return false; } catch (Throwable t) { Logger.error(this, "Caught "+t+" parsing opennet node from fieldset", t); return false; } }
Source:
<code>public Map<String, String> machineAttributes() { final Map<String, String> attributes = new HashMap<>(); for (Entry<String, String> entry : labels.entrySet()) { Matcher matcher = MACHINE_ATTRIBUTE_PATTERN.matcher(entry.getKey()); if (matcher.matches()) { <START> String attribute = matcher.group("attribute"); <END> attributes.put(attribute, labels.get(String.format(MACHINE_ATTR_LABEL_FMT, attribute))); } } return attributes; }</code><technical_language>I is serialize/deserialize map instead of single attribute</technical_language>

Target:
public Map<String, String> machineAttributes() { final Map<String, String> attributes = GSON.fromJson(labels.get(LABEL_MACHINE_ATTRIBUTES), mapTypeToken); if (attributes != null) { return attributes; } return new HashMap<>(); }
Source:
<code>private ReplicatedTokenRequestSerializer() { <START> throw new AssertionError(); <END> }</code><technical_language>adding assertion here, a message describing assertion is (class instantiated) is in order</technical_language>

Target:
private ReplicatedTokenRequestSerializer() { throw new AssertionError( "Should not be instantiated" ); }
Source:
<code>private boolean isHostNetworkUnreacable(VDS vds) { VdsDynamic vdsDynamic = vds.getDynamicData(); return (vdsDynamic.getStatus() == VDSStatus.Down || vdsDynamic.getStatus() == VDSStatus.Reboot || vdsDynamic.getStatus() == VDSStatus.Kdumping || vdsDynamic.getStatus() == VDSStatus.NonResponsive || (vdsDynamic.getStatus() == VDSStatus.NonOperational <START> || (vdsDynamic.getStatus() == VDSStatus.PendingApproval <END> && vdsDynamic.getNonOperationalReason() == NonOperationalReason.NETWORK_UNREACHABLE)); }</code><technical_language>Please fix bracketing</technical_language>

Target:
private boolean isHostNetworkUnreacable(VDS vds) { VdsDynamic vdsDynamic = vds.getDynamicData(); return (vdsDynamic.getStatus() == VDSStatus.Down || vdsDynamic.getStatus() == VDSStatus.Reboot || vdsDynamic.getStatus() == VDSStatus.Kdumping || vdsDynamic.getStatus() == VDSStatus.NonResponsive || vdsDynamic.getStatus() == VDSStatus.PendingApproval || (vdsDynamic.getStatus() == VDSStatus.NonOperational && vdsDynamic.getNonOperationalReason() == NonOperationalReason.NETWORK_UNREACHABLE)); }
Source:
<code><START> public void addComparisonToFixtureFor(Class<?>... fixturesFor) { <END> for ( Class<?> fixture : fixturesFor ) { this.fixturesFor.add( fixture ); } }</code><technical_language>I guess rule usage more expressive chaining calls this method instead of passing classes in constructor</technical_language>

Target:
public GeneratedSource addComparisonToFixtureFor(Class<?>... fixturesFor) { for ( Class<?> fixture : fixturesFor ) { this.fixturesFor.add( fixture ); } return this; }
Source:
<code>private static double maximumPortOrLabelWidth(final NodeContext nodeContext, final PortSide portSide) { double maxResult = 0.0; for (PortContext portContext : nodeContext.portContexts.get(portSide)) { if (portContext.portLabelCell != null) { double labelWidth = portContext.portLabelCell.getMinimumWidth(); <START> if (labelWidth > maxResult) { <END> maxResult = labelWidth; } } if (portContext.port.getSize().x > maxResult) { maxResult = portContext.port.getSize().x; } } return maxResult; }</code><technical_language>labelWidth = Math.max(maxResult, labelWidth)</technical_language>

Target:
private static double maximumPortOrLabelWidth(final NodeContext nodeContext, final PortSide portSide) { double maxResult = 0.0; for (PortContext portContext : nodeContext.portContexts.get(portSide)) { if (portContext.portLabelCell != null) { double labelWidth = portContext.portLabelCell.getMinimumWidth(); maxResult = Math.max(maxResult, labelWidth); } maxResult = Math.max(maxResult, portContext.port.getSize().x); } return maxResult; }
Source:
<code>public void visited(RevObject o) { <START> lowestDepthVisited.put(o, Long.valueOf(walk.getTreeDepth())); <END> }</code><technical_language>Stupid question: long/Long? walk.getTreeDepth() returns int, Integer (also in Map, intValue() above)</technical_language>

Target:
public void visited(RevObject o) { lowestDepthVisited.put(o, Integer.valueOf(walk.getTreeDepth())); }
Source:
<code>public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final StreamBatch that = (StreamBatch) o; if (!cursor.equals(that.cursor)) return false; <START> if (events != null ? !events.equals(that.events) : that.events != null) return false; <END> return metadata != null ? metadata.equals(that.metadata) : that.metadata == null; }</code><technical_language>events null</technical_language>

Target:
public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final StreamBatch that = (StreamBatch) o; if (!cursor.equals(that.cursor)) return false; if (!events.equals(that.events)) return false; return metadata != null ? metadata.equals(that.metadata) : that.metadata == null; }
Source:
<code><START> public String getIdentifier() <END> { Preconditions.checkState(args.size() == 1, "LambdaExpr has no or multiple arguments"); return args.get(0).toString(); }</code><technical_language>a "note-to-self" , thanks for explaining</technical_language>

Target:
public String getIdentifier() { Preconditions.checkState(args.size() < 2, "LambdaExpr has multiple arguments"); if (args.size() == 1) { return args.get(0).toString(); } return null; }
Source:
<code>public void onSelectChange(final JQuerySelectPickerEvent event) { final String newValue = event.target.value; <START> if (!newValue.equals(getValue())) { <END> setPickerValue(newValue); presenter.refreshView(newValue); } }</code><technical_language>newValue is null</technical_language>

Target:
public void onSelectChange(final JQuerySelectPickerEvent event) { final String newValue = event.target.value; if (!Objects.equals(newValue, getValue())) { setPickerValue(newValue); presenter.refreshView(newValue); } }
Source:
<code>protected void prepareViewing() { <START> drawRegistration.remove(); <END> clickRegistration.remove(); if(markerRegisration != null) { markerRegisration.remove(); } }</code><technical_language>project open ATM, a null check? field for "view mode" if a populated readonly property is set (I if this is currently V8)</technical_language>

Target:
protected void prepareViewing() { if (drawRegistration != null) { drawRegistration.remove(); drawRegistration = null; } if (clickRegistration != null) { clickRegistration.remove(); clickRegistration = null; } if (markerRegisration != null) { markerRegisration.remove(); markerRegisration = null; } }
Source:
<code>private boolean isWatched(ZooKeeper zooKeeper, String zPath) throws KeeperException, InterruptedException { boolean watched = true; if (znodeExists.contains(zPath)) return watched; Matcher configMatcher = TABLE_SETTING_CONFIG_PATTERN.matcher(zPath); if (configMatcher.matches()) { Stat stat; try { stat = zooKeeper.exists(zPath, false); } catch (KeeperException.BadVersionException | KeeperException.NoNodeException e1) { <START> throw new ConcurrentModificationException(); <END> } if (stat != null) { watched = true; synchronized (znodeExists) { znodeExists.add(zPath); } } else { watched = false; } } return watched; }</code><technical_language>ConcurrentModificationException? concurrent modification is occurring object</technical_language>

Target:
private boolean isWatched(ZooKeeper zooKeeper, String zPath) throws KeeperException, InterruptedException { boolean watched = true; if (znodeExists.contains(zPath)) return watched; Matcher configMatcher = TABLE_SETTING_CONFIG_PATTERN.matcher(zPath); if (configMatcher.matches()) { Stat stat; try { stat = zooKeeper.exists(zPath, false); } catch (KeeperException.BadVersionException | KeeperException.NoNodeException e1) { throw e1; } if (stat != null) { watched = true; synchronized (znodeExists) { znodeExists.add(zPath); } } else { watched = false; } } return watched; }
Source:
<code>private static boolean isWhitelisted(List<Identifier> ids) { StringBuffer sb = new StringBuffer(); <START> for (int i = 0; i < ids.size(); i++) { <END> sb.append(ids.get(i).getValue()); if (i != ids.size() - 1) { sb.append("."); } } switch (sb.toString().toLowerCase(Locale.ROOT)) { case "queueable": case "database.batchable": case "installhandler": return true; default: break; } return false; }</code><technical_language>a more redable for in Java</technical_language>

Target:
private static boolean isWhitelisted(List<Identifier> ids) { String identifier = ids.stream().map(Identifier::getValue).collect(Collectors.joining(".")); switch (identifier.toLowerCase(Locale.ROOT)) { case "queueable": case "database.batchable": case "installhandler": return true; default: break; } return false; }
Source:
<code>public void convertsToJsonWhenUrlAbsent() { <START> final String success = "Living the dream!"; <END> MatcherAssert.assertThat( new Statuses.StatusCreate(Status.State.SUCCESS) .withDescription(success) .withContext(Optional.of(CONTEXT)) .json().toString(), Matchers.equalTo("{\"state\":\"success\",\"description\":\"Living the dream!\",\"context\":\"jcabi/github/test\"}") ); }</code><technical_language>@cvrebert here, pass withDescription a literal</technical_language>

Target:
public void convertsToJsonWhenUrlAbsent() { final String success = "Living the dream!"; MatcherAssert.assertThat( new Statuses.StatusCreate(Status.State.SUCCESS) .withDescription(success) .withContext(Optional.of(StatusesTest.CONTEXT)) .json().toString(), Matchers.equalTo( Json.createObjectBuilder() .add(StatusesTest.STATE_PROP, "success") .add(StatusesTest.DESCRIPTION_PROP, success) .add(StatusesTest.CONTEXT_PROP, StatusesTest.CONTEXT) .build().toString() ) ); }
Source:
<code>public JdbiImmutables registerImmutable(Iterable<Class<?>> specs) { <START> specs.iterator().forEachRemaining(this::registerImmutable); <END> return this; }</code><technical_language>Iterable a forEach IIRC</technical_language>

Target:
public JdbiImmutables registerImmutable(Iterable<Class<?>> specs) { specs.forEach(this::registerImmutable); return this; }
Source:
<code>public boolean validate() { validateListItems(getHost()); validateListItems(getAvailableStorageDomainTypeItems()); validateListItems(getAvailableStorageTypeItems()); getDescription().validateEntity(new IValidation[] { new LengthValidation(BusinessEntitiesDefinitions.GENERAL_MAX_SIZE), new SpecialAsciiI18NOrNoneValidation() }); getComment().validateEntity(new IValidation[] { new SpecialAsciiI18NOrNoneValidation() }); getWarningLowSpaceIndicator().validateEntity(new IValidation[]{ new NotEmptyValidation(), new IntegerValidation(0, StorageConstants.LOW_SPACE_THRESHOLD) }); int maxAllowedSpace = Integer.MAX_VALUE; if (!isNewStorage()) { maxAllowedSpace = getStorage().getTotalDiskSize() == 0 <START> ? Integer.MAX_VALUE : <END> getStorage().getTotalDiskSize(); } getCriticalSpaceActionBlocker().validateEntity(new IValidation[] { new NotEmptyValidation(), new IntegerValidation(0, maxAllowedSpace) }); getWarningLowConfirmedSpaceIndicator().validateEntity(new IValidation[]{ new NotEmptyValidation(), new IntegerValidation(0, StorageConstants.LOW_SPACE_THRESHOLD) }); validateDiscardAfterDelete(); return getName().getIsValid() && getHost().getIsValid() && getIsValid() && getCurrentStorageItem().validate() && getDescription().getIsValid() && getComment().getIsValid() && getWarningLowSpaceIndicator().getIsValid() && getCriticalSpaceActionBlocker().getIsValid() && getWarningLowConfirmedSpaceIndicator().getIsValid() && getDiscardAfterDelete().getIsValid() && getBackup().getIsValid(); }</code><technical_language>"maxAllowedSpace"</technical_language>

Target:
public boolean validate() { validateListItems(getHost()); validateListItems(getAvailableStorageDomainTypeItems()); validateListItems(getAvailableStorageTypeItems()); getDescription().validateEntity(new IValidation[] { new LengthValidation(BusinessEntitiesDefinitions.GENERAL_MAX_SIZE), new SpecialAsciiI18NOrNoneValidation() }); getComment().validateEntity(new IValidation[] { new SpecialAsciiI18NOrNoneValidation() }); getWarningLowSpaceIndicator().validateEntity(new IValidation[]{ new NotEmptyValidation(), new IntegerValidation(0, StorageConstants.LOW_SPACE_THRESHOLD) }); int maxAllowedSpace = Integer.MAX_VALUE; if (!isNewStorage() && getStorage().getTotalDiskSize() != 0 ) { maxAllowedSpace = getStorage().getTotalDiskSize(); } getCriticalSpaceActionBlocker().validateEntity(new IValidation[] { new NotEmptyValidation(), new IntegerValidation(0, maxAllowedSpace) }); getWarningLowConfirmedSpaceIndicator().validateEntity(new IValidation[]{ new NotEmptyValidation(), new IntegerValidation(0, StorageConstants.LOW_SPACE_THRESHOLD) }); validateDiscardAfterDelete(); return getName().getIsValid() && getHost().getIsValid() && getIsValid() && getCurrentStorageItem().validate() && getDescription().getIsValid() && getComment().getIsValid() && getWarningLowSpaceIndicator().getIsValid() && getCriticalSpaceActionBlocker().getIsValid() && getWarningLowConfirmedSpaceIndicator().getIsValid() && getDiscardAfterDelete().getIsValid() && getBackup().getIsValid(); }
Source:
<code>public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == RECORD_AUDIO_PERMISSION_CODE) { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { speechToTextManager.startSpeechToTextFlow(); } else { <START> Toast.makeText(getContext(), R.string.speech_microphone_permission_denied, Toast.LENGTH_LONG).show(); <END> } } }</code><technical_language>nit: UIUtils.showLongToast(). If exist, one</technical_language>

Target:
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { if (requestCode == RECORD_AUDIO_PERMISSION_CODE) { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { speechToTextManager.startSpeechToTextFlow(); } else { UIUtils.showLongToast(R.string.speech_to_text_permission_denied, getContext()); } } }
Source:
<code>public String getUsage() { <START> return "robot explain --input <file> --reasoner <reasoner> --axiom <axiom> <output>"; <END> }</code><technical_language>"robot explain --input <file> --axiom <axiom> --output <output>" Default reasoner is ELK (returned CommandLineHelper.getReasonerFactory(...)) user need that. a note in docs? if link reason docs, reasoners</technical_language>

Target:
public String getUsage() { return "robot explain --input <file> --axiom <axiom> --explanation <output>"; }
Source:
<code>public AbstractRegistry(URL url) { setUrl(url); syncSaveFile = url.getParameter(Constants.REGISTRY_FILESAVE_SYNC_KEY, false); <START> String defaultFile = System.getProperty("user.home") + "/.dubbo/dubbo-registry-" + url.getParameter(Constants.APPLICATION_KEY) + "-" + url.getAddress() + ".cache"; <END> String filename = url.getParameter(Constants.FILE_KEY, defaultFile); File file = null; if (ConfigUtils.isNotEmpty(filename)) { file = new File(filename); if (!file.exists() && file.getParentFile() != null && !file.getParentFile().exists()) { if (!file.getParentFile().mkdirs()) { throw new IllegalArgumentException( String.format( "Invalid registry store file %s, cause: Failed to create directory %s!", file, file.getParentFile() ) ); } } } this.file = file; loadProperties(); notify(url.getBackupUrls()); }</code><technical_language>refactor this extrating another method e.g. String fileName= getFileKey(url); private static String getFileKey(URL url) { String defaultFile = System.getProperty("user.home") + "/.dubbo/dubbo-registry-" + url.getParameter(Constants.APPLICATION_KEY) + "-" + url.getAddress() + ".cache"; return url.getParameter(Constants.FILE_KEY, defaultFile); } Do feel increase readability of code</technical_language>

Target:
public AbstractRegistry(URL url) { setUrl(url); syncSaveFile = url.getParameter(Constants.REGISTRY_FILESAVE_SYNC_KEY, false); String filename = getFileKey(url); File file = null; if (ConfigUtils.isNotEmpty(filename)) { file = new File(filename); if (!file.exists() && file.getParentFile() != null && !file.getParentFile().exists()) { if (!file.getParentFile().mkdirs()) { throw new IllegalArgumentException("Invalid registry cache file " + file + ", cause: Failed to create directory " + file.getParentFile() + "!"); } } } this.file = file; loadProperties(); notify(url.getBackupUrls()); }
Source:
<code>public void shouldAlwaysGenerateTheSameValueForTheSameSeed() { <START> IntegerRangeRandomizer bntegerRangeRandomizer = aNewIntegerRangeRandomizer(min, max, SEED); <END> Integer i = bntegerRangeRandomizer.getRandomValue(); then(i).isEqualTo(7); }</code><technical_language>typo here: bntegerRangeRandomizer -> integerRangeRandomizer</technical_language>

Target:
public void shouldAlwaysGenerateTheSameValueForTheSameSeed() { IntegerRangeRandomizer integerRangeRandomizer = aNewIntegerRangeRandomizer(min, max, SEED); Integer i = integerRangeRandomizer.getRandomValue(); then(i).isEqualTo(7); }
Source:
<code>public Centre[] getCentres(String branchId, String offset, String limit) throws MambuApiException { String urlString = new String(mambuAPIService.createUrl(APIData.CENTRES)); <START> String jsonResponse; <END> ParamsMap params = new ParamsMap(); params.addParam(APIData.BRANCH_ID, branchId); params.put(OFFSET, offset); params.put(LIMIT, limit); jsonResponse = mambuAPIService.executeRequest(urlString, params, Method.GET); Centre centres[] = (Centre[]) GsonUtils.createGson().fromJson(jsonResponse, Centre[].class); return centres; }</code><technical_language>This variable is needed here</technical_language>

Target:
public Centre[] getCentres(String branchId, String offset, String limit) throws MambuApiException { String urlString = new String(mambuAPIService.createUrl(APIData.CENTRES)); ParamsMap params = new ParamsMap(); params.addParam(APIData.BRANCH_ID, branchId); params.put(OFFSET, offset); params.put(LIMIT, limit); String jsonResponse = mambuAPIService.executeRequest(urlString, params, Method.GET); Centre centres[] = (Centre[]) GsonUtils.createGson().fromJson(jsonResponse, Centre[].class); return centres; }
Source:
<code><START> protected List<Map<String, Object>> getEntitiesFromResultSet( <END> ResultSet resultSet) throws SQLException { ArrayList<Map<String, Object>> entities = new ArrayList<>(); while (resultSet.next()) { entities.add(getEntityFromResultSet(resultSet)); } return entities; }</code><technical_language>this a static method</technical_language>

Target:
protected static List<Map<String, Object>> getEntitiesFromResultSet( ResultSet resultSet) throws SQLException { ArrayList<Map<String, Object>> entities = new ArrayList<>(); while (resultSet.next()) { entities.add(getEntityFromResultSet(resultSet)); } return entities; }
Source:
<code>public List<SongMetadata> list() { <START> String[] proj = { MediaStore.Audio.Media._ID, <END> MediaStore.Audio.Media.ALBUM, MediaStore.Audio.Media.ARTIST, MediaStore.Audio.Media.TITLE}; Cursor cursor = this.activity.getContentResolver().query( MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, proj, null, null, null); List<SongMetadata> metadataList = new ArrayList<SongMetadata>(); cursor.moveToFirst(); while (!cursor.isAfterLast()) { SongMetadata metadata = new SongMetadata(); metadata.setId(cursor.getLong(0)); metadata.setAlbum(cursor.getString(1)); metadata.setArtist(cursor.getString(2)); metadata.setTitle(cursor.getString(3)); metadataList.add(metadata); cursor.moveToNext(); } cursor.close(); return metadataList; }</code><technical_language>Lets clean this list. { MediaStore.Audio.Media._ID, MediaStore.Audio.Media.ALBUM, MediaStore.Audio.Media.ARTIST, MediaStore.Audio.Media.TITLE };</technical_language>

Target:
public List<SongMetadata> list() { String[] proj = {ID, ALBUM, ARTIST, TITLE}; Cursor cursor = this.activity.getContentResolver().query(EC_URI, proj, null, null, null); List<SongMetadata> metadataList = new ArrayList<SongMetadata>(); cursor.moveToFirst(); while (!cursor.isAfterLast()) { SongMetadata metadata = new SongMetadata(); metadata.setId(cursor.getLong(cursor.getColumnIndex(ID))); metadata.setAlbum(cursor.getString(cursor.getColumnIndex(ALBUM))); metadata.setArtist(cursor.getString(cursor.getColumnIndex(ARTIST))); metadata.setTitle(cursor.getString(cursor.getColumnIndex(TITLE))); metadataList.add(metadata); cursor.moveToNext(); } cursor.close(); return metadataList; }
Source:
<code>public Sequence<T> run(final Query<T> query, final Map<String, Object> context) { final List<Sequence<T>> listOfSequences = Lists.newArrayList(); final Sequence<T> returningSeq = baseRunner.run(query, context); listOfSequences.add(returningSeq); return new YieldingSequenceBase<T>() { @Override public <OutType> Yielder<OutType> toYielder( OutType initValue, YieldingAccumulator<OutType, T> accumulator ) { final List<SegmentDescriptor> missingSegments = getMissingSegments(context); if (missingSegments.isEmpty()) { <START> return returningSeq.toYielder(initValue, accumulator); <END> } for (int i = 0; i < config.numTries(); i++) { log.info("[%,d] missing segments found. Retry attempt [%,d]", missingSegments.size(), i); context.put(MISSING_SEGMENTS_KEY, Lists.newArrayList()); final Query<T> retryQuery = query.withQuerySegmentSpec( new MultipleSpecificSegmentSpec( missingSegments ) ); Sequence<T> retrySequence = baseRunner.run(retryQuery, context); listOfSequences.add(retrySequence); if (getMissingSegments(context).isEmpty()) { break; } } final List<SegmentDescriptor> finalMissingSegs = getMissingSegments(context); if (!config.returnPartialResults() && !finalMissingSegs.isEmpty()) { throw new SegmentMissingException("No results found for segments[%s]", finalMissingSegs); } return toolChest.mergeSequencesUnordered(Sequences.simple(listOfSequences)).toYielder(initValue, accumulator); } }; }</code><technical_language>remove this line skip return end of function, remove returningSeq variable for clarity</technical_language>

Target:
public Sequence<T> run(final Query<T> query, final Map<String, Object> context) { final List<Sequence<T>> listOfSequences = Lists.newArrayList(); listOfSequences.add(baseRunner.run(query, context)); return new YieldingSequenceBase<T>() { @Override public <OutType> Yielder<OutType> toYielder( OutType initValue, YieldingAccumulator<OutType, T> accumulator ) { final List<SegmentDescriptor> missingSegments = getMissingSegments(context); if (!missingSegments.isEmpty()) { for (int i = 0; i < config.numTries(); i++) { log.info("[%,d] missing segments found. Retry attempt [%,d]", missingSegments.size(), i); context.put(MISSING_SEGMENTS_KEY, Lists.newArrayList()); final Query<T> retryQuery = query.withQuerySegmentSpec( new MultipleSpecificSegmentSpec( missingSegments ) ); Sequence<T> retrySequence = baseRunner.run(retryQuery, context); listOfSequences.add(retrySequence); if (getMissingSegments(context).isEmpty()) { break; } } final List<SegmentDescriptor> finalMissingSegs = getMissingSegments(context); if (!finalMissingSegs.isEmpty()) { throw new SegmentMissingException("No results found for segments[%s]", finalMissingSegs); } } return toolChest.mergeSequencesUnordered(Sequences.simple(listOfSequences)).toYielder(initValue, accumulator); } }; }
Source:
<code>public synchronized boolean setWifiEnabled(String packageName, boolean enable) throws RemoteException { enforceChangePermission(); Slog.d(TAG, "setWifiEnabled: " + enable + " pid=" + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()); <START> mLog.trace("setWifiEnabled uid=%").c(Binder.getCallingUid()).flush(); <END> long ident = Binder.clearCallingIdentity(); try { if (! mSettingsStore.handleWifiToggled(enable)) { return true; } } finally { Binder.restoreCallingIdentity(ident); } if (mPermissionReviewRequired) { final int wiFiEnabledState = getWifiEnabledState(); if (enable) { if (wiFiEnabledState == WifiManager.WIFI_STATE_DISABLING || wiFiEnabledState == WifiManager.WIFI_STATE_DISABLED) { if (startConsentUiIfNeeded(packageName, Binder.getCallingUid(), WifiManager.ACTION_REQUEST_ENABLE)) { return true; } } } else if (wiFiEnabledState == WifiManager.WIFI_STATE_ENABLING || wiFiEnabledState == WifiManager.WIFI_STATE_ENABLED) { if (startConsentUiIfNeeded(packageName, Binder.getCallingUid(), WifiManager.ACTION_REQUEST_DISABLE)) { return true; } } } mWifiController.sendMessage(CMD_WIFI_TOGGLED); return true; }</code><technical_language>log if wanted enabled disabled</technical_language>

Target:
public synchronized boolean setWifiEnabled(String packageName, boolean enable) throws RemoteException { enforceChangePermission(); Slog.d(TAG, "setWifiEnabled: " + enable + " pid=" + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()); mLog.trace("setWifiEnabled uid=% enable=%") .c(Binder.getCallingUid()) .c(enable ? "true" : "false").flush(); long ident = Binder.clearCallingIdentity(); try { if (! mSettingsStore.handleWifiToggled(enable)) { return true; } } finally { Binder.restoreCallingIdentity(ident); } if (mPermissionReviewRequired) { final int wiFiEnabledState = getWifiEnabledState(); if (enable) { if (wiFiEnabledState == WifiManager.WIFI_STATE_DISABLING || wiFiEnabledState == WifiManager.WIFI_STATE_DISABLED) { if (startConsentUiIfNeeded(packageName, Binder.getCallingUid(), WifiManager.ACTION_REQUEST_ENABLE)) { return true; } } } else if (wiFiEnabledState == WifiManager.WIFI_STATE_ENABLING || wiFiEnabledState == WifiManager.WIFI_STATE_ENABLED) { if (startConsentUiIfNeeded(packageName, Binder.getCallingUid(), WifiManager.ACTION_REQUEST_DISABLE)) { return true; } } } mWifiController.sendMessage(CMD_WIFI_TOGGLED); return true; }
Source:
<code>public void setup(ManagementClient managementClient, String containerId) throws Exception { ModelNode node = new ModelNode(); node.get(ADDRESS).set(PathAddress.parseCLIStyleAddress("/subsystem=ejb3").toModelNode()); node.get(OP).set(WRITE_ATTRIBUTE_OPERATION); node.get(NAME).set(EJB3SubsystemModel.ALLOW_EJB_NAME_REGEX); node.get(VALUE).set(true); <START> managementClient.getControllerClient().execute(node); <END> }</code><technical_language>add assertTrue result of this operation ..</technical_language>

Target:
public void setup(ManagementClient managementClient, String containerId) throws Exception { ModelNode node = new ModelNode(); node.get(ADDRESS).set(PathAddress.parseCLIStyleAddress("/subsystem=ejb3").toModelNode()); node.get(OP).set(WRITE_ATTRIBUTE_OPERATION); node.get(NAME).set(EJB3SubsystemModel.ALLOW_EJB_NAME_REGEX); node.get(VALUE).set(true); final ModelNode result = managementClient.getControllerClient().execute(node); if (!Operations.isSuccessfulOutcome(result)) { Assert.fail(Operations.getFailureDescription(result).asString()); } }
Source:
<code>public void clientCallback(ClientResponse response) throws Exception { m_responses[m_index] = new ClientResponseWithPartitionKey(m_partitionKey, response); <START> m_partitionCounter.decrementAndGet(); <END> if (m_partitionCounter.get() == 0) { m_cb.clientCallback(m_responses); } }</code><technical_language>combine this line next one</technical_language>

Target:
public void clientCallback(ClientResponse response) throws Exception { m_responses[m_index] = new ClientResponseWithPartitionKey(m_partitionKey, response); if (m_partitionCounter.decrementAndGet() == 0) { m_cb.clientCallback(m_responses); } }
Source:
<code>public static void deleteRecursively(File file) throws IOException { if (file.isDirectory()) { File[] children = file.listFiles(); if (children != null) { for (File child : children) { deleteRecursively(child); } } } <START> <END> for (int n = 0; n < 10; n++) { try { Files.delete(file.toPath()); } catch (DirectoryNotEmptyException dnee) { Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS); continue; } catch (AccessDeniedException ade) { Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS); continue; } catch (NoSuchFileException nse) { if (n == 0) throw nse; return; } return; } throw new RuntimeException("Could not delete: " + file.toPath()); }</code><technical_language>@zack-shoylev Do underlying issue is here? Waiting for locks released, or..</technical_language>

Target:
public static void deleteRecursively(File file) throws IOException { if (file.isDirectory()) { File[] children = file.listFiles(); if (children != null) { for (File child : children) { deleteRecursively(child); } } } delete(file); }
Source:
<code>public AnsibleReturnCode runCommand(AnsibleCommandBuilder command, int timeout) throws IOException, InterruptedException { log.trace("Enter AnsibleExecutor::runCommand"); if (Files.notExists(Paths.get(command.playbook()))) { <START> log.warn("Playbook '{}' does not exists. Ensure ovirt-ansible-roles is installed.", command.playbook()); <END> return AnsibleReturnCode.ERROR; } Path inventoryFile = null; AnsibleReturnCode returnCode = AnsibleReturnCode.UNEXPECTED_ERROR; try { inventoryFile = createInventoryFile(command); log.info("Executing Ansible command: {}", command); List<String> ansibleCommand = command.build(); File logFile = command.logFile(); ProcessBuilder ansibleProcessBuilder = new ProcessBuilder() .redirectErrorStream(true) .redirectOutput(logFile) .command(ansibleCommand) .directory(command.playbookDir().toFile()); ansibleProcessBuilder.environment() .put("ANSIBLE_CONFIG", Paths.get(command.playbookDir().toString(), "ansible.cfg").toString()); Process ansibleProcess = ansibleProcessBuilder.start(); ansibleProcess.waitFor(timeout, TimeUnit.MINUTES); returnCode = AnsibleReturnCode.values()[ansibleProcess.exitValue()]; ansibleProcess.destroy(); } finally { log.info("Ansible playbook command has exited with value: {}", returnCode); removeFile(inventoryFile); } log.trace("Exit AnsibleExecutor::runCommand"); return returnCode; }</code><technical_language>rephrase: Playbook '{}' exist, please ensure ovirt-ansible-roles package is properly installed</technical_language>

Target:
public AnsibleReturnCode runCommand(AnsibleCommandBuilder command, int timeout) throws IOException, InterruptedException { log.trace("Enter AnsibleExecutor::runCommand"); if (Files.notExists(Paths.get(command.playbook()))) { log.warn( "Playbook '{}' does not exist, please ensure that ovirt-ansible-roles package is properly installed.", command.playbook() ); return AnsibleReturnCode.ERROR; } Path inventoryFile = null; AnsibleReturnCode returnCode = AnsibleReturnCode.UNEXPECTED_ERROR; try { inventoryFile = createInventoryFile(command); log.info("Executing Ansible command: {}", command); List<String> ansibleCommand = command.build(); File logFile = command.logFile(); ProcessBuilder ansibleProcessBuilder = new ProcessBuilder() .redirectErrorStream(true) .redirectOutput(logFile) .command(ansibleCommand) .directory(command.playbookDir().toFile()); ansibleProcessBuilder.environment() .put("ANSIBLE_CONFIG", Paths.get(command.playbookDir().toString(), "ansible.cfg").toString()); Process ansibleProcess = ansibleProcessBuilder.start(); ansibleProcess.waitFor(timeout, TimeUnit.MINUTES); returnCode = AnsibleReturnCode.values()[ansibleProcess.exitValue()]; ansibleProcess.destroy(); } finally { log.info("Ansible playbook command has exited with value: {}", returnCode); removeFile(inventoryFile); } log.trace("Exit AnsibleExecutor::runCommand"); return returnCode; }
Source:
<code>public List<TurboUser> getUsersOfRepo(String repoId) { Optional<Model> model = getModelById(repoId); if (model.isPresent()) { return model.get().getUsers(); } else { return new ArrayList<>(); <START> } <END> }</code><technical_language>if this done in line. ... ? ... : ..</technical_language>

Target:
public List<TurboUser> getUsersOfRepo(String repoId) { Optional<Model> model = getModelById(repoId); return model.isPresent() ? model.get().getUsers() : new ArrayList<>(); }
Source:
<code>private AdvancedCache<?, ?> lookupIndexedCache(RestRequest request, NettyRestResponse.Builder builder) { String cacheName = request.variables().get("cacheName"); AdvancedCache<?, ?> cache = invocationHelper.getRestCacheManager().getCache(cacheName, request); if (cache == null) { builder.status(HttpResponseStatus.NOT_FOUND.code()); return null; } Configuration cacheConfiguration = cache.getCacheConfiguration(); if (!cacheConfiguration.indexing().isEnabled()) { <START> builder.entity("cache is not indexed").status(BAD_REQUEST.code()).build(); <END> } return cache; }</code><technical_language>build() call is necessary</technical_language>

Target:
private AdvancedCache<?, ?> lookupIndexedCache(RestRequest request, NettyRestResponse.Builder builder) { String cacheName = request.variables().get("cacheName"); AdvancedCache<?, ?> cache = invocationHelper.getRestCacheManager().getCache(cacheName, request); if (cache == null) { builder.status(HttpResponseStatus.NOT_FOUND.code()); return null; } Configuration cacheConfiguration = cache.getCacheConfiguration(); if (!cacheConfiguration.indexing().enabled()) { builder.entity("cache is not indexed").status(BAD_REQUEST.code()).build(); } return cache; }
Source:
<code>private static Date timeToUTC(Date date) { SimpleDateFormat dateFormatGmt = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss"); dateFormatGmt.setTimeZone(TimeZone.getTimeZone("GMT")); SimpleDateFormat dateFormatLocal = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss"); try { date = dateFormatLocal.parse(dateFormatGmt.format(date)); } catch (ParseException e) { DAO.severe(e); <START> date = new Date(); <END> } return date; }</code><technical_language>codacy issue is reassigned this object here. This check ensures do accidentally modify object in a function. a new variable newDate fix issue</technical_language>

Target:
private static Date timeToUTC(Date date) { Date dateUtc; SimpleDateFormat dateFormatGmt = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss"); dateFormatGmt.setTimeZone(TimeZone.getTimeZone("GMT")); SimpleDateFormat dateFormatLocal = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss"); try { dateUtc = dateFormatLocal.parse(dateFormatGmt.format(date)); } catch (ParseException e) { DAO.severe(e); dateUtc = new Date(); } return dateUtc; }
Source:
<code><START> public Builder schemaVersion(long schemaVersion, RealmMigration migration) { <END> if (schemaVersion < 0) { throw new IllegalArgumentException("Realm schema version numbers must be 0 (zero) or higher. Yours was: " + schemaVersion); } if (migration == null) { throw new IllegalArgumentException("Migration cannot be null"); } this.schemaVersion = schemaVersion; this.migration = migration; return this; }</code><technical_language>consider alternatives this name? schema(long schemaVersion, RealmMigration migration) more accurate? sure. sense making "schemaVersion" primary concept migration a result of that</technical_language>

Target:
public Builder schemaVersion(long schemaVersion, RealmMigration migration) { schemaVersion(schemaVersion); if (migration == null) { throw new IllegalArgumentException("Migration cannot be null"); } this.migration = migration; return this; }
Source:
<code>public RemoteConnection(LinkedHashMap<String, Object> connectionParams) throws IOException { host = (String) connectionParams.get("host"); try{ port = (Integer) connectionParams.get("port"); } catch(ClassCastException e) { port = Integer.parseInt((String) connectionParams.get("port")); } user = (String) connectionParams.get("user"); password = (String) connectionParams.get("password"); jmx_url = (String) connectionParams.get("jmx_url"); if (connectionParams.containsKey("path")){ path = (String) connectionParams.get("path"); } env = getEnv(connectionParams); address = getAddress(connectionParams); String trustStorePath; String trustStorePassword; if (connectionParams.containsKey(TRUST_STORE_PATH_KEY) && connectionParams.containsKey(TRUST_STORE_PASSWORD_KEY)) { trustStorePath = (String) connectionParams.get(TRUST_STORE_PATH_KEY); trustStorePassword = (String) connectionParams.get(TRUST_STORE_PASSWORD_KEY); if (trustStorePath != null && trustStorePassword != null) { System.setProperty("javax.net.ssl.trustStore", trustStorePath); System.setProperty("javax.net.ssl.trustStorePassword", trustStorePassword); LOGGER.info("Setting trustStore path: " + trustStorePath + " and trustStorePassword"); } } <START> System.setProperty("sun.rmi.transport.tcp.responseTimeout", DEFAULT_RMI_RESPONSE_TIMEOUT); <END> createConnection(); }</code><technical_language>reach timeout? Do catch handle exception raised correctly</technical_language>

Target:
public RemoteConnection(LinkedHashMap<String, Object> connectionParams) throws IOException { host = (String) connectionParams.get("host"); try{ port = (Integer) connectionParams.get("port"); } catch(ClassCastException e) { port = Integer.parseInt((String) connectionParams.get("port")); } user = (String) connectionParams.get("user"); password = (String) connectionParams.get("password"); jmx_url = (String) connectionParams.get("jmx_url"); rmi_timeout = (String) connectionParams.get("rmi_client_timeout"); if (rmi_timeout == null) { rmi_timeout = DEFAULT_RMI_RESPONSE_TIMEOUT; } if (connectionParams.containsKey("path")){ path = (String) connectionParams.get("path"); } env = getEnv(connectionParams); address = getAddress(connectionParams); String trustStorePath; String trustStorePassword; if (connectionParams.containsKey(TRUST_STORE_PATH_KEY) && connectionParams.containsKey(TRUST_STORE_PASSWORD_KEY)) { trustStorePath = (String) connectionParams.get(TRUST_STORE_PATH_KEY); trustStorePassword = (String) connectionParams.get(TRUST_STORE_PASSWORD_KEY); if (trustStorePath != null && trustStorePassword != null) { System.setProperty("javax.net.ssl.trustStore", trustStorePath); System.setProperty("javax.net.ssl.trustStorePassword", trustStorePassword); LOGGER.info("Setting trustStore path: " + trustStorePath + " and trustStorePassword"); } } System.setProperty("sun.rmi.transport.tcp.responseTimeout", rmi_timeout); createConnection(); }
Source:
<code>protected void executeCommand() { final VDS vds = getVds(); <START> try (EngineLock monitoringLock = acquireMonitorLock("Activate")) { <END> ExecutionHandler.updateSpecificActionJobCompleted(vds.getId(), VdcActionType.MaintenanceVds, false); setSucceeded(setVdsStatus(VDSStatus.Unassigned).getSucceeded()); if (getSucceeded()) { TransactionSupport.executeInNewTransaction(() -> { List<Network> networks = getNetworkDao().getAllForCluster(vds.getClusterId()); for (Network net : networks) { NetworkClusterHelper.setStatus(vds.getClusterId(), net); } return null; }); if (vds.getHighlyAvailableIsConfigured()) { SetHaMaintenanceModeVDSCommandParameters param = new SetHaMaintenanceModeVDSCommandParameters(vds, HaMaintenanceMode.LOCAL, false); if (!runVdsCommand(VDSCommandType.SetHaMaintenanceMode, param).getSucceeded()) { haMaintenanceFailed = true; } } if (vds.getClusterSupportsGlusterService()) { runVdsCommand(VDSCommandType.ManageGlusterService, new GlusterServiceVDSParameters(vds.getId(), Arrays.asList("glusterd"), "restart")); } } } }</code><technical_language>"Activate host" :-)</technical_language>

Target:
protected void executeCommand() { final VDS vds = getVds(); try (EngineLock monitoringLock = acquireMonitorLock("Activate host")) { ExecutionHandler.updateSpecificActionJobCompleted(vds.getId(), VdcActionType.MaintenanceVds, false); setSucceeded(setVdsStatus(VDSStatus.Unassigned).getSucceeded()); if (getSucceeded()) { TransactionSupport.executeInNewTransaction(() -> { List<Network> networks = getNetworkDao().getAllForCluster(vds.getClusterId()); for (Network net : networks) { NetworkClusterHelper.setStatus(vds.getClusterId(), net); } return null; }); if (vds.getHighlyAvailableIsConfigured()) { SetHaMaintenanceModeVDSCommandParameters param = new SetHaMaintenanceModeVDSCommandParameters(vds, HaMaintenanceMode.LOCAL, false); if (!runVdsCommand(VDSCommandType.SetHaMaintenanceMode, param).getSucceeded()) { haMaintenanceFailed = true; } } if (vds.getClusterSupportsGlusterService()) { runVdsCommand(VDSCommandType.ManageGlusterService, new GlusterServiceVDSParameters(vds.getId(), Arrays.asList("glusterd"), "restart")); } } } }
Source:
<code>public QRCodeTabsActivityPage clickConfigureQRWithAdminPassword(String password) { clickOnString(R.string.configure_via_qr_code); <START> inputText("blah"); <END> clickOKOnDialog(); return new QRCodeTabsActivityPage(rule).assertOnPage(); }</code><technical_language>password</technical_language>

Target:
public QRCodeTabsActivityPage clickConfigureQRWithAdminPassword(String password) { clickOnString(R.string.configure_via_qr_code); inputText(password); clickOKOnDialog(); return new QRCodeTabsActivityPage(rule).assertOnPage(); }
Source:
<code>public void clusteredCacheManagerExample() throws Exception { final CacheManagerBuilder<PersistentCacheManager> clusteredCacheManagerBuilder = CacheManagerBuilder.newCacheManagerBuilder() <START> .with(ClusteringServiceConfigurationBuilder.cluster(URI.create("<LINK_0>"))); END> final PersistentCacheManager cacheManager = clusteredCacheManagerBuilder.build(true); cacheManager.close(); }</code><technical_language>updated port is good - hostname localhost well</technical_language>

Target:
public void clusteredCacheManagerExample() throws Exception { final CacheManagerBuilder<PersistentCacheManager> clusteredCacheManagerBuilder = CacheManagerBuilder.newCacheManagerBuilder() .with(ClusteringServiceConfigurationBuilder.cluster(URI.create("http://localhost:9510/my-application?auto-create"))); final PersistentCacheManager cacheManager = clusteredCacheManagerBuilder.build(true); cacheManager.close(); }
Source:
<code>public TaskResult runTask() { try (TDOperator op = TDOperator.fromConfig(params)) { TDJobOperator job = op.runJob(state, POLL_JOB, this::startJob); <START> state.remove(POLL_JOB); <END> logger.debug("fetching poll job result: {}", job.getJobId()); boolean done = fetchJobResult(job); if (!done) { state.remove(JOB_ID); throw TaskExecutionException.ofNextPolling(pollInterval, ConfigElement.copyOf(state)); } return TaskResult.empty(request); } }</code><technical_language>do remove this state? safer left runJob() avoid re-run unexpected retry occurs</technical_language>

Target:
public TaskResult runTask() { try (TDOperator op = TDOperator.fromConfig(params)) { TDJobOperator job = op.runJob(state, POLL_JOB, this::startJob); state.remove(POLL_JOB); logger.debug("fetching poll job result: {}", job.getJobId()); boolean done = fetchJobResult(job); if (!done) { throw TaskExecutionException.ofNextPolling(pollInterval, ConfigElement.copyOf(state)); } return TaskResult.empty(request); } }
Source:
<code>protected View onCreateAnswerView(Context context, FormEntryPrompt prompt, int answerFontSize) { binding = BearingWidgetAnswerBinding.inflate(((Activity) context).getLayoutInflater()); if (prompt.isReadOnly()) { binding.bearingButton.setVisibility(GONE); } else { binding.bearingButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, answerFontSize); binding.bearingButton.setOnClickListener(v -> onButtonClick()); } binding.answerText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, answerFontSize); return binding.getRoot(); <START> } <END></code><technical_language>is wrong button text. set default set R.string.replace_bearing record bearing (only if create widget scratch is answer)</technical_language>

Target:
protected View onCreateAnswerView(Context context, FormEntryPrompt prompt, int answerFontSize) { binding = BearingWidgetAnswerBinding.inflate(((Activity) context).getLayoutInflater()); if (prompt.isReadOnly()) { binding.bearingButton.setVisibility(GONE); } else { binding.bearingButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, answerFontSize); binding.bearingButton.setOnClickListener(v -> onButtonClick()); } binding.answerText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, answerFontSize); binding.answerText.setBackground(null); String answerText = prompt.getAnswerText(); if (answerText != null && !answerText.isEmpty()) { binding.bearingButton.setText(getContext().getString(R.string.replace_bearing)); binding.answerText.setText(answerText); } return binding.getRoot(); }
Source:
<code><START> public final Parcelable.Creator<?> readParcelableCreator(ClassLoader loader) throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException { <END> final String name = realObject.readString(); if (name == null) return null; ClassLoader parcelableClassLoader = (loader == null ? getClass().getClassLoader() : loader); Class<?> parcelableClass = Class.forName(name, false , parcelableClassLoader); Field field = parcelableClass.getField("CREATOR"); field.setAccessible(true); return (Parcelable.Creator<?>) field.get(null ); }</code><technical_language>Remove final</technical_language>

Target:
public Parcelable.Creator<?> readParcelableCreator(ClassLoader loader) throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException { final String name = realObject.readString(); if (name == null) return null; ClassLoader parcelableClassLoader = (loader == null ? getClass().getClassLoader() : loader); Class<?> parcelableClass = Class.forName(name, false , parcelableClassLoader); Field field = parcelableClass.getField("CREATOR"); field.setAccessible(true); return (Parcelable.Creator<?>) field.get(null ); }
Source:
<code>default CompletableFuture<Map<K, V>> getAllAsync(Collection<K> keys) { <START> Map<CompletableFuture<V>, K> getFutures = keys.stream() <END> .collect(Collectors.toMap(k -> getAsync(k), Function.identity())); return CompletableFuture.allOf( Iterables.toArray(getFutures.keySet(), CompletableFuture.class)) .thenApply(future -> getFutures.keySet().stream() .collect(Collectors.toMap(f -> getFutures.get(f), f -> f.join()))); }</code><technical_language>I if Pair cleaner here</technical_language>

Target:
default CompletableFuture<Map<K, V>> getAllAsync(Collection<K> keys) { Map<K, CompletableFuture<V>> getFutures = keys.stream().collect( Collectors.toMap(k -> k, k -> getAsync(k))); return CompletableFuture.allOf( Iterables.toArray(getFutures.values(), CompletableFuture.class)) .thenApply(future -> getFutures.entrySet() .stream() .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue().join()))); }