auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private Set<String> computeRoles(U user, T tenant, boolean isSystemTenant) { Set<String> roles = Sets.newTreeSet(); roles.addAll(user.getUserAccountData().getPermissions().getPermissions()); roles.addAll(tenant.getTenantData().getPermissions().getPermissions()); roles.add(UserInfo.PERMISSION_LOGGED_IN); if (Strings.isFilled(tenant.getTenantData().getAccountNumber())) { roles.add("tenant-" + tenant.getTenantData().getAccountNumber()); } Set<String> transformedRoles = transformRoles(roles); if (isSystemTenant && transformedRoles.contains(PERMISSION_MANAGE_SYSTEM)) { roles.add(PERMISSION_SYSTEM_TENANT); return applyAdditionalRolesProvider(user, tenant, transformRoles(roles)); } return applyAdditionalRolesProvider(user, tenant, transformedRoles); }

Target:
private Set<String> computeRoles(U user, T tenant, boolean isSystemTenant) { Set<String> roles = Sets.newTreeSet(); roles.addAll(user.getUserAccountData().getPermissions().getPermissions()); roles.addAll(tenant.getTenantData().getPermissions().getPermissions()); roles.add(UserInfo.PERMISSION_LOGGED_IN); if (Strings.isFilled(tenant.getTenantData().getAccountNumber())) { roles.add("tenant-" + tenant.getTenantData().getAccountNumber()); } Set<String> transformedRoles = transformRoles(roles); if (isSystemTenant && transformedRoles.contains(PERMISSION_MANAGE_SYSTEM)) { roles.add(PERMISSION_SYSTEM_TENANT); return transformRoles(roles); } return transformedRoles; }
Source:
public static <T> T fromJson(String jsonStr, Class<T> valueType) throws ParseJsonException { try { return mapper.readValue(jsonStr, valueType); } catch (Exception e) { e.printStackTrace(); throw new ParseJsonException("Failed to deserialize Object from Json string"); } }

Target:
public static <T> T fromJson(String jsonStr, Class<T> valueType) throws ParseJsonException { try { return mapper.readValue(jsonStr, valueType); } catch (Exception e) { throw new ParseJsonException("Failed to deserialize Object from Json string"); } }
Source:
public ValueHolder<V> compute(final K key, final BiFunction<? super K, ? super V, ? extends V> remappingFunction) { checkKeyType(key); return map.compute(key, new BiFunction<K, ValueHolder<V>, ValueHolder<V>>() { @Override public ValueHolder<V> apply(final K k, final ValueHolder<V> vValueHolder) { V computedValue = remappingFunction.apply(k, vValueHolder == null ? null : vValueHolder.value()); checkValueType(computedValue); return nullSafeValueHolder(computedValue); } }); }

Target:
public ValueHolder<V> compute(final K key, final BiFunction<? super K, ? super V, ? extends V> remappingFunction) { checkKey(key); final long now = timeSource.getTimeMillis(); return map.compute(key, new BiFunction<K, OnHeapValueHolder<V>, OnHeapValueHolder<V>>() { @Override public OnHeapValueHolder<V> apply(final K mappedKey, OnHeapValueHolder<V> mappedValue) { if (mappedValue != null && mappedValue.isExpired(now)) { mappedValue = null; } V computedValue = remappingFunction.apply(k, vValueHolder == null ? null : vValueHolder.value()); checkValue(computedValue); return nullSafeValueHolder(computedValue); } }); }
Source:
private Button button( final String text, final Command command, final ButtonType type ) { Button button = new Button( text, new ClickHandler() { @Override public void onClick( ClickEvent event ) { command.execute(); } } ); button.setType( type ); return button; }

Target:
Button button( final String text, final Command command, final ButtonType type ) { Button button = new Button( text, event -> command.execute() ); button.setType( type ); return button; }
Source:
public void testAccessTimeParam() { final AccessTimeParam p = new AccessTimeParam(AccessTimeParam.DEFAULT); assertEquals(-1L, p.getValue().longValue()); new AccessTimeParam(-1L); try { new AccessTimeParam(-2L); Assert.fail(); } catch(IllegalArgumentException e) { LOG.info("EXPECTED: " + e); } }

Target:
public void testAccessTimeParam() { final AccessTimeParam p = new AccessTimeParam(AccessTimeParam.DEFAULT); Assert.assertEquals(-1L, p.getValue().longValue()); new AccessTimeParam(-1L); try { new AccessTimeParam(-2L); Assert.fail(); } catch(IllegalArgumentException e) { LOG.info("EXPECTED: " + e); } }
Source:
private String getGeolocationsUrl(String deploymentUrl, String accountSid, Boolean xml) { if (deploymentUrl.endsWith("/")) { deploymentUrl = deploymentUrl.substring(0, deploymentUrl.length() - 1); } geolocationsUrl = deploymentUrl + "/2012-04-24/Accounts/" + accountSid + "/Geolocation"; if (!xml) { geolocationsUrl += ".json"; } return geolocationsUrl; }

Target:
private String getGeolocationsUrl(String deploymentUrl, String accountSid, Boolean xml) { deploymentUrl = evaluateDeploymentUrl(deploymentUrl); geolocationsUrl = deploymentUrl + apiVersionAccounts + accountSid + "/Geolocation"; if (!xml) { geolocationsUrl += ".json"; } return geolocationsUrl; }
Source:
public void visitEnd() { if (_containsSyntheticLambda) { String classToVisit = _methodInsnOwner.replace('/', '.'); SyntheticLambdaAnalyzer syntheticLambdaAnalyzer = new SyntheticLambdaAnalyzer(api, classToVisit, _methodInsnName); ClassReader cr = getClassReader(classToVisit); if (cr != null) { cr.accept(syntheticLambdaAnalyzer, 0); _inferredOperationConsumer.accept(new InferredOperation(syntheticLambdaAnalyzer.getInferredOperation())); _lineNumberConsumer.accept(syntheticLambdaAnalyzer.getLineNumber()); } } else { if (_methodInsnOpcode == Opcodes.INVOKESTATIC) { String functionName = Util.extractSimpleName(_methodInsnOwner, "/") + "::" + _methodInsnName; _inferredOperationConsumer.accept(new InferredOperation(functionName)); } else { String classToVisit = _lambdaSourcePointer._className.replace('/', '.'); FindMethodCallAnalyzer methodCallAnalyzer = new FindMethodCallAnalyzer(api, classToVisit, _lambdaSourcePointer, _methodInsnName); ClassReader cr = getClassReader(classToVisit); if (cr != null) { cr.accept(methodCallAnalyzer, 0); _inferredOperationConsumer.accept(new InferredOperation(methodCallAnalyzer.getInferredOperation())); } } } super.visitEnd(); }

