auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public StepDefinitionMatch stepDefinitionMatch(String featurePath, PickleStep step) { String stepText = step.getText(); CacheEntry cacheEntry = matchedStepDefinitionsCache.get(stepText); if (cacheEntry != null) { return new StepDefinitionMatch(cacheEntry.arguments, cacheEntry.stepDefinition, featurePath, step, localizedXStreams); } List<StepDefinitionMatch> matches = stepDefinitionMatches(featurePath, step); if (matches.isEmpty()) { return null; } if (matches.size() == 1) { StepDefinitionMatch match = matches.get(0); matchedStepDefinitionsCache.put(stepText, new CacheEntry(match.getStepDefinition(),match.getArguments())); return match; } else { throw new AmbiguousStepDefinitionsException(step, matches); } }

Target:
public StepDefinitionMatch stepDefinitionMatch(String featurePath, PickleStep step) { String stepText = step.getText(); CacheEntry cacheEntry = matchedStepDefinitionsCache.get(stepText); if (cacheEntry != null) { return new StepDefinitionMatch(cacheEntry.arguments, cacheEntry.stepDefinition, featurePath, step, localizedXStreams); } List<StepDefinitionMatch> matches = stepDefinitionMatches(featurePath, step); if (matches.isEmpty()) { return null; } if (matches.size() == 1) { StepDefinitionMatch match = matches.get(0); matchedStepDefinitionsCache.put(stepText, new CacheEntry(match.getStepDefinition(), match.getArguments())); return match; } throw new AmbiguousStepDefinitionsException(step, matches); }
Source:
public VdsIdVDSCommandBase(P parameters) { this(parameters, true); }

Target:
public VdsIdVDSCommandBase(P parameters) { this(parameters, false); }
Source:
private void addIndex(Label label, Index index) { if ( index != null ) { if ( index.getName() != null ) { log.cannotSetNameForIndex( index.getName() ); if ( log.isEnabled( Level.WARN ) ) { log.warnf( "Neo4j does not support named indexes. Property name='%1$s' is ignored!", index.getName() ); } } List<String> properties = CollectionHelper.toStream( index.getColumnIterator() ) .map( Column::getName ).collect( Collectors.toList() ); indexSpecs.add( new Neo4jIndexSpec( label, properties ) ); } }

Target:
private void addIndex(Label label, Index index) { if ( index != null ) { if ( index.getName() != null ) { log.cannotSetNameForIndex( index.getName() ); } List<String> properties = CollectionHelper.toStream( index.getColumnIterator() ) .map( Column::getName ).collect( Collectors.toList() ); indexSpecs.add( new Neo4jIndexSpec( label, properties ) ); } }
Source:
private void addOpenEditorTasks(HashSet<ITask> relevantTasks) { IWorkbenchWindow[] workbenchWindows = PlatformUI.getWorkbench().getWorkbenchWindows(); for (IWorkbenchWindow workbenchWindow : workbenchWindows) { IWorkbenchPage[] workbenchPages = workbenchWindow.getPages(); for (IWorkbenchPage workbenchPage : workbenchPages) { IEditorReference[] editorReferences = workbenchPage.getEditorReferences(); for (IEditorReference editorReference : editorReferences) { IEditorPart editorPart = editorReference.getEditor(false); if (editorPart instanceof TaskEditor) { TaskEditorInput taskEditorInput = ((TaskEditor) editorPart).getTaskEditorInput(); if (taskEditorInput.exists()) { relevantTasks.add(taskEditorInput.getTask()); } } } } } }

Target:
private void addOpenEditorTasks(HashSet<ITask> relevantTasks) { IWorkbenchWindow[] workbenchWindows = PlatformUI.getWorkbench().getWorkbenchWindows(); for (IWorkbenchWindow workbenchWindow : workbenchWindows) { IWorkbenchPage[] workbenchPages = workbenchWindow.getPages(); for (IWorkbenchPage workbenchPage : workbenchPages) { IEditorReference[] editorReferences = workbenchPage.getEditorReferences(); for (IEditorReference editorReference : editorReferences) { IEditorPart editorPart = editorReference.getEditor(false); if (editorPart instanceof TaskEditor) { TaskEditorInput taskEditorInput = ((TaskEditor) editorPart).getTaskEditorInput(); if (taskEditorInput.exists()) { ITask task = taskEditorInput.getTask(); if (!(task instanceof LocalTask)) { relevantTasks.add(task); } } } } } } }
Source:
public boolean checkAccess(User user, String commandName) throws PermissionDeniedException { if (isDisabled()) { return true; } Account account = accountService.getAccount(user.getAccountId()); if (account == null) { throw new PermissionDeniedException("The account id=" + user.getAccountId() + "for user id=" + user.getId() + "is null"); } final Role accountRole = roleService.findRole(account.getRoleId()); if (accountRole == null || accountRole.getId() < 1L) { denyApiAccess(commandName); } if (accountRole.getRoleType() == RoleType.Admin && accountRole.getId() == RoleType.Admin.getId()) { return true; } final List<RolePermission> rolePermissions = roleService.findAllPermissionsBy(accountRole.getId()); if (checkPermission(rolePermissions, RolePermission.Permission.ALLOW, commandName)) { return true; } if (checkPermission(rolePermissions, RolePermission.Permission.DENY, commandName)) { denyApiAccess(commandName); } if (annotationRoleBasedApisMap.get(accountRole.getRoleType()) != null && annotationRoleBasedApisMap.get(accountRole.getRoleType()).contains(commandName)) { return true; } denyApiAccess(commandName); return false; }

Target:
public boolean checkAccess(User user, String commandName) throws PermissionDeniedException { if (isDisabled()) { return true; } Account account = accountService.getAccount(user.getAccountId()); if (account == null) { throw new PermissionDeniedException("The account id=" + user.getAccountId() + "for user id=" + user.getId() + "is null"); } final Role accountRole = roleService.findRole(account.getRoleId()); if (accountRole == null || accountRole.getId() < 1L) { denyApiAccess(commandName); } if (accountRole.getRoleType() == RoleType.Admin && accountRole.getId() == RoleType.Admin.getId()) { return true; } for (final RolePermission permission : roleService.findAllPermissionsBy(accountRole.getId())) { if (permission.getRule().matches(commandName)) { if (RolePermission.Permission.ALLOW.equals(permission.getPermission())) { return true; } else { denyApiAccess(commandName); } } } if (annotationRoleBasedApisMap.get(accountRole.getRoleType()) != null && annotationRoleBasedApisMap.get(accountRole.getRoleType()).contains(commandName)) { return true; } denyApiAccess(commandName); return false; }
Source:
protected void migrateData(ReviewDb db, UpdateUI ui) throws OrmException, SQLException { JdbcSchema schema = (JdbcSchema) db; SqlDialect dialect = schema.getDialect(); try (Statement stmt = schema.getConnection().createStatement()) { Set<String> listIndexes = dialect.listIndexes( schema.getConnection(), "changes"); for (String index : listIndexes) { if (index.equalsIgnoreCase("changes_allOpen")) { stmt.executeUpdate("DROP INDEX " + index); } if (index.equalsIgnoreCase("changes_allClosed")) { stmt.executeUpdate("DROP INDEX " + index); } if (index.equalsIgnoreCase("changes_byBranchClosed")) { stmt.executeUpdate("DROP INDEX " + index); } } stmt.executeUpdate("DROP INDEX changes_byProjectOpen"); if (dialect instanceof DialectPostgreSQL) { stmt.executeUpdate("CREATE INDEX changes_byProjectOpen" + " ON changes (dest_project_name, last_updated_on)" + " WHERE open = 'Y'"); } else { stmt.executeUpdate("CREATE INDEX changes_byProjectOpen" + " ON changes (open, dest_project_name, last_updated_on)"); } } }