Target:
public void visitEnd() { if (_containsSyntheticLambda) { String classToVisit = _methodInsnOwner.replace('/', '.'); SyntheticLambdaAnalyzer syntheticLambdaAnalyzer = new SyntheticLambdaAnalyzer(api, classToVisit, _methodInsnName); ClassReader cr = getClassReader(classToVisit); if (cr != null) { cr.accept(syntheticLambdaAnalyzer, 0); _inferredOperationConsumer.accept(new InferredOperation(syntheticLambdaAnalyzer.getInferredOperation())); int inferredLineNumber = syntheticLambdaAnalyzer.getLineNumber(); if (inferredLineNumber != -1) { _lineNumberConsumer.accept(inferredLineNumber); } } } else { if (_methodInsnOpcode == Opcodes.INVOKESTATIC) { String functionName = Util.extractSimpleName(_methodInsnOwner, "/") + "::" + _methodInsnName; _inferredOperationConsumer.accept(new InferredOperation(functionName)); } else { String classToVisit = _lambdaSourcePointer._className.replace('/', '.'); FindMethodCallAnalyzer methodCallAnalyzer = new FindMethodCallAnalyzer(api, classToVisit, _lambdaSourcePointer, _methodInsnName); ClassReader cr = getClassReader(classToVisit); if (cr != null) { cr.accept(methodCallAnalyzer, 0); _inferredOperationConsumer.accept(new InferredOperation(methodCallAnalyzer.getInferredOperation())); } } } super.visitEnd(); }
Source:
public Optional<String> switchBoard() { if (getLastOpenBoard().isPresent() && getAllBoards().size() > 1) { List<String> boardNames = getAllBoardNames(); int lastBoard = boardNames.indexOf(getLastOpenBoard().get()); int index = (lastBoard + 1) % boardNames.size(); setLastOpenBoard(boardNames.get(index)); } save(); return getLastOpenBoard(); }

Target:
public Optional<String> switchBoard() { if (getLastOpenBoard().isPresent() && getAllBoards().size() > 1) { List<String> boardNames = getAllBoardNames(); int lastBoard = boardNames.indexOf(getLastOpenBoard().get()); int index = (lastBoard + 1) % boardNames.size(); setLastOpenBoard(boardNames.get(index)); } return getLastOpenBoard(); }
Source:
public CasAssertionSecurityContext() { applicationContext = ApplicationContextLocator.getApplicationContext(); String propertyVal = applicationContext.getBean(CAS_COPY_ASSERT_ATTR_TO_USER_ATTR_BEAN, String.class); copyAssertionAttributesToUserAttributes = "true".equalsIgnoreCase(propertyVal); propertyVal = applicationContext.getBean(DECRYPT_CRED_TO_PWD, String.class); decryptCredentialToPassword = "true".equalsIgnoreCase(propertyVal); if (decryptCredentialToPassword) { String decryptCredentialToPasswordPrivateKey = applicationContext.getBean(DECRYPT_CRED_TO_PWD_KEY, String.class); if (key == null) { try { key = getPrivateKeyFromFile(decryptCredentialToPasswordPrivateKey); } catch (Exception e) { log.error("Cannot load key from file: {}", decryptCredentialToPasswordPrivateKey); e.printStackTrace(); } } if (cipher == null) { try { cipher = Cipher.getInstance(key.getAlgorithm()); } catch (Exception e) { log.error("Cannot create cipher for key from file: {}", decryptCredentialToPasswordPrivateKey); e.printStackTrace(); } } algorithm = applicationContext.getBean(DECRYPT_CRED_TO_PWD_ALG, String.class); } }

Target:
public CasAssertionSecurityContext() { applicationContext = ApplicationContextLocator.getApplicationContext(); String propertyVal = applicationContext.getBean(CAS_COPY_ASSERT_ATTR_TO_USER_ATTR_BEAN, String.class); copyAssertionAttributesToUserAttributes = Boolean.valueOf(propertyVal); propertyVal = applicationContext.getBean(DECRYPT_CRED_TO_PWD, String.class); decryptCredentialToPassword = Boolean.valueOf(propertyVal); if (decryptCredentialToPassword) { String decryptCredentialToPasswordPrivateKey = applicationContext.getBean(DECRYPT_CRED_TO_PWD_KEY, String.class); if (key == null) { try { key = getPrivateKeyFromFile(decryptCredentialToPasswordPrivateKey); } catch (Exception e) { log.error("Cannot load key from file: {}", decryptCredentialToPasswordPrivateKey, e); } } if (cipher == null) { try { cipher = Cipher.getInstance(key.getAlgorithm()); } catch (Exception e) { log.error("Cannot create cipher for key from file: {}", decryptCredentialToPasswordPrivateKey, e); } } algorithm = applicationContext.getBean(DECRYPT_CRED_TO_PWD_ALG, String.class); } }
Source:
private String dropTableIndex() { if (DbConnectionFactory.isMySql()) { return MYSQL_DROP_WORKFLOW_SCHEME_X_STRUCTURE_INDEX; } else if (DbConnectionFactory.isPostgres()) { return POSTGRES_DROP_WORKFLOW_SCHEME_X_STRUCTURE_INDEX; } else if (DbConnectionFactory.isMsSql()) { return MSSQL_DROP_WORKFLOW_SCHEME_X_STRUCTURE_INDEX; } else if (DbConnectionFactory.isOracle()) { return ORACLE_DROP_WORKFLOW_SCHEME_X_STRUCTURE_INDEX; } else { return null; } }