Target:
protected void migrateData(ReviewDb db, UpdateUI ui) throws OrmException, SQLException { JdbcSchema schema = (JdbcSchema) db; SqlDialect dialect = schema.getDialect(); try (Statement stmt = schema.getConnection().createStatement()) { Pattern pattern = Pattern.compile("^changes_(allOpen|allClosed|byBranchClosed)$", Pattern.CASE_INSENSITIVE); Set<String> listIndexes = dialect.listIndexes( schema.getConnection(), "changes"); for (String index : listIndexes) { if (pattern.matcher(index).matches()) { stmt.executeUpdate("DROP INDEX " + index); } } stmt.executeUpdate("DROP INDEX changes_byProjectOpen"); if (dialect instanceof DialectPostgreSQL) { stmt.executeUpdate("CREATE INDEX changes_byProjectOpen" + " ON changes (dest_project_name, last_updated_on)" + " WHERE open = 'Y'"); } else { stmt.executeUpdate("CREATE INDEX changes_byProjectOpen" + " ON changes (open, dest_project_name, last_updated_on)"); } } }
Source:
public List<Object> configurations() { return Collections.singletonList(allowEmptyCatch); }

Target:
public List<Object> configurations() { return Collections.singletonList(new Config()); }
Source:
private boolean isBootstrapped(RequestMsg requestMsg) { if (getCurrentLayout() == null) { log.debug("Received request but not bootstrapped! RequestMsg={}", requestMsg); return false; } return true; }

Target:
private boolean isBootstrapped(RequestMsg requestMsg) { if (getCurrentLayout() == null) { log.debug("Received request but not bootstrapped! RequestMsg={}", TextFormat.shortDebugString(requestMsg)); return false; } return true; }
Source:
public String toString() { return format("PrestoWarning(code: %s, message: %s)", code, message); }

Target:
public String toString() { return format("%s, %s", warningCode, message); }
Source:
public void deactivate(ComponentContext context) throws LoginException { log.info("deactivate"); for (String id : registeredServices.keySet()) { unregisterService(id); } log.info("Deactivation successful!"); }

Target:
public void deactivate(ComponentContext context) throws LoginException { log.trace("deactivate"); for (String id : registeredServices.keySet()) { unregisterService(id); } log.trace("Deactivation successful!"); }
Source:
public void testIsHostedEngineStorage() { VmStatic vm = new VmStatic(); vm.setId(Guid.newGuid()); vm.setOrigin(OriginType.HOSTED_ENGINE); vmStaticDao.save(vm); DiskImage disk = new DiskImage(); disk.setId(Guid.newGuid()); disk.setImageId(Guid.newGuid()); disk.setActive(true); disk.setVolumeType(VolumeType.Preallocated); disk.setVolumeFormat(VolumeFormat.RAW); disk.setDiskDescription(""); imageDao.save(disk.getImage()); baseDiskDao.save(disk); ImageStorageDomainMap map = new ImageStorageDomainMap( disk.getImageId(), existingDomain.getId(), null, null); imageStorageDomainMapDao.save(map); VmDevice device = new VmDevice( new VmDeviceId(disk.getId(), vm.getId()), VmDeviceGeneralType.DISK, VmDeviceType.DISK.getName(), "", null, true, false, false, "", null, null, null); vmDeviceDao.save(device); DiskVmElement diskVmElement = new DiskVmElement(device.getId()); diskVmElement.setDiskInterface(DiskInterface.IDE); diskVmElementDao.save(diskVmElement); StorageDomain domain = dao.get(existingDomain.getId()); assertTrue(domain.isHostedEngineStorage()); vm.setOrigin(OriginType.MANAGED_HOSTED_ENGINE); vmStaticDao.update(vm); domain = dao.get(existingDomain.getId()); assertTrue(domain.isHostedEngineStorage()); }

Target:
public void testIsHostedEngineStorage() { VmStatic vm = new VmStatic(); vm.setId(Guid.newGuid()); vm.setOrigin(OriginType.HOSTED_ENGINE); vmStaticDao.save(vm); DiskImage disk = new DiskImage(); disk.setId(Guid.newGuid()); disk.setImageId(Guid.newGuid()); disk.setActive(true); disk.setVolumeType(VolumeType.Preallocated); disk.setVolumeFormat(VolumeFormat.RAW); imageDao.save(disk.getImage()); baseDiskDao.save(disk); ImageStorageDomainMap map = new ImageStorageDomainMap( disk.getImageId(), existingDomain.getId(), null, null); imageStorageDomainMapDao.save(map); VmDevice device = new VmDevice( new VmDeviceId(disk.getId(), vm.getId()), VmDeviceGeneralType.DISK, VmDeviceType.DISK.getName(), "", null, true, false, false, "", null, null, null); vmDeviceDao.save(device); DiskVmElement diskVmElement = new DiskVmElement(device.getId()); diskVmElement.setDiskInterface(DiskInterface.IDE); diskVmElementDao.save(diskVmElement); StorageDomain domain = dao.get(existingDomain.getId()); assertTrue(domain.isHostedEngineStorage()); vm.setOrigin(OriginType.MANAGED_HOSTED_ENGINE); vmStaticDao.update(vm); domain = dao.get(existingDomain.getId()); assertTrue(domain.isHostedEngineStorage()); }
Source:
public DefaultPageCursorTracerSupplier() { }