Target:
private String dropTableIndex() { String sql = null; if (DbConnectionFactory.isMySql()) { sql = MYSQL_DROP_WORKFLOW_SCHEME_X_STRUCTURE_INDEX; } else if (DbConnectionFactory.isPostgres()) { sql = POSTGRES_DROP_WORKFLOW_SCHEME_X_STRUCTURE_INDEX; } else if (DbConnectionFactory.isMsSql()) { sql = MSSQL_DROP_WORKFLOW_SCHEME_X_STRUCTURE_INDEX; } else if (DbConnectionFactory.isOracle()) { sql = ORACLE_DROP_WORKFLOW_SCHEME_X_STRUCTURE_INDEX; } return sql; }
Source:
protected String[] updateEnvironment(String[] envp, IProject project) { if (project == null) return envp; if (envp == null) envp = new String[0]; String ltPath = LinuxtoolsPathProperty.getInstance().getLinuxtoolsPath(project); String envpPath = getEnvpPath(envp); String systemPath = null; Map<String, String> systemEnvMap = null; try { systemEnvMap = RemoteProxyManager.getInstance().getEnv(project); String pathValue = systemEnvMap.get(PATH); if(pathValue != null) systemPath = PATH + "=" + pathValue; } catch (CoreException e) { e.printStackTrace(); } StringBuffer newPath = new StringBuffer(); newPath.append(PATH_EQUAL); if (ltPath != null && ltPath.length() > 0) { newPath.append(ltPath); newPath.append(SEPARATOR); } if (envpPath != null && envpPath.length() > 0) { newPath.append(envpPath); newPath.append(SEPARATOR); } if (systemPath != null && systemPath.length() > 0) { newPath.append(systemPath); newPath.append(SEPARATOR); } if (newPath.length() == PATH_EQUAL.length()) return envp; String[] newEnvp; if (envpPath != null) { newEnvp = new String[envp.length]; for (int i = 0; i < envp.length; i++) if (envp[i].startsWith(PATH_EQUAL)) newEnvp[i] = newPath.toString(); else newEnvp[i] = envp[i]; } else if(systemEnvMap != null) { Map<String, String> envVars = systemEnvMap; Set<String> keySet = envVars.keySet(); newEnvp = new String[envVars.size()]; int i = 0; for (String key : keySet) { newEnvp[i] = key + "=" + envVars.get(key); i++; } } else { newEnvp = new String[] {}; } return newEnvp; }

Target:
protected String[] updateEnvironment(String[] envp, IProject project) { if (project == null) return envp; if (envp == null) envp = new String[0]; String ltPath = LinuxtoolsPathProperty.getInstance().getLinuxtoolsPath(project); String envpPath = getEnvpPath(envp); String systemPath = null; Map<String, String> systemEnvMap = null; try { systemEnvMap = RemoteProxyManager.getInstance().getEnv(project); systemPath = systemEnvMap.get(PATH); } catch (CoreException e) { e.printStackTrace(); } StringBuffer newPath = new StringBuffer(); newPath.append(PATH_EQUAL); if (ltPath != null && ltPath.length() > 0) { newPath.append(ltPath); newPath.append(SEPARATOR); } if (envpPath != null && envpPath.length() > 0) { newPath.append(envpPath); newPath.append(SEPARATOR); } if (systemPath != null && systemPath.length() > 0) { newPath.append(systemPath); newPath.append(SEPARATOR); } if (newPath.length() == PATH_EQUAL.length()) return envp; String[] newEnvp; if (envpPath != null) { newEnvp = new String[envp.length]; for (int i = 0; i < envp.length; i++) if (envp[i].startsWith(PATH_EQUAL)) newEnvp[i] = newPath.toString(); else newEnvp[i] = envp[i]; } else if(systemEnvMap != null) { Map<String, String> envVars = systemEnvMap; Set<String> keySet = envVars.keySet(); newEnvp = new String[envVars.size()]; int i = 0; for (String key : keySet) { newEnvp[i] = key + "=" + envVars.get(key); i++; } } else { newEnvp = new String[] {}; } return newEnvp; }
Source:
public void repeatBrickTest() throws InterpretationException { checkSetUpBrickArrangement(); deleteBrickAtPosition(brickPosition); checkIfBrickAtPositionShowsString(1, R.string.brick_change_y_by); onView(withText(R.string.brick_loop_end)) .check(doesNotExist()); addLoopAtPosition(R.string.brick_repeat, brickPosition); onScriptList().atPosition(2) .perform(longClick()).perform(new GeneralSwipeAction(Swipe.FAST, GeneralLocation.TOP_CENTER, new CoordinatesProvider() { @Override public float[] calculateCoordinates(View view) { float[] coordinates = GeneralLocation.CENTER.calculateCoordinates(view); coordinates[1] = view.getContext().getResources().getDisplayMetrics().heightPixels; return coordinates; } }, Press.FINGER)); checkSetUpBrickArrangement(); }

Target:
public void repeatBrickTest() throws InterpretationException { checkSetUpBrickArrangement(); deleteBrickAtPosition(1); checkIfBrickAtPositionShowsString(1, R.string.brick_change_y_by); onView(withText(R.string.brick_loop_end)) .check(doesNotExist()); addBrickAtPosition(RepeatBrick.class, 1, R.string.category_control); dragBrickAtPositionToBottom(2); checkSetUpBrickArrangement(); }
Source:
void updateOrCreateDefaultStatefulBeanSessionTimeoutService(final OperationContext context, final ModelNode model) throws OperationFailedException { final long defaultSessionTimeout = EJB3SubsystemRootResourceDefinition.DEFAULT_STATEFUL_BEAN_SESSION_TIMEOUT.resolveModelAttribute(context, model).asLong(); final ServiceController<?> sc = context.getServiceRegistry(true).getService(SERVICE_NAME); if (sc != null) { final AtomicLong existingValue = (AtomicLong) sc.getValue(); existingValue.set(defaultSessionTimeout); } else { context.getServiceTarget().addService(SERVICE_NAME, new ValueService<>(new ImmediateValue<>(new AtomicLong(defaultSessionTimeout)))).install(); } }

Target:
void updateOrCreateDefaultStatefulBeanSessionTimeoutService(final OperationContext context, final ModelNode model) throws OperationFailedException { final long defaultSessionTimeout = EJB3SubsystemRootResourceDefinition.DEFAULT_STATEFUL_BEAN_SESSION_TIMEOUT.resolveModelAttribute(context, model).asLong(); final ServiceController<?> sc = context.getServiceRegistry(true).getRequiredService(SERVICE_NAME); final AtomicLong existingValue = (AtomicLong) sc.getValue(); existingValue.set(defaultSessionTimeout); }
Source:
private void handleVersion2(String name, Attributes attributes) throws SAXException { if (name.equals(TaskRepositoriesExternalizer.ELEMENT_TASK_REPOSITORY) && currentRepository == null) { currentRepository = createRepository(attributes); } else if (name.equals(TaskRepositoriesExternalizer.ELEMENT_PROPERTY) && currentRepository != null) { String key = org.eclipse.mylyn.internal.commons.core.XmlStringConverter.convertXmlToString(attributes.getValue(TaskRepositoriesExternalizer.PROPERTY_KEY)); String value = org.eclipse.mylyn.internal.commons.core.XmlStringConverter.convertXmlToString(attributes.getValue(TaskRepositoriesExternalizer.PROPERTY_VALUE)); currentRepository.setProperty(key, value); } }