Target:
private DefaultPageCursorTracerSupplier() { }
Source:
private HttpURLConnection setupConnection() throws IOException { Logger.v(TAG, "HttpWebRequest setupConnection thread:" + android.os.Process.myTid()); if (mUrl == null) { throw new IllegalArgumentException("requestURL"); } if (!mUrl.getProtocol().equalsIgnoreCase("http") && !mUrl.getProtocol().equalsIgnoreCase("https")) { throw new IllegalArgumentException("requestURL"); } HttpURLConnection.setFollowRedirects(true); final HttpURLConnection connection = (HttpURLConnection)mUrl.openConnection(); connection.setConnectTimeout(CONNECT_TIME_OUT); if (Build.VERSION.SDK_INT > 13) { connection.setRequestProperty("Connection", "close"); } final Iterator<String> headerKeys = mRequestHeaders.keySet().iterator(); while (headerKeys.hasNext()) { String header = headerKeys.next(); Logger.v(TAG, "Setting header: " + header); connection.setRequestProperty(header, mRequestHeaders.get(header)); } System.setProperty("http.keepAlive", "false"); connection.setReadTimeout(READ_TIME_OUT); connection.setInstanceFollowRedirects(mInstanceRedirectsFollow); connection.setUseCaches(mUseCaches); connection.setRequestMethod(mRequestMethod); connection.setDoInput(true); setRequestBody(connection); return connection; }

Target:
private HttpURLConnection setupConnection() throws IOException { Logger.v(TAG, "HttpWebRequest setupConnection thread:" + android.os.Process.myTid()); if (mUrl == null) { throw new IllegalArgumentException("requestURL"); } if (!mUrl.getProtocol().equalsIgnoreCase("http") && !mUrl.getProtocol().equalsIgnoreCase("https")) { throw new IllegalArgumentException("requestURL"); } HttpURLConnection.setFollowRedirects(true); final HttpURLConnection connection = (HttpURLConnection)mUrl.openConnection(); connection.setConnectTimeout(CONNECT_TIME_OUT); if (Build.VERSION.SDK_INT > 13) { connection.setRequestProperty("Connection", "close"); } final Iterator<String> headerKeys = mRequestHeaders.keySet().iterator(); while (headerKeys.hasNext()) { String header = headerKeys.next(); Logger.v(TAG, "Setting header: " + header); connection.setRequestProperty(header, mRequestHeaders.get(header)); } System.setProperty("http.keepAlive", "false"); connection.setReadTimeout(READ_TIME_OUT); connection.setInstanceFollowRedirects(mInstanceRedirectsFollow); connection.setUseCaches(mUseCaches); connection.setRequestMethod(mRequestMethod); connection.setDoInput(true); setRequestBody(connection, mRequestContent, mRequestContentType); return connection; }
Source:
private ClusterClientProvider<String> createClusterClientProvider(String clusterId) { return () -> { final Configuration configuration = new Configuration(flinkConfig); try { final Optional<Endpoint> restEndpoint = client.getRestEndpoint(clusterId).get(); if (restEndpoint.isPresent()) { configuration.setString(RestOptions.ADDRESS, restEndpoint.get().getAddress()); configuration.setInteger(RestOptions.PORT, restEndpoint.get().getPort()); } else { throw new RuntimeException( new ClusterRetrieveException( "Could not get the rest endpoint of " + clusterId)); } return new RestClusterClient<>( configuration, clusterId, new StandaloneClientHAServices(HighAvailabilityServicesUtils.getWebMonitorAddress( configuration, HighAvailabilityServicesUtils.AddressResolution.TRY_ADDRESS_RESOLUTION))); } catch (Exception e) { client.handleException(e); throw new RuntimeException(new ClusterRetrieveException("Could not create the RestClusterClient.", e)); } }; }

Target:
private ClusterClientProvider<String> createClusterClientProvider(String clusterId) { return () -> { final Configuration configuration = new Configuration(flinkConfig); final Optional<Endpoint> restEndpoint = client.getRestEndpoint(clusterId); if (restEndpoint.isPresent()) { configuration.setString(RestOptions.ADDRESS, restEndpoint.get().getAddress()); configuration.setInteger(RestOptions.PORT, restEndpoint.get().getPort()); } else { throw new RuntimeException( new ClusterRetrieveException( "Could not get the rest endpoint of " + clusterId)); } try { return new RestClusterClient<>( configuration, clusterId, new StandaloneClientHAServices(HighAvailabilityServicesUtils.getWebMonitorAddress( configuration, HighAvailabilityServicesUtils.AddressResolution.TRY_ADDRESS_RESOLUTION))); } catch (Exception e) { client.handleException(e); throw new RuntimeException(new ClusterRetrieveException("Could not create the RestClusterClient.", e)); } }; }
Source:
private SimpleFeatureCollection eliminateFeatureBounds(SimpleFeatureCollection fc) { final SimpleFeatureType original = fc.getSchema(); List<String> names = new ArrayList<String>(); boolean alternateGeometry = false; for(AttributeDescriptor ad : original.getAttributeDescriptors()) { final String name = ad.getLocalName(); if(!boundedBy.equals(name) && !metaData.equals(name)) { names.add(name); } if(!location.equals(name) && ad instanceof GeometryDescriptor) { alternateGeometry = true; } } if(alternateGeometry) { names.remove("location"); } if(names.size() < original.getDescriptors().size()) { String[] namesArray = names.toArray(new String[names.size()]); SimpleFeatureType target = SimpleFeatureTypeBuilder.retype(original, namesArray); return new RetypingFeatureCollection(fc, target); } return fc; }

Target:
private SimpleFeatureCollection eliminateFeatureBounds(SimpleFeatureCollection fc) { final SimpleFeatureType original = fc.getSchema(); List<String> names = new ArrayList<String>(); boolean alternateGeometry = false; for(AttributeDescriptor ad : original.getAttributeDescriptors()) { final String name = ad.getLocalName(); if(!BOUNDEDBY.equals(name) && !METADATA.equals(name)) { names.add(name); } if(!LOCATION.equals(name) && ad instanceof GeometryDescriptor) { alternateGeometry = true; } } if(alternateGeometry) { names.remove("location"); } if(names.size() < original.getDescriptors().size()) { String[] namesArray = names.toArray(new String[names.size()]); SimpleFeatureType target = SimpleFeatureTypeBuilder.retype(original, namesArray); return new RetypingFeatureCollection(fc, target); } return fc; }
Source:
public void postAttachInit(ArrayList<EntityModel> datacenters) { ListModel model = new ListModel(); setWindow(model); model.setTitle(ConstantsManager.getInstance().getConstants().attachToDataCenterTitle()); if (getEntity() != null) { switch (getEntity().getStorageDomainType()) { case ISO: setHelpTag(HelpTag.attach_iso_library); break; case Data: setHelpTag(HelpTag.attach_storage); break; case ImportExport: setHelpTag(HelpTag.attach_export_domain); break; } } model.setItems(datacenters); if (datacenters.isEmpty()) { model.setMessage(ConstantsManager.getInstance() .getConstants() .thereAreNoDataCenterStorageDomainAttachedMsg()); UICommand tempVar = new UICommand("Cancel", this); tempVar.setTitle(ConstantsManager.getInstance().getConstants().close()); tempVar.setIsDefault(true); tempVar.setIsCancel(true); model.getCommands().add(tempVar); } else { model.setSelectedItem(datacenters.get(0)); UICommand tempVar2 = UICommand.createDefaultOkUiCommand("OnAttach", this); model.getCommands().add(tempVar2); UICommand tempVar3 = UICommand.createCancelUiCommand("Cancel", this); model.getCommands().add(tempVar3); } }

Target:
public void postAttachInit(ArrayList<EntityModel> datacenters) { ListModel model = new ListModel(); setWindow(model); model.setTitle(ConstantsManager.getInstance().getConstants().attachToDataCenterTitle()); if (getEntity() != null) { switch (getEntity().getStorageDomainType()) { case ISO: setHelpTag(HelpTag.attach_iso_library); break; case Data: setHelpTag(HelpTag.attach_storage); break; case ImportExport: setHelpTag(HelpTag.attach_export_domain); break; } } if (datacenters.isEmpty()) { model.setMessage(ConstantsManager.getInstance() .getConstants() .thereAreNoDataCenterStorageDomainAttachedMsg()); UICommand tempVar = new UICommand("Cancel", this); tempVar.setTitle(ConstantsManager.getInstance().getConstants().close()); tempVar.setIsDefault(true); tempVar.setIsCancel(true); model.getCommands().add(tempVar); } else { model.setItems(datacenters, datacenters.get(0)); UICommand tempVar2 = UICommand.createDefaultOkUiCommand("OnAttach", this); model.getCommands().add(tempVar2); UICommand tempVar3 = UICommand.createCancelUiCommand("Cancel", this); model.getCommands().add(tempVar3); } }
Source:
public void testDefeatRecovery() throws Exception { final Channel channel1 = mock(Channel.class); when(channel1.isOpen()).thenReturn(true); willAnswer(i -> { return null; }).given(channel1).close(); final Channel channel2 = mock(Channel.class); when(channel2.isOpen()).thenReturn(true); final com.rabbitmq.client.Connection rabbitConn = mock(AutorecoveringConnection.class); when(rabbitConn.isOpen()).thenReturn(true); com.rabbitmq.client.ConnectionFactory cf = mock(com.rabbitmq.client.ConnectionFactory.class); doAnswer(invocation -> rabbitConn).when(cf).newConnection(any(ExecutorService.class), anyString()); when(rabbitConn.createChannel()).thenReturn(channel1).thenReturn(channel2); CachingConnectionFactory ccf = new CachingConnectionFactory(cf); Connection conn1 = ccf.createConnection(); Channel channel = conn1.createChannel(false); verifyChannelIs(channel1, channel); channel.close(); conn1.close(); Connection conn2 = ccf.createConnection(); assertSame(conn1, conn2); channel = conn1.createChannel(false); verifyChannelIs(channel1, channel); channel.close(); conn2.close(); when(rabbitConn.isOpen()).thenReturn(false).thenReturn(true); when(channel1.isOpen()).thenReturn(false); conn2 = ccf.createConnection(); try { channel = conn2.createChannel(false); } catch (AmqpException e) { assertThat(e.getMessage(), equalTo("Auto recovery connection is not currently open")); } channel = conn2.createChannel(false); verifyChannelIs(channel2, channel); channel.close(); verify(rabbitConn, never()).close(); verify(channel1).close(); }

Target:
public void testDefeatRecovery() throws Exception { final Channel channel1 = mock(Channel.class); when(channel1.isOpen()).thenReturn(true); final Channel channel2 = mock(Channel.class); when(channel2.isOpen()).thenReturn(true); final com.rabbitmq.client.Connection rabbitConn = mock(AutorecoveringConnection.class); when(rabbitConn.isOpen()).thenReturn(true); com.rabbitmq.client.ConnectionFactory cf = mock(com.rabbitmq.client.ConnectionFactory.class); doAnswer(invocation -> rabbitConn).when(cf).newConnection(any(ExecutorService.class), anyString()); when(rabbitConn.createChannel()).thenReturn(channel1).thenReturn(channel2); CachingConnectionFactory ccf = new CachingConnectionFactory(cf); Connection conn1 = ccf.createConnection(); Channel channel = conn1.createChannel(false); verifyChannelIs(channel1, channel); channel.close(); conn1.close(); Connection conn2 = ccf.createConnection(); assertSame(conn1, conn2); channel = conn1.createChannel(false); verifyChannelIs(channel1, channel); channel.close(); conn2.close(); when(rabbitConn.isOpen()).thenReturn(false).thenReturn(true); when(channel1.isOpen()).thenReturn(false); conn2 = ccf.createConnection(); try { conn2.createChannel(false); fail("Expected AutoRecoverConnectionNotCurrentlyOpenException"); } catch (AutoRecoverConnectionNotCurrentlyOpenException e) { assertThat(e.getMessage(), equalTo("Auto recovery connection is not currently open")); } channel = conn2.createChannel(false); verifyChannelIs(channel2, channel); channel.close(); verify(rabbitConn, never()).close(); verify(channel1).close(); }
Source:
public void deleteCell(EntityId entityId, String family, String qualifier, long timestamp) throws IOException { final State state = mState.get(); Preconditions.checkState(state == State.OPEN, "Cannot delete cell while KijiTableWriter %s is in state %s.", this, state); final HBaseColumnName hbaseColumnName = mWriterLayoutCapsule.getColumnNameTranslator() .toHBaseColumnName(new KijiColumnName(family, qualifier)); final DeleteRequest delete = new DeleteRequest( Bytes.toBytes(mTable.getName()), entityId.getHBaseRowKey(), hbaseColumnName.getFamily(), hbaseColumnName.getQualifier(), timestamp); delete.setDeleteAtTimestampOnly(true); try { mHBClient.delete(delete).join(); } catch (Exception e) { ZooKeeperUtils.wrapAndRethrow(e); } }