Target:
private void handleVersion2(String name, Attributes attributes) throws SAXException { if (name.equals(TaskRepositoriesExternalizer.ELEMENT_TASK_REPOSITORY) && currentRepository == null) { currentRepository = createRepository(attributes); } else if (name.equals(TaskRepositoriesExternalizer.ELEMENT_PROPERTY) && currentRepository != null) { String key = attributes.getValue(TaskRepositoriesExternalizer.PROPERTY_KEY); String value = attributes.getValue(TaskRepositoriesExternalizer.PROPERTY_VALUE); if (key != null && value != null) { currentRepository.setProperty(key, value); } } }
Source:
public void copy() throws IOException { File srcFile = new File(repo.getWorkTree(), path + "/" + src); File destFile = new File(repo.getWorkTree(), dest); try (FileInputStream input = new FileInputStream(srcFile); FileOutputStream output = new FileOutputStream(destFile)) { FileChannel channel = input.getChannel(); output.getChannel().transferFrom(channel, 0, channel.size()); destFile.setExecutable(srcFile.canExecute()); } }

Target:
public void copy() throws IOException { File srcFile = new File(repo.getWorkTree(), path + "/" + src); File destFile = new File(repo.getWorkTree(), dest); try (FileInputStream input = new FileInputStream(srcFile); FileOutputStream output = new FileOutputStream(destFile)) { FileChannel channel = input.getChannel(); output.getChannel().transferFrom(channel, 0, channel.size()); } destFile.setExecutable(srcFile.canExecute()); }
Source:
public void testRemove() { MemoryNode node = new MemoryNode(Mods.NAME); node.add(new MemoryNode("http://names.example/alice")); MemoryNode bob = new MemoryNode("http://names.example/bob"); node.add(bob); node.add(new MemoryNode("http://names.example/charlie")); assertThat(node.getEnumerated().stream().mapToInt(r -> r.isAny() ? 1 : 0).sum(), is(3)); assertThat(node.remove(bob), is(true)); assertThat(node.getEnumerated().stream().mapToInt(r -> r.isAny() ? 1 : 0).sum(), is(2)); assertThat(node.remove(bob), is(false)); assertThat(node.getEnumerated().stream().mapToInt(r -> r.isAny() ? 1 : 0).sum(), is(2)); }

Target:
public void testRemove() { MemoryNode node = new MemoryNode(MODS_NAME); node.add(new MemoryNode("http://names.example/alice")); MemoryNode bob = new MemoryNode("http://names.example/bob"); node.add(bob); node.add(new MemoryNode("http://names.example/charlie")); assertThat(node.getEnumerated().stream().mapToInt(r -> r.isAny() ? 1 : 0).sum(), is(3)); assertThat(node.remove(bob), is(true)); assertThat(node.getEnumerated().stream().mapToInt(r -> r.isAny() ? 1 : 0).sum(), is(2)); assertThat(node.remove(bob), is(false)); assertThat(node.getEnumerated().stream().mapToInt(r -> r.isAny() ? 1 : 0).sum(), is(2)); }
Source:
public void testEjbClassAvailableInServlet(@ArquillianResource(HelloWorldServlet.class) URL baseUrl) throws Exception { final HttpClient httpClient = HttpClientBuilder.create().build(); final String message = "JBossAS7"; final String requestURL = baseUrl.toURI() + HelloWorldServlet.URL_PATTERN + "?" + HelloWorldServlet.PARAMETER_NAME + "=" + message; final HttpGet request = new HttpGet(requestURL); final HttpResponse response = httpClient.execute(request); final HttpEntity entity = response.getEntity(); Assert.assertNotNull("Response message from servlet was null", entity); final String responseMessage = EntityUtils.toString(entity); Assert.assertEquals("Unexpected echo message from servlet", message, responseMessage); }

Target:
public void testEjbClassAvailableInServlet(@ArquillianResource(HelloWorldServlet.class) URL baseUrl) throws Exception { try (final CloseableHttpClient httpClient = HttpClients.createDefault()) { final String message = "JBossAS7"; final String requestURL = baseUrl.toURI() + HelloWorldServlet.URL_PATTERN + "?" + HelloWorldServlet.PARAMETER_NAME + "=" + message; final HttpGet request = new HttpGet(requestURL); final HttpResponse response = httpClient.execute(request); final HttpEntity entity = response.getEntity(); Assert.assertNotNull("Response message from servlet was null", entity); final String responseMessage = EntityUtils.toString(entity); Assert.assertEquals("Unexpected echo message from servlet", message, responseMessage); } }
Source:
public void setConstraints(int constraints) { this.constraints = constraints; }

Target:
public void setConstraints(int constraints) { System.out.println("TextEditor::setConstraints(int) not implemented"); }
Source:
public void stop() { System.gc(); }

Target:
public void stop() { }
Source:
private org.wso2.carbon.mediator.bam.BamMediator createBAMMediator( EsbNode subject, TransformationInfo information) throws Exception { Assert.isTrue(subject instanceof BAMMediator, "Invalid subject."); BAMMediator visualBAMMediator = (BAMMediator) subject; org.wso2.carbon.mediator.bam.BamMediator bamMediator = new org.wso2.carbon.mediator.bam.BamMediator(); setCommonProperties(bamMediator, visualBAMMediator); if (StringUtils.isNotEmpty(visualBAMMediator.getServerProfile())) { bamMediator.setServerProfile(visualBAMMediator.getServerProfile()); } else { throw new IllegalArgumentException("BAM Mediator Error : Server Profile Name is required"); } if (StringUtils.isNotEmpty(visualBAMMediator.getStreamName())) { if (StringUtils.isNotEmpty(visualBAMMediator.getStreamVersion())) { StreamConfiguration streamConfiguration = new StreamConfiguration(); streamConfiguration.setName(visualBAMMediator.getStreamName()); streamConfiguration.setVersion(visualBAMMediator.getStreamVersion()); bamMediator.getStream().setStreamConfiguration(streamConfiguration); } else { throw new IllegalArgumentException("BAM Mediator Error : Stream Version is required"); } } else { throw new IllegalArgumentException("BAM Mediator Error : Stream Name is required"); } return bamMediator; }

Target:
private org.wso2.carbon.mediator.bam.BamMediator createBAMMediator( EsbNode subject, TransformationInfo information) throws Exception { Assert.isTrue(subject instanceof BAMMediator, "Invalid subject."); BAMMediator visualBAMMediator = (BAMMediator) subject; org.wso2.carbon.mediator.bam.BamMediator bamMediator = new org.wso2.carbon.mediator.bam.BamMediator(); setCommonProperties(bamMediator, visualBAMMediator); bamMediator.setServerProfile(visualBAMMediator.getServerProfile()); StreamConfiguration streamConfiguration = new StreamConfiguration(); streamConfiguration.setName(visualBAMMediator.getStreamName()); streamConfiguration.setVersion(visualBAMMediator.getStreamVersion()); bamMediator.getStream().setStreamConfiguration(streamConfiguration); return bamMediator; }
Source:
private static void writeDates(JsonWriter writer, ProjectAnalysis analysis, System2 system2) { analysis.getAnalysis().ifPresent(a -> writer.propDateTime("analysedAt", a.getDate())); if (analysis.getAnalysis().isPresent()) { writer.propDateTime("changedAt", analysis.getAnalysis().get().getDate()); } else { writer.propDateTime("changedAt", new Date(system2.now())); } }