Target:
public void deleteCell(EntityId entityId, String family, String qualifier, long timestamp) throws IOException { final State state = mState.get(); Preconditions.checkState(state == State.OPEN, "Cannot delete cell while KijiTableWriter %s is in state %s.", this, state); final HBaseColumnName hbaseColumnName = mWriterLayoutCapsule.getColumnNameTranslator() .toHBaseColumnName(new KijiColumnName(family, qualifier)); final DeleteRequest delete = new DeleteRequest( mTableName, entityId.getHBaseRowKey(), hbaseColumnName.getFamily(), hbaseColumnName.getQualifier(), timestamp); delete.setDeleteAtTimestampOnly(true); try { mHBClient.delete(delete).join(); } catch (Exception e) { ZooKeeperUtils.wrapAndRethrow(e); } }
Source:
public static boolean isAnyPrefixOf(String pathToCheck, Collection<String> possiblePrefixes) { for (String possiblePrefix : possiblePrefixes) { if (pathToCheck.startsWith(possiblePrefix)) { return true; } if (possiblePrefix.length() == pathToCheck.length() + 1 && possiblePrefix.charAt(possiblePrefix.length() - 1) == '/' && possiblePrefix.startsWith(pathToCheck)) { return true; } } return false; }

Target:
protected static boolean isAnyPrefixOf(String pathToCheck, Collection<String> possiblePrefixes) { for (String possiblePrefix : possiblePrefixes) { if (pathToCheck.startsWith(possiblePrefix)) { return true; } if (possiblePrefix.length() == pathToCheck.length() + 1 && possiblePrefix.charAt(possiblePrefix.length() - 1) == '/' && possiblePrefix.startsWith(pathToCheck)) { return true; } } return false; }
Source:
public SQLJobSubmissionBuilder addJars(List<Path> jarFiles) { this.jars.addAll(jarFiles.stream().map(path -> path.toAbsolutePath().toString()).collect(Collectors.toList())); return this; }

Target:
public SQLJobSubmissionBuilder addJars(List<Path> jarFiles) { jarFiles.forEach(this::addJar); return this; }
Source:
public String getDisplayRecipient(ZulipApp app) { if (this.getType() == MessageType.STREAM_MESSAGE) { return this.getStream().getName(); } else { Person[] people = this.getRecipients(app); ArrayList<String> names = new ArrayList<>(); for (Person person : people) { if (!person.getEmail().equals(app.getYou().getEmail()) || people.length == 1) { names.add(person.getName()); } } return TextUtils.join(", ", names); } }

Target:
public String getDisplayRecipient(ZulipApp app) { if (this.getType() == MessageType.STREAM_MESSAGE) { return this.getStream().getName(); } else { Person[] people = this.getRecipients(app); ArrayList<String> names = new ArrayList<>(); for (Person person : people) { if (person.id != app.getYou().id || people.length == 1) { names.add(person.getName()); } } return TextUtils.join(", ", names); } }
Source:
public void writeFrom(ReadableByteChannel channel, long offset, long size) throws IOException { if (offset < 0 || offset > capacityInBytes) { throw new IllegalArgumentException( "Provided offset [" + offset + "] is out of bounds for the segment [" + file.getAbsolutePath() + "] with capacity [" + capacityInBytes + "]"); } if (offset + size > capacityInBytes) { ensureNext(metrics.overflowWriteError); logger.info("{} : Write of data of size from offset from a channel will be rolled over " + "to the next segment because capacity is {}", file.getAbsolutePath(), next.getName(), size, offset, next.getName(), capacityInBytes); } long sizeToBeWritten = Math.min(size, capacityInBytes - offset); long sizeLeft = size - sizeToBeWritten; long bytesWritten = 0; while (bytesWritten < sizeToBeWritten) { bytesWritten += fileChannel.transferFrom(channel, offset + bytesWritten, sizeToBeWritten - bytesWritten); } if (offset + sizeToBeWritten > endOffset.get()) { endOffset.set(offset + sizeToBeWritten); } if (sizeLeft > 0) { next.writeFrom(channel, 0, sizeLeft); } }

Target:
void writeFrom(ReadableByteChannel channel, long offset, long size) throws IOException { if (offset < 0 || offset >= capacityInBytes) { throw new IndexOutOfBoundsException( "Provided offset [" + offset + "] is out of bounds for the segment [" + file.getAbsolutePath() + "] with capacity [" + capacityInBytes + "]"); } if (offset + size > capacityInBytes) { metrics.overflowWriteError.inc(); throw new IndexOutOfBoundsException("Cannot write to segment [" + file.getAbsolutePath() + "] from offset [" + offset + "] for size [" + size + "] because it exceeds the capacity [" + capacityInBytes + "]"); } long bytesWritten = 0; while (bytesWritten < size) { bytesWritten += fileChannel.transferFrom(channel, offset + bytesWritten, size - bytesWritten); } if (offset + size > endOffset.get()) { endOffset.set(offset + size); } }
Source:
protected void printEntryLogMetadata(long logId) throws IOException { LOG.info("Print entryLogMetadata of entrylog " + logId + " (" + Long.toHexString(logId) + ".log)"); initEntryLogger(); EntryLogMetadata entryLogMetadata = entryLogger.getEntryLogMetadata(logId); entryLogMetadata.getLedgersMap().forEach((ledgerId, size) -> { LOG.info("--------- Lid=" + ledgerIdFormatter.formatLedgerId(ledgerId) + ", TotalSizeOfEntriesOfLedger=" + size + " ---------"); }); }

Target:
protected void printEntryLogMetadata(long logId) throws IOException { LOG.info("Print entryLogMetadata of entrylog ({}.log)", logId, Long.toHexString(logId)); initEntryLogger(); EntryLogMetadata entryLogMetadata = entryLogger.getEntryLogMetadata(logId); entryLogMetadata.getLedgersMap().forEach((ledgerId, size) -> { LOG.info("--------- Lid={}, TotalSizeOfEntriesOfLedger={} ---------", ledgerIdFormatter.formatLedgerId(ledgerId), size); }); }
Source:
private static void serializeIdentity(final PreSharedKeyIdentity principal, final DatagramWriter writer) { writer.writeByte(ClientAuthenticationType.PSK.code); byte[] virtualHost = principal.getVirtualHost() == null ? new byte[0] : principal.getVirtualHost().getBytes(StandardCharsets.UTF_8); writeBytesWithLength(PSK_LENGTH_BITS, virtualHost, writer); writeBytesWithLength(PSK_LENGTH_BITS, principal.getIdentity().getBytes(StandardCharsets.UTF_8), writer); }