Target:
private static void writeDates(JsonWriter writer, ProjectAnalysis analysis, System2 system2) { analysis.getAnalysis().ifPresent(a -> writer.propDateTime("analysedAt", a.getDate())); writer.propDateTime("changedAt", analysis.getAnalysis().map(Analysis::getDate).orElseGet(() -> new Date(system2.now()))); }
Source:
private static boolean cleanlyDelete(FileSystem fs, Path root, Path path, boolean useTrash) { Preconditions.checkNotNull(fs, "File system cannot be null"); Preconditions.checkNotNull(root, "Root path cannot be null"); Preconditions.checkNotNull(path, "Path to delete cannot be null"); try { boolean deleted; Path relativePath; if (path.isAbsolute()) { relativePath = new Path(root.toUri().relativize(path.toUri())); } else { relativePath = path; } if (relativePath.isAbsolute()) { LOG.debug("Deleting path {}", path); deleted = useTrash ? Trash.moveToAppropriateTrash(fs, path, fs.getConf()) : fs.delete(path, true ); } else { Path absolute = new Path(root, relativePath); LOG.debug("Deleting path {}", absolute); deleted = useTrash ? Trash.moveToAppropriateTrash(fs, absolute, fs.getConf()) : fs.delete(absolute, true ); for (Path current = absolute.getParent(); !current.equals(root) && !(current.getParent() == null); current = current.getParent()) { final FileStatus[] stats = fs.listStatus(current); if (stats == null || stats.length == 0) { LOG.debug("Deleting empty path {}", current); deleted = (useTrash ? Trash.moveToAppropriateTrash(fs, current, fs.getConf()) : fs.delete(current, true)) || deleted; } else { break; } } } return deleted; } catch (IOException ex) { throw new DatasetIOException("Could not cleanly delete path:" + path, ex); } }

Target:
private static boolean cleanlyDelete(FileSystem fs, Path root, Path path, boolean useTrash) { Preconditions.checkNotNull(fs, "File system cannot be null"); Preconditions.checkNotNull(root, "Root path cannot be null"); Preconditions.checkNotNull(path, "Path to delete cannot be null"); try { boolean deleted; Path relativePath; if (path.isAbsolute()) { relativePath = new Path(root.toUri().relativize(path.toUri())); } else { relativePath = path; } if (relativePath.isAbsolute()) { LOG.debug("Deleting path {}", path); deleted = useTrash ? Trash.moveToAppropriateTrash(fs, path, fs.getConf()) : fs.delete(path, true ); } else { Path absolute = new Path(root, relativePath); LOG.debug("Deleting path {}", absolute); deleted = useTrash ? Trash.moveToAppropriateTrash(fs, absolute, fs.getConf()) : fs.delete(absolute, true ); for (Path current = absolute.getParent(); !current.equals(root) && !(current.getParent() == null); current = current.getParent()) { final FileStatus[] stats = fs.listStatus(current); if (stats == null || stats.length == 0) { LOG.debug("Deleting empty path {}", current); deleted = fs.delete(current, true) || deleted; } else { break; } } } return deleted; } catch (IOException ex) { throw new DatasetIOException("Could not cleanly delete path:" + path, ex); } }
Source:
public void clear() { timeStamps = null; values = null; }

Target:
public void clear() { timeStamps.clear(); values.clear(); key = null; }
Source:
public void testRestoreWithTrustedEmptySnapFiles() throws Exception { FileTxnSnapLog.setTrustEmptySnapshotFlag(true); runTest(false, true); assertFalse("Trust empty snapshot flag should be reset after first use.", FileTxnSnapLog.getTrustEmptySnapshotFlag()); }

Target:
public void testRestoreWithTrustedEmptySnapFiles() throws Exception { runTest(false, true); }
Source:
private QueryParams buildQueryParams(GridSettings settings, List<Order> orderList) { int page = (settings.getPage() == null) ? 1 : settings.getPage(); int pageSize = (settings.getPage() == null) ? 10 : settings.getRows(); return new QueryParams(page, pageSize, orderList); }

Target:
private QueryParams buildQueryParams(GridSettings settings, List<Order> orderList) { int page = (settings.getPage() == null) ? 1 : settings.getPage(); int pageSize = (settings.getRows() == null) ? 10 : settings.getRows(); return new QueryParams(page, pageSize, orderList); }
Source:
private boolean checkAggregates(Offer offer, NodeTask taskToLaunch, int ports, double cpus, double mem) { final ServiceResourceProfile profile = taskToLaunch.getProfile(); final String taskPrefix = taskToLaunch.getTaskPrefix(); final double aggrCpu = profile.getAggregateCpu() + profile.getExecutorCpu(); final double aggrMem = profile.getAggregateMemory() + profile.getExecutorMemory(); final TaskConstraints taskConstraints = taskConstraintsManager.getConstraints(taskPrefix); if (aggrCpu <= cpus && aggrMem <= mem && taskConstraints.portsCount() <= ports) { return true; } else { LOGGER.error("Offer not sufficient for task with, cpu: {}, memory: {}, ports: {}", aggrCpu, aggrMem, ports); return false; } }

Target:
private boolean checkAggregates(Offer offer, NodeTask taskToLaunch, int ports, double cpus, double mem) { final ServiceResourceProfile profile = taskToLaunch.getProfile(); final String taskPrefix = taskToLaunch.getTaskPrefix(); final double aggrCpu = profile.getAggregateCpu() + profile.getExecutorCpu(); final double aggrMem = profile.getAggregateMemory() + profile.getExecutorMemory(); final TaskConstraints taskConstraints = taskConstraintsManager.getConstraints(taskPrefix); if (aggrCpu <= cpus && aggrMem <= mem && taskConstraints.portsCount() <= ports) { return true; } else { LOGGER.debug("Offer insufficient for task with, cpu: {}, memory: {}, ports: {}", aggrCpu, aggrMem, ports); return false; } }
Source:
public void testLayerDisabledServiceResponse() throws Exception { enableWMS(); String layerName = "cite:RoadSegments"; LayerInfo linfo = getCatalog().getLayerByName(layerName); ResourceInfo ri = linfo.getResource(); ri.setServiceConfiguration(true); ri.setDisabledServices(new ArrayList<>(Arrays.asList("WMS"))); getCatalog().save(ri); getCatalog().save(linfo); Document doc = getAsDOM( "wms?bbox=" + "-180,-90,180,90" + "&layers=" + layerName + "&Format=image/png" + "&request=GetMap" + "&width=550" + "&height=250" + "&srs=EPSG:4326"); assertEquals("ServiceExceptionReport", doc.getDocumentElement().getNodeName()); }

Target:
public void testLayerDisabledServiceResponse() throws Exception { enableWMS(); String layerName = "cite:RoadSegments"; FeatureTypeInfo ftinfo = getCatalog().getFeatureTypeByName(layerName); ftinfo.setServiceConfiguration(true); ftinfo.setDisabledServices(new ArrayList<>(Arrays.asList("WMS"))); getCatalog().save(ftinfo); Document doc = getAsDOM( "wms?bbox=" + "-180,-90,180,90" + "&layers=" + layerName + "&Format=image/png" + "&request=GetMap" + "&width=550" + "&height=250" + "&srs=EPSG:4326"); assertEquals("ServiceExceptionReport", doc.getDocumentElement().getNodeName()); }
Source:
protected void clearErrorMessage() { errorContainer.setVisibility(View.GONE); notificationButtonView.setVisibility(View.GONE); }

Target:
protected void clearErrorMessage() { errorContainer.setVisibility(View.GONE); }
Source:
private void decorateResourceMapping(Object element, IDecoration decoration) throws CoreException { @SuppressWarnings("restriction") ResourceMapping mapping = Utils.getResourceMapping(element); boolean isWorkingSet = mapping.getModelObject() instanceof IWorkingSet; IDecoratableResource decoRes; try { if (isWorkingSet) { decoRes = new DecoratableWorkingSet(mapping); } else { decoRes = new DecoratableResourceMapping(mapping); } } catch (IOException e) { throw new CoreException(Activator.createErrorStatus( NLS.bind(UIText.Decorator_exceptionMessage, element), e)); } if (!decoRes.isTracked() && isWorkingSet) return; final DecorationHelper helper = new DecorationHelper( Activator.getDefault().getPreferenceStore()); helper.decorate(decoration, decoRes); }

Target:
private void decorateResourceMapping(Object element, IDecoration decoration) throws CoreException { @SuppressWarnings("restriction") ResourceMapping mapping = Utils.getResourceMapping(element); if (mapping == null) { return; } boolean isWorkingSet = mapping.getModelObject() instanceof IWorkingSet; IDecoratableResource decoRes; try { if (isWorkingSet) { decoRes = new DecoratableWorkingSet(mapping); } else { decoRes = new DecoratableResourceMapping(mapping); } } catch (IOException e) { throw new CoreException(Activator.createErrorStatus( NLS.bind(UIText.Decorator_exceptionMessage, element), e)); } if (!decoRes.isTracked() && isWorkingSet) { return; } final DecorationHelper helper = new DecorationHelper( Activator.getDefault().getPreferenceStore()); helper.decorate(decoration, decoRes); }
Source:
private Map<String, String> createMigrationInfo() { Map<String, String> migrationInfo = new HashMap<>(); P parameters = getParameters(); migrationInfo.put(VdsProperties.vm_guid, parameters.getVmId().toString()); migrationInfo.put(VdsProperties.src, String.format("%1$s", parameters.getSrcHost())); migrationInfo.put(VdsProperties.dst, String.format("%1$s", parameters.getDstHost())); migrationInfo.put(VdsProperties.method, VdsProperties.migrationMethodtoString(parameters.getMigrationMethod())); migrationInfo.put("abortOnError", Boolean.TRUE.toString()); migrationInfo.put(VdsProperties.TUNNELED, Boolean.toString(parameters.isTunnelMigration())); if (StringUtils.isNotBlank(parameters.getDstQemu())) { migrationInfo.put(VdsProperties.DST_QEMU, parameters.getDstQemu()); } if (parameters.getMigrationDowntime() != 0) { migrationInfo.put(VdsProperties.MIGRATION_DOWNTIME, Integer.toString(parameters.getMigrationDowntime())); } if (parameters.getAutoConverge() != null) { migrationInfo.put(VdsProperties.AUTO_CONVERGE, parameters.getAutoConverge().toString()); } if (parameters.getMigrateCompressed() != null) { migrationInfo.put(VdsProperties.MIGRATE_COMPRESSED, parameters.getMigrateCompressed().toString()); } if (parameters.getConsoleAddress() != null) { migrationInfo.put(VdsProperties.CONSOLE_ADDRESS, parameters.getConsoleAddress()); } return migrationInfo; }

Target:
private Map<String, String> createMigrationInfo() { Map<String, String> migrationInfo = new HashMap<>(); P parameters = getParameters(); migrationInfo.put(VdsProperties.vm_guid, parameters.getVmId().toString()); migrationInfo.put(VdsProperties.src, String.format("%1$s", parameters.getSrcHost())); migrationInfo.put(VdsProperties.dst, String.format("%1$s", parameters.getDstHost())); migrationInfo.put(VdsProperties.method, VdsProperties.migrationMethodtoString(parameters.getMigrationMethod())); migrationInfo.put(VdsProperties.TUNNELED, Boolean.toString(parameters.isTunnelMigration())); migrationInfo.put("abortOnError", Boolean.TRUE.toString()); if (StringUtils.isNotBlank(parameters.getDstQemu())) { migrationInfo.put(VdsProperties.DST_QEMU, parameters.getDstQemu()); } if (parameters.getMigrationDowntime() != 0) { migrationInfo.put(VdsProperties.MIGRATION_DOWNTIME, Integer.toString(parameters.getMigrationDowntime())); } if (parameters.getAutoConverge() != null) { migrationInfo.put(VdsProperties.AUTO_CONVERGE, parameters.getAutoConverge().toString()); } if (parameters.getMigrateCompressed() != null) { migrationInfo.put(VdsProperties.MIGRATE_COMPRESSED, parameters.getMigrateCompressed().toString()); } if (parameters.getConsoleAddress() != null) { migrationInfo.put(VdsProperties.CONSOLE_ADDRESS, parameters.getConsoleAddress()); } return migrationInfo; }
Source:
public void testRoundRobinBalancer() { RandomLoadBalancerStrategyFactory lbFactory = new RandomLoadBalancerStrategyFactory(); RandomLoadBalancerStrategy rrLoadBalancer = lbFactory.newLoadBalancer(null); Map<Integer, PartitionData> partitionDataMap = new HashMap<Integer, PartitionData>(2); partitionDataMap.put(DefaultPartitionAccessor.DEFAULT_PARTITION_ID, new PartitionData(1d)); TrackerClient trackerClient1 = Mockito.mock(TrackerClient.class); TrackerClient trackerClient2 = Mockito.mock(TrackerClient.class); Map<URI, TrackerClient> trackerClients = new HashMap<>(); URI uri1 = URI.create("http://cluster-1/test"); URI uri2 = URI.create("http://cluster-1/test"); trackerClients.put(uri1, trackerClient1); trackerClients.put(uri2, trackerClient2); for (int i = 0; i < 100; ++i) { assertNotNull(rrLoadBalancer.getTrackerClient(null, new RequestContext(), 0, DefaultPartitionAccessor.DEFAULT_PARTITION_ID, trackerClients)); } }