Target:
private static void serializeIdentity(final PreSharedKeyIdentity principal, final DatagramWriter writer) { writer.writeByte(ClientAuthenticationType.PSK.code); byte[] virtualHost = principal.getVirtualHost() == null ? EMPTY_BYTE_ARRAY : principal.getVirtualHost().getBytes(StandardCharsets.UTF_8); writeBytesWithLength(PSK_LENGTH_BITS, virtualHost, writer); writeBytesWithLength(PSK_LENGTH_BITS, principal.getIdentity().getBytes(StandardCharsets.UTF_8), writer); }
Source:
public long computeBin(final Histogram1d<T> histo) {; long[] hist = histo.toLongArray(); int no_pts = hist.length; int pk, st, fi, d1, d2; long tmp; int i; int thresh; boolean doInvert = false; pk = find_start(hist, no_pts); st = find_first(hist, no_pts); fi = find_end(hist, no_pts); d1 = pk - st; d2 = fi - pk; if ((d1 < 0) || (d2 < 0)) { log.warn("Histogram peak at a strange location"); } if (d1 > d2) { doInvert = true; } if (doInvert) { for (i = 0; i < no_pts / 2; i++) { tmp = hist[i]; hist[i] = hist[no_pts - 1 - i]; hist[no_pts - 1 - i] = tmp; } } st = find_start(hist, no_pts); thresh = find_corner(hist, st, no_pts); if (doInvert) { thresh = no_pts - thresh - 1; } return thresh; }

Target:
public long computeBin(final Histogram1d<T> histo) {; long[] hist = histo.toLongArray(); int noPts = hist.length; int pk, st, fi, d1, d2; long tmp; int i; int thresh; boolean doInvert = false; pk = findStart(hist, noPts); st = findFirst(hist, noPts); fi = findEnd(hist, noPts); d1 = pk - st; d2 = fi - pk; if ((d1 < 0) || (d2 < 0)) { log.warn("Histogram peak at a strange location"); } if (d1 > d2) { doInvert = true; } if (doInvert) { for (i = 0; i < noPts / 2; i++) { tmp = hist[i]; hist[i] = hist[noPts - 1 - i]; hist[noPts - 1 - i] = tmp; } } st = findStart(hist, noPts); thresh = findCorner(hist, st, noPts); if (doInvert) { thresh = noPts - thresh - 1; } return thresh; }
Source:
private TimeLockServices createLegacyTimeLockServices( Supplier<ManagedTimestampService> rawTimestampServiceSupplier, RemoteLockService lockService) { TimelockService timelockService = new LockTokenConvertingTimelockService( new LegacyTimelockService(rawTimestampServiceSupplier.get(), lockService, LockClient.of("legacy"))); return TimeLockServices.create( new TimelockTimestampServiceAdapter(timelockService), lockService, AsyncOrLegacyTimelockService.createFromLegacyTimelock(timelockService), AwaitingLeadershipProxy.newProxyInstance( ManagedTimestampService.class, rawTimestampServiceSupplier, leaderElectionService)); }

Target:
private TimeLockServices createLegacyTimeLockServices( Supplier<ManagedTimestampService> rawTimestampServiceSupplier, RemoteLockService lockService) { ManagedTimestampService timestampService = AwaitingLeadershipProxy.newProxyInstance( ManagedTimestampService.class, rawTimestampServiceSupplier, leaderElectionService); TimelockService timelockService = new LockTokenConvertingTimelockService( new LegacyTimelockService( timestampService, lockService, LockClient.of("legacy"))); return TimeLockServices.create( timestampService, lockService, AsyncOrLegacyTimelockService.createFromLegacyTimelock(timelockService), timestampService); }
Source:
public void testWithParserAndNullInputformatParseProperly() throws IOException { final InputRowParser<ByteBuffer> parser = new StringInputRowParser( new NotConvertibleToInputFormatParseSpec(), StringUtils.UTF8_STRING ); final StreamChunkParser chunkParser = new StreamChunkParser( parser, null, null, null, null ); final String json = "{\"timestamp\": \"2020-01-01\", \"dim\": \"val\", \"met\": \"val2\"}"; List<InputRow> parsedRows = chunkParser.parse(Collections.singletonList(json.getBytes(StringUtils.UTF8_STRING))); Assert.assertEquals(1, parsedRows.size()); InputRow row = parsedRows.get(0); Assert.assertEquals(DateTimes.of("2020-01-01"), row.getTimestamp()); Assert.assertEquals("val", Iterables.getOnlyElement(row.getDimension("dim"))); Assert.assertEquals("val2", Iterables.getOnlyElement(row.getDimension("met"))); }

Target:
public void testWithParserAndNullInputformatParseProperly() throws IOException { final InputRowParser<ByteBuffer> parser = new StringInputRowParser( new NotConvertibleToInputFormatParseSpec(), StringUtils.UTF8_STRING ); final StreamChunkParser chunkParser = new StreamChunkParser( parser, null, null, null, null ); parseAndAssertResult(chunkParser); }
Source:
public void start(Collection<? extends Location> locations) { RedisStore master = getMaster(); if (master == null) { master = addChild(EntitySpec.create(RedisStore.class)); setAttribute(MASTER, master); } Entities.manage(master); master.invoke(RedisStore.START, ImmutableMap.<String, Object>of("locations", ImmutableList.copyOf(locations))).blockUntilEnded(); DynamicCluster slaves = getSlaves(); if (slaves == null) { slaves = addChild(EntitySpec.create(DynamicCluster.class) .configure(DynamicCluster.MEMBER_SPEC, EntitySpec.create(RedisSlave.class).configure(RedisSlave.MASTER, master))); setAttribute(SLAVES, slaves); } slaves.invoke(DynamicCluster.START, ImmutableMap.<String, Object>of("locations", ImmutableList.copyOf(locations))).blockUntilEnded(); setAttribute(Startable.SERVICE_UP, calculateServiceUp()); addEnricher(Enrichers.builder() .propagating(RedisStore.HOSTNAME, RedisStore.ADDRESS, RedisStore.SUBNET_HOSTNAME, RedisStore.SUBNET_ADDRESS, RedisStore.REDIS_PORT) .from(master) .build()); }

Target:
public void start(Collection<? extends Location> locations) { ServiceStateLogic.setExpectedState(this, Lifecycle.STARTING); ServiceProblemsLogic.clearProblemsIndicator(this, START); try { doStart(locations); ServiceStateLogic.setExpectedState(this, Lifecycle.RUNNING); } catch (Exception e) { ServiceProblemsLogic.updateProblemsIndicator(this, START, "Start failed with error: "+e); ServiceStateLogic.setExpectedState(this, Lifecycle.ON_FIRE); throw Exceptions.propagate(e); } }
Source:
private Collection<Resource> getModifiedResources() { List<Resource> changed = new ArrayList<Resource>(); for (Resource currentResource : session.getAllSessionResources()) { if (currentResource.isModified()) { changed.add(currentResource); } } for (Resource currentResource : session.getSemanticResources()) { if (currentResource.isModified()) { changed.add(currentResource); } } return changed; }

Target:
private Collection<Resource> getModifiedResources() { List<Resource> changed = new ArrayList<Resource>(); for (Resource currentResource : session.getAllSessionResources()) { if (currentResource.isModified()) { changed.add(currentResource); } } for (Resource currentResource : session.getSemanticResources()) { if (currentResource.isModified()) { changed.add(currentResource); } } if (session instanceof DAnalysisSessionEObject) { for (Resource currentResource : ((DAnalysisSessionEObject) session).getControlledResources()) { if (currentResource.isModified()) { changed.add(currentResource); } } } return changed; }
Source:
static public void assertEqualDoubleArrays(final double[] lhs, final double[] rhs, final double accuracy) { if (accuracy <= 0) throw new IllegalArgumentException("Accuracy must be positive."); Assert.assertEquals(lhs.length, rhs.length, "Arrays not same length: " + lhs.length + " vs. " + rhs.length); for (int i = 0; i < lhs.length; ++i) { Assert.assertTrue(compareDoubleWithAccuracy(lhs[i], rhs[i], accuracy), "Arrays disagree at position " + i + ": " + lhs[i] + " vs. " + rhs[i] + ". "); } }

Target:
public static void assertEqualDoubleArrays(final double[] lhs, final double[] rhs, final double accuracy) { Assert.assertNotNull(lhs); Assert.assertNotNull(rhs); if (accuracy <= 0) throw new IllegalArgumentException("Accuracy must be positive."); Assert.assertEquals(lhs.length, rhs.length, "Arrays not same length: " + lhs.length + " vs. " + rhs.length); for (int i = 0; i < lhs.length; ++i) { Assert.assertTrue(compareDoubleWithAccuracy(lhs[i], rhs[i], accuracy), "Arrays disagree at position " + i + ": " + lhs[i] + " vs. " + rhs[i] + ". "); } }
Source:
public Predicate<String> create(final String resourceGroup, final URI vaultUri, final boolean shouldBePresent) { checkNotNull(resourceGroup, "resourceGroup cannot be null"); checkNotNull(vaultUri, "vaultUri cannot be null"); return retry(new Predicate<String>() { @Override public boolean apply(final String name) { boolean present = false; checkNotNull(name, "name cannot be null"); DeletedSecretBundle secret = api.getVaultApi(resourceGroup).getDeletedSecret(vaultUri, name); if (shouldBePresent) { return secret != null; } else { return secret == null; } } }, operationTimeout, initialPeriod, maxPeriod); }

Target:
public Predicate<String> create(final String resourceGroup, final URI vaultUri, final boolean shouldBePresent) { checkNotNull(resourceGroup, "resourceGroup cannot be null"); checkNotNull(vaultUri, "vaultUri cannot be null"); return retry(new Predicate<String>() { @Override public boolean apply(final String name) { boolean present = false; checkNotNull(name, "name cannot be null"); DeletedSecretBundle secret = api.getVaultApi(resourceGroup).getDeletedSecret(vaultUri, name); return shouldBePresent == (secret != null); } }, operationTimeout, initialPeriod, maxPeriod); }
Source:
private void putUnion(final ByteBuffer buffer, final int position, final DoublesUnion union) { Int2ObjectMap<DoublesUnion> map = unions.get(buffer); if (map == null) { map = new Int2ObjectOpenHashMap<>(); unions.put(buffer, map); } map.put(position, union); }

Target:
private void putUnion(final ByteBuffer buffer, final int position, final DoublesUnion union) { Int2ObjectMap<DoublesUnion> map = unions.computeIfAbsent(buffer, buf -> new Int2ObjectOpenHashMap<>()); map.put(position, union); }
Source:
private void migrateOpenPgpGlobalToAccountSettings() { Preferences preferences = Preferences.getPreferences(this); Storage storage = preferences.getStorage(); String openPgpProvider = storage.getString("openPgpProvider", null); boolean openPgpSupportSignOnly = storage.getBoolean("openPgpSupportSignOnly", false); for (Account account : preferences.getAccounts()) { account.setOpenPgpProvider(openPgpProvider); account.setOpenPgpHideSignOnly(!openPgpSupportSignOnly); } storage.edit() .remove("openPgpProvider") .remove("openPgpSupportSignOnly") .commit(); }

Target:
private void migrateOpenPgpGlobalToAccountSettings() { Preferences preferences = Preferences.getPreferences(this); Storage storage = preferences.getStorage(); String openPgpProvider = storage.getString("openPgpProvider", null); boolean openPgpSupportSignOnly = storage.getBoolean("openPgpSupportSignOnly", false); for (Account account : preferences.getAccounts()) { account.setOpenPgpProvider(openPgpProvider); account.setOpenPgpHideSignOnly(!openPgpSupportSignOnly); account.save(preferences); } storage.edit() .remove("openPgpProvider") .remove("openPgpSupportSignOnly") .commit(); }
Source:
public static VirtualChannel start(final TaskListener listener, final String rootUsername, final String rootPassword) throws IOException, InterruptedException { if(File.pathSeparatorChar==';') return newLocalChannel(); String os = Util.fixNull(System.getProperty("os.name")); if(os.equals("Linux")) return new UnixSu() { protected String sudoExe() { return "sudo"; } protected Process sudoWithPass(ArgumentListBuilder args) throws IOException { args.prepend(sudoExe(),"-S"); listener.getLogger().println("$ "+Util.join(args.toList()," ")); ProcessBuilder pb = new ProcessBuilder(args.toCommandArray()); Process p = pb.start(); try (PrintStream ps = new PrintStream(p.getOutputStream())) { ps.println(rootPassword); ps.println(rootPassword); ps.println(rootPassword); } return p; } }.start(listener,rootPassword); if(os.equals("SunOS")) return new UnixSu() { protected String sudoExe() { return "/usr/bin/pfexec"; } protected Process sudoWithPass(ArgumentListBuilder args) throws IOException { listener.getLogger().println("Running with embedded_su"); ProcessBuilder pb = new ProcessBuilder(args.prepend(sudoExe()).toCommandArray()); return EmbeddedSu.startWithSu(rootUsername, rootPassword, pb); } }.start(listener,rootUsername==null?null:rootPassword); return newLocalChannel(); }