Target:
public void testRoundRobinBalancer() { RandomLoadBalancerStrategyFactory lbFactory = new RandomLoadBalancerStrategyFactory(); RandomLoadBalancerStrategy rrLoadBalancer = lbFactory.newLoadBalancer(null); Map<Integer, PartitionData> partitionDataMap = new HashMap<Integer, PartitionData>(2); partitionDataMap.put(DefaultPartitionAccessor.DEFAULT_PARTITION_ID, new PartitionData(1d)); TrackerClient trackerClient1 = Mockito.mock(TrackerClient.class); TrackerClient trackerClient2 = Mockito.mock(TrackerClient.class); Map<URI, TrackerClient> trackerClients = new HashMap<>(); URI uri1 = URI.create("http://cluster-1/test"); URI uri2 = URI.create("http://cluster-2/test"); trackerClients.put(uri1, trackerClient1); trackerClients.put(uri2, trackerClient2); for (int i = 0; i < 100; ++i) { assertNotNull(rrLoadBalancer.getTrackerClient(null, new RequestContext(), 0, DefaultPartitionAccessor.DEFAULT_PARTITION_ID, trackerClients)); } }
Source:
public String get(String name, ParcelableProxy proxy) throws QueryFailedException { throw new UnsupportedOperationException("Returning armored key from Web Key Directory not supported"); }

Target:
public String get(String name, ParcelableProxy proxy) { throw new UnsupportedOperationException("Returning armored key from Web Key Directory not supported"); }
Source:
public void testGetTaskDefinitionTags() throws Exception { final List<Tag> expected = ImmutableList.of( new Tag().withKey("k1").withValue("v1"), new Tag().withKey("k2").withValue("v2") ); final ListTagsForResourceResult result = new ListTagsForResourceResult() .withTags(expected); doReturn(result).when(rawEcsClient).listTagsForResource(any(ListTagsForResourceRequest.class)); List<Tag> tags = ecsClient.getTaskDefinitionTags("my_task_def_arn"); assertEquals(expected.size(), tags.size()); assertEquals(expected.get(0), tags.get(0)); assertEquals(expected.get(1), tags.get(1)); }

Target:
public void testGetTaskDefinitionTags() throws Exception { final List<Tag> expected = ImmutableList.of( new Tag().withKey("k1").withValue("v1"), new Tag().withKey("k2").withValue("v2") ); final ListTagsForResourceRequest request = new ListTagsForResourceRequest() .withResourceArn("my_task_def_arn"); final ListTagsForResourceResult result = new ListTagsForResourceResult() .withTags(expected); doReturn(result).when(rawEcsClient).listTagsForResource(request); List<Tag> tags = ecsClient.getTaskDefinitionTags(request.getResourceArn()); assertEquals(expected.size(), tags.size()); assertEquals(expected.get(0), tags.get(0)); assertEquals(expected.get(1), tags.get(1)); }
Source:
public BucketCache(final int numberBuckets, final Graph<SequenceSegment> graph) { this.numberBuckets = (int) Math.pow(2, Math.ceil(Math.log(numberBuckets) / Math.log(2))); this.graph = graph; maxUnifiedEnd = getMaxUnifiedEnd(); bucketWidth = maxUnifiedEnd / this.numberBuckets; cacheGraph(); }

Target:
public BucketCache(final int numberBuckets, final Graph<SequenceSegment> graph) { this.numberBuckets = (int) Math.round(Math.pow(2, Math.ceil(Math.log(numberBuckets) / Math.log(2)))); this.graph = graph; maxUnifiedEnd = getMaxUnifiedEnd(); bucketWidth = maxUnifiedEnd / this.numberBuckets; cacheGraph(); }
Source:
protected R performUpdate(R incoming, EntityIdResolver<Guid> entityResolver, VdcActionType update, ParametersProvider<R, Q> updateProvider) { Q entity = doUpdate(incoming, entityResolver, update, updateProvider); R model = map(entity); deprecatedPopulate(model, entity); return addLinks(doPopulate(model, entity)); }

Target:
protected R performUpdate(R incoming, EntityIdResolver<Guid> entityResolver, VdcActionType update, ParametersProvider<R, Q> updateProvider) { Q entity = getEntity(entityResolver, true); validateUpdate(incoming, map(entity)); entity = doUpdate(incoming, entity, entityResolver, update, updateProvider); R model = map(entity); deprecatedPopulate(model, entity); return addLinks(doPopulate(model, entity)); }
Source:
public List<Connection> getTransitivelyConnectedElements(EObject element, EObject traceModel, int maximumDepth) { ArrayList<Object> accumulator = new ArrayList<>(); return getTransitivelyConnectedElements(element, traceModel, accumulator, DEFAULT_INITIAL_TRANSITIVITY_DEPTH, maximumDepth); }

Target:
public List<Connection> getTransitivelyConnectedElements(EObject element, EObject traceModel, int maximumDepth) { List<Object> accumulator = new ArrayList<>(); return getTransitivelyConnectedElements(element, traceModel, accumulator, DEFAULT_INITIAL_TRANSITIVITY_DEPTH, maximumDepth); }
Source:
public void close() { currentValue = -1; currentValueCt = -1; currentValueIsRepeated = false; thereIsABufferedValue = false; isFirst = true; bitWriter.close(); }

Target:
public void close() { bitWriter.close(); }
Source:
protected void unsetNotificationSender(NotificationSender notificationSender) { if (log.isDebugEnabled()) { log.debug("Setting notification sender in Entitlement bundle"); } this.notificationSender = null; }

Target:
protected void unsetNotificationSender(NotificationSender notificationSender) { if (log.isDebugEnabled()) { log.debug("Setting notification sender"); } TOTPManagerComponent.notificationSender = null; }
Source:
default Stream<T> stream() { final Spliterator<T> s = Spliterators.spliteratorUnknownSize(this, Spliterator.ORDERED); return StreamSupport.stream(s, false); }