Target:
public static VirtualChannel start(final TaskListener listener, final String rootUsername, final String rootPassword) throws IOException, InterruptedException { if(File.pathSeparatorChar==';') return newLocalChannel(); String os = Util.fixNull(System.getProperty("os.name")); if(os.equals("Linux")) return new UnixSu() { protected String sudoExe() { return "sudo"; } protected Process sudoWithPass(ArgumentListBuilder args) throws IOException { args.prepend(sudoExe(),"-S"); listener.getLogger().println("$ "+Util.join(args.toList()," ")); ProcessBuilder pb = new ProcessBuilder(args.toCommandArray()); Process p = pb.start(); PrintStream ps = new PrintStream(p.getOutputStream()); ps.println(rootPassword); ps.println(rootPassword); ps.println(rootPassword); return p; } }.start(listener,rootPassword); if(os.equals("SunOS")) return new UnixSu() { protected String sudoExe() { return "/usr/bin/pfexec"; } protected Process sudoWithPass(ArgumentListBuilder args) throws IOException { listener.getLogger().println("Running with embedded_su"); ProcessBuilder pb = new ProcessBuilder(args.prepend(sudoExe()).toCommandArray()); return EmbeddedSu.startWithSu(rootUsername, rootPassword, pb); } }.start(listener,rootUsername==null?null:rootPassword); return newLocalChannel(); }
Source:
private static Interval createToInterval(final String intervalName, final boolean sourceNegativeStrand, final TargetIntersection targetIntersection) { int toStart = targetIntersection.chain.getBlock(targetIntersection.firstBlockIndex).toStart + targetIntersection.startOffset; int toEnd = targetIntersection.chain.getBlock(targetIntersection.lastBlockIndex).getToEnd() - targetIntersection.offsetFromEnd; if (toEnd <= toStart || toStart < 0) { throw new SAMException("Something strange lifting over interval " + intervalName); } if (targetIntersection.chain.toOppositeStrand) { int negativeStart = targetIntersection.chain.toSequenceSize - toEnd; int negativeEnd = targetIntersection.chain.toSequenceSize - toStart; toStart = negativeStart; toEnd = negativeEnd; } final boolean strand = targetIntersection.chain.toOppositeStrand ? !sourceNegativeStrand : sourceNegativeStrand; return new Interval(targetIntersection.chain.toSequenceName, toStart+1, toEnd, strand, intervalName); }

Target:
private static Interval createToInterval(final String intervalName, final boolean sourceNegativeStrand, final TargetIntersection targetIntersection) { int toStart = targetIntersection.chain.getBlock(targetIntersection.firstBlockIndex).toStart + targetIntersection.startOffset; int toEnd = targetIntersection.chain.getBlock(targetIntersection.lastBlockIndex).getToEnd() - targetIntersection.offsetFromEnd; if (toEnd <= toStart || toStart < 0) { throw new SAMException("Something strange lifting over interval " + intervalName); } if (targetIntersection.chain.toOppositeStrand) { int negativeStart = targetIntersection.chain.toSequenceSize - toEnd; int negativeEnd = targetIntersection.chain.toSequenceSize - toStart; toStart = negativeStart; toEnd = negativeEnd; } final boolean negativeStrand = targetIntersection.chain.toOppositeStrand ? !sourceNegativeStrand : sourceNegativeStrand; return new Interval(targetIntersection.chain.toSequenceName, toStart+1, toEnd, negativeStrand, intervalName); }
Source:
@Test public void annotatedNestedType() { String tuacanon = TypeUseAnnotation.class.getCanonicalName(); String expected = "java.util.Map.@" + tuacanon + " Entry"; AnnotationSpec typeUseAnnotation = AnnotationSpec.builder(TypeUseAnnotation.class).build(); TypeName type = TypeName.get(Map.Entry.class).annotated(typeUseAnnotation); String actual = type.toString(); assertEquals(expected, actual); }

Target:
@Test public void annotatedNestedType() { String expected = "java.util.Map.@" + TypeUseAnnotation.class.getCanonicalName() + " Entry"; AnnotationSpec typeUseAnnotation = AnnotationSpec.builder(TypeUseAnnotation.class).build(); TypeName type = TypeName.get(Map.Entry.class).annotated(typeUseAnnotation); String actual = type.toString(); assertEquals(expected, actual); }
Source:
private <T> CompletableFuture<List<T>> sendSplitRequest(final MultiRequest<T> multiRequest) { final List<byte[]> keys = multiRequest.getKeys(); final Map<RawMemcacheClient, List<byte[]>> routing = Maps.newIdentityHashMap(); final List<RawMemcacheClient> routing2 = Lists.newArrayListWithCapacity(keys.size()); for (final byte[] key : keys) { final RawMemcacheClient client = getClient(key); List<byte[]> subKeys = routing.get(client); if (subKeys == null) { subKeys = Lists.newArrayList(); routing.put(client, subKeys); } subKeys.add(key); routing2.add(client); } final Map<RawMemcacheClient, CompletableFuture<List<T>>> futures = Maps.newIdentityHashMap(); for (final Map.Entry<RawMemcacheClient, List<byte[]>> entry : routing.entrySet()) { final List<byte[]> subKeys = entry.getValue(); final Request<List<T>> subRequest = multiRequest.create(subKeys); final RawMemcacheClient client = entry.getKey(); CompletableFuture<List<T>> send = client.send(subRequest); futures.put(client, send); } CompletableFuture<List<T>> cfs = futures.values().toArray(new CompletableFuture[futures.size()]); CompletableFuture<List<T>> result = CompletableFuture .allOf(cfs) .thenApply(__ -> Arrays.stream(cfs) .map(CompletableFuture::join) .flatMap(List::stream) .collect(Collectors.toList())); return result; }

Target:
private <T> CompletionStage<List<T>> sendSplitRequest(final MultiRequest<T> multiRequest) { final List<byte[]> keys = multiRequest.getKeys(); final Map<RawMemcacheClient, List<byte[]>> routing = Maps.newIdentityHashMap(); final List<RawMemcacheClient> routing2 = Lists.newArrayListWithCapacity(keys.size()); for (final byte[] key : keys) { final RawMemcacheClient client = getClient(key); List<byte[]> subKeys = routing.get(client); if (subKeys == null) { subKeys = Lists.newArrayList(); routing.put(client, subKeys); } subKeys.add(key); routing2.add(client); } final Map<RawMemcacheClient, CompletionStage<List<T>>> futures = Maps.newIdentityHashMap(); for (final Map.Entry<RawMemcacheClient, List<byte[]>> entry : routing.entrySet()) { final List<byte[]> subKeys = entry.getValue(); final Request<List<T>> subRequest = multiRequest.create(subKeys); final RawMemcacheClient client = entry.getKey(); CompletionStage<List<T>> send = client.send(subRequest); futures.put(client, send); } List<CompletableFuture<List<T>>> cfs = futures.values().stream() .map(CompletionStage::toCompletableFuture) .collect(Collectors.toList()); CompletableFuture<List<T>> result = CompletableFuture .allOf(cfs.toArray(new CompletableFuture[futures.size()])) .thenApply(__ -> cfs.stream() .map(CompletableFuture::join) .flatMap(List::stream) .collect(Collectors.toList())); return result; }