Target:
default Stream<T> stream() { final Spliterator<T> s = Spliterators.spliteratorUnknownSize(this, Spliterator.ORDERED); return StreamSupport.stream(s, false).onClose(this::close); }
Source:
public String toString() { if (this.alarms.isEmpty()) { return String.format("DlmsPushNotification [device = %s, trigger type = %s]", this.equipmentIdentifier, this.triggerType); } else { return String.format("DlmsPushNotification [device = %s, trigger type = %s, alarms=%s]", this.equipmentIdentifier, this.triggerType, this.alarms); } }

Target:
public String toString() { return String.format("DlmsPushNotification [device = %s, trigger type = %s, alarms=%s]", this.equipmentIdentifier, this.triggerType, this.alarms); }
Source:
public void testDelayedChannelPutSuccess() throws Exception { VerifiableProperties vProps = getNonBlockingRouterProperties(); router = new NonBlockingRouter(new RouterConfig(vProps), new NonBlockingRouterMetrics(new MetricRegistry()), new MockNetworkClientFactory(vProps, mockSelectorState, MAX_PORTS_PLAIN_TEXT, MAX_PORTS_SSL, CHECKOUT_TIMEOUT_MS, mockServerLayout, mockTime), new LoggingNotificationSystem(), mockClusterMap, mockTime); int blobSize = chunkSize * random.nextInt(10) + 1; RequestAndResult requestAndResult = new RequestAndResult(blobSize); requestAndResultsList.add(requestAndResult); MockReadableStreamChannel putChannel = new MockReadableStreamChannel(blobSize); FutureResult<String> future = (FutureResult<String>) router .putBlob(requestAndResult.putBlobProperties, requestAndResult.putUserMetadata, putChannel, null); ByteBuffer src = ByteBuffer.wrap(requestAndResult.putContent); int pushedSoFar = 0; while (pushedSoFar < blobSize && !future.isDone()) { int toPush = random.nextInt(blobSize - pushedSoFar + 1); ByteBuffer buf = ByteBuffer.allocate(toPush); src.get(buf.array()); putChannel.write(buf); Thread.yield(); pushedSoFar += toPush; } future.await(); requestAndResult.result = future; assertSuccess(); assertCloseCleanup(); }

Target:
public void testDelayedChannelPutSuccess() throws Exception { router = getNonBlockingRouter(); int blobSize = chunkSize * random.nextInt(10) + 1; RequestAndResult requestAndResult = new RequestAndResult(blobSize); requestAndResultsList.add(requestAndResult); MockReadableStreamChannel putChannel = new MockReadableStreamChannel(blobSize); FutureResult<String> future = (FutureResult<String>) router .putBlob(requestAndResult.putBlobProperties, requestAndResult.putUserMetadata, putChannel, null); ByteBuffer src = ByteBuffer.wrap(requestAndResult.putContent); int pushedSoFar = 0; while (pushedSoFar < blobSize && !future.isDone()) { int toPush = random.nextInt(blobSize - pushedSoFar + 1); ByteBuffer buf = ByteBuffer.allocate(toPush); src.get(buf.array()); putChannel.write(buf); Thread.yield(); pushedSoFar += toPush; } future.await(); requestAndResult.result = future; assertSuccess(); assertCloseCleanup(); }
Source:
protected void sendTuple(T tuple) { if ( alreadyInKafka(tuple) ) { return; } try { getProducer().send(new ProducerRecord<>(getTopic(), key, tuple)).get(); } catch (InterruptedException e) { throw new RuntimeException(e); } catch (ExecutionException e) { throw new RuntimeException(e); } }

Target:
protected void sendTuple(T tuple) { if ( alreadyInKafka(tuple) ) { return; } getProducer().send(new ProducerRecord<>(getTopic(), key, tuple),new Callback() { public void onCompletion(RecordMetadata metadata, Exception e) { if (e != null) { logger.info("Wrting to Kafka failed with an exception {}" + e.getMessage()); throw new RuntimeException(e); } } }); }
Source:
public synchronized void send(String destination, DatastreamProducerRecord record, SendCallback onComplete) { if (_unrecoverableError != null) { throw _unrecoverableError; } List<EventData> events = record.getEvents().stream().map(x -> createEventData(x.getValue())).collect(Collectors.toList()); int partition = record.getPartition().orElse(0); List<CompletableFuture<Void>> sendResults = events.stream().map(x -> sendToPartition(x, partition)).collect(Collectors.toList()); DatastreamRecordMetadata recordMetadata = new DatastreamRecordMetadata(record.getCheckpoint(), "", partition); CompletableFuture<?>[] allsendResults = new CompletableFuture<?>[events.size()]; sendResults.toArray(allsendResults); CompletableFuture<Void> pendingFuture = CompletableFuture.allOf(allsendResults).handle((aVoid, throwable) -> { if (throwable instanceof Error) { LOG.error("send failed with unrecoverable error", throwable); _unrecoverableError = (Error) throwable; close(); _ehClient = null; } else { onComplete.onCompletion(recordMetadata, (Exception) throwable); } return aVoid; }); _pendingFutures.add(pendingFuture); pendingFuture.thenRun(() -> _pendingFutures.remove(pendingFuture)); }

Target:
public synchronized void send(String destination, DatastreamProducerRecord record, SendCallback onComplete) { if (_unrecoverableError != null) { throw _unrecoverableError; } List<EventData> events = record.getEvents().stream().map(x -> createEventData(x.getValue())).collect(Collectors.toList()); if (!record.getPartition().isPresent()) { String msg = "Event hub transport provider requires partition to be specified in DatastreamProducerRecord"; LOG.error(msg); throw new DatastreamRuntimeException(msg); } int partition = record.getPartition().get(); List<CompletableFuture<Void>> sendResults = events.stream().map(x -> sendToPartition(x, partition)).collect(Collectors.toList()); DatastreamRecordMetadata recordMetadata = new DatastreamRecordMetadata(record.getCheckpoint(), "", partition); CompletableFuture<?>[] allsendResults = new CompletableFuture<?>[events.size()]; sendResults.toArray(allsendResults); CompletableFuture<Void> pendingFuture = CompletableFuture.allOf(allsendResults).handle((aVoid, throwable) -> { if (throwable instanceof Error) { LOG.error("send failed with unrecoverable error", throwable); _unrecoverableError = (Error) throwable; close(); _ehClient = null; } else { onComplete.onCompletion(recordMetadata, (Exception) throwable); } return aVoid; }); _pendingFutures.add(pendingFuture); pendingFuture.thenRun(() -> _pendingFutures.remove(pendingFuture)); }