auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
void transactionMessageSendAndCompleteTransaction(MessagingEntityType entityType, boolean isCommit) { setSenderAndReceiver(entityType, 0, false); final boolean isSessionEnabled = false; final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, false); AtomicReference<ServiceBusTransactionContext> transaction = new AtomicReference<>(); StepVerifier.create(sender.createTransaction()) .assertNext(txn -> { transaction.set(txn); assertNotNull(transaction); }) .verifyComplete(); assertNotNull(transaction.get()); StepVerifier.create(sender.send(message, transaction.get())) .verifyComplete(); if (isCommit) { StepVerifier.create(sender.commitTransaction(transaction.get()).delaySubscription(Duration.ofSeconds(1))) .verifyComplete(); StepVerifier.create(receiveAndDeleteReceiver.receive().next()) .assertNext(receivedMessage -> { assertMessageEquals(receivedMessage, messageId, isSessionEnabled); messagesPending.decrementAndGet(); }) .verifyComplete(); } else { StepVerifier.create(sender.rollbackTransaction(transaction.get()).delaySubscription(Duration.ofSeconds(1))) .verifyComplete(); } }

Target:
void transactionMessageSendAndCompleteTransaction(MessagingEntityType entityType, boolean isCommit) { Duration shortTimeout = Duration.ofSeconds(15); setSenderAndReceiver(entityType, TestUtils.USE_CASE_SEND_READ_BACK_MESSAGES, false); final boolean isSessionEnabled = false; final String messageId = UUID.randomUUID().toString(); final int total = 3; final List<ServiceBusMessage> messages = TestUtils.getServiceBusMessages(total, messageId, CONTENTS_BYTES); AtomicReference<ServiceBusTransactionContext> transaction = new AtomicReference<>(); StepVerifier.create(sender.createTransaction()) .assertNext(txn -> { transaction.set(txn); assertNotNull(transaction); }) .verifyComplete(); assertNotNull(transaction.get()); StepVerifier.create(sender.send(messages, transaction.get())) .verifyComplete(); if (isCommit) { StepVerifier.create(sender.commitTransaction(transaction.get()).delaySubscription(Duration.ofSeconds(1))) .verifyComplete(); StepVerifier.create(receiver.receive().take(total).timeout(shortTimeout)) .assertNext(receivedMessage -> { assertMessageEquals(receivedMessage, messageId, isSessionEnabled); messagesPending.decrementAndGet(); }) .assertNext(receivedMessage -> { assertMessageEquals(receivedMessage, messageId, isSessionEnabled); messagesPending.decrementAndGet(); }) .assertNext(receivedMessage -> { assertMessageEquals(receivedMessage, messageId, isSessionEnabled); messagesPending.decrementAndGet(); }) .verifyComplete(); } else { StepVerifier.create(sender.rollbackTransaction(transaction.get()).delaySubscription(Duration.ofSeconds(1))) .verifyComplete(); StepVerifier.create(receiver.receive().take(total)) .verifyTimeout(shortTimeout); } }
Source:
public Collection<Container> match(ModuleDescriptor moduleDescriptor, ModuleDeploymentProperties deploymentProperties, Iterable<Container> containers) { Assert.notNull(moduleDescriptor, "'moduleDescriptor' cannot be null."); Assert.notNull(deploymentProperties, "'deploymentProperties' cannot be null."); logger.debug("Matching containers for module {}", moduleDescriptor); List<Container> candidates = findAllContainersMatchingCriteria(containers, deploymentProperties.getCriteria()); return distributeForRequestedCount(candidates, deploymentProperties.getCount()); }

Target:
public Collection<Container> match(ModuleDescriptor moduleDescriptor, ModuleDeploymentProperties deploymentProperties, Iterable<Container> containers) { Assert.notNull(moduleDescriptor, "'moduleDescriptor' cannot be null."); Assert.notNull(deploymentProperties, "'deploymentProperties' cannot be null."); Assert.notNull(containers, "'containers' cannot be null."); logger.debug("Matching containers for module {}", moduleDescriptor); List<Container> candidates = findAllContainersMatchingCriteria(containers, deploymentProperties.getCriteria()); return distributeForRequestedCount(candidates, deploymentProperties.getCount()); }
Source:
private void manageProcessDependenciesForIndex(Workpiece workpiece) throws CustomResponseException, IOException { Process process = workpiece.getProcess(); if (workpiece.getIndexAction() == IndexAction.DELETE) { if (process != null) { process.getWorkpieces().remove(workpiece); serviceManager.getProcessService().saveToIndex(process); } } else { if (process != null) { serviceManager.getProcessService().saveToIndex(process); } } }

Target:
private void manageProcessDependenciesForIndex(Workpiece workpiece) throws CustomResponseException, IOException { Process process = workpiece.getProcess(); if (workpiece.getIndexAction() == IndexAction.DELETE) { process.getWorkpieces().remove(workpiece); serviceManager.getProcessService().saveToIndex(process); } else { serviceManager.getProcessService().saveToIndex(process); } }
Source:
public NodeBean load(final File flowFile) throws Exception { checkArgument(flowFile != null); checkArgument(flowFile.exists()); checkArgument(flowFile.getName().endsWith(Constants.FLOW_FILE_SUFFIX)); final NodeBean nodeBean = new Yaml().loadAs(new FileInputStream(flowFile), NodeBean.class); if (nodeBean == null) { throw new ProjectManagerException( "Failed to load flow file " + flowFile.getName() + ". Node bean is null ."); } nodeBean.setName(getFlowName(flowFile)); nodeBean.setType(Constants.FLOW_NODE_TYPE); return nodeBean; }

Target:
public NodeBean load(final File flowFile) throws Exception { checkArgument(flowFile != null && flowFile.exists()); checkArgument(flowFile.getName().endsWith(Constants.FLOW_FILE_SUFFIX)); final NodeBean nodeBean = new Yaml().loadAs(new FileInputStream(flowFile), NodeBean.class); if (nodeBean == null) { throw new ProjectManagerException( "Failed to load flow file " + flowFile.getName() + ". Node bean is null ."); } nodeBean.setName(getFlowName(flowFile)); nodeBean.setType(Constants.FLOW_NODE_TYPE); return nodeBean; }
Source:
public void variableSubjQuery_Test() throws Exception { addStatements(); final String query = "PREFIX time: <<LINK_1>> \n" + "PREFIX tempo: <tag:rya-rdf.org,2015:temporal#> \n" + "PREFIX geo: <<LINK_2>>" + "PREFIX geof: <<LINK_0>>" + "SELECT * " + "WHERE { " + " ?subj time:atTime ?time . " + " ?subj geo:asWKT ?point . " + " FILTER(geof:sfWithin(?point, \"POLYGON((-3 -2, -3 2, 1 2, 1 -2, -3 -2))\"^^geo:wktLiteral)) " + " FILTER(tempo:equals(?time, \"2015-12-30T12:00:00Z\")) " + "}"; final TupleQueryResult rez = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate(); final List<BindingSet> results = new ArrayList<>(); while(rez.hasNext()) { final BindingSet bs = rez.next(); results.add(bs); } final MapBindingSet expected1 = new MapBindingSet(); expected1.addBinding("point", VF.createLiteral("POINT (0 0)")); expected1.addBinding("time", VF.createLiteral("2015-12-30T07:00:00-05:00")); final MapBindingSet expected2 = new MapBindingSet(); expected2.addBinding("point", VF.createLiteral("POINT (1 1)")); expected2.addBinding("time", VF.createLiteral("2015-12-30T07:00:00-05:00")); assertEquals(2, results.size()); assertEquals(expected1, results.get(0)); assertEquals(expected2, results.get(1)); }

Target:
public void variableSubjQuery_Test() throws Exception { final String query = "PREFIX time: <<LINK_1>> \n" + "PREFIX tempo: <tag:rya-rdf.org,2015:temporal#> \n" + "PREFIX geo: <<LINK_2>>" + "PREFIX geof: <<LINK_0>>" + "SELECT * " + "WHERE { " + " ?subj time:atTime ?time . " + " ?subj geo:asWKT ?point . " + " FILTER(geof:sfWithin(?point, \"POLYGON((-3 -2, -3 2, 1 2, 1 -2, -3 -2))\"^^geo:wktLiteral)) " + " FILTER(tempo:equals(?time, \"2015-12-30T12:00:00Z\")) " + "}"; final TupleQueryResult rez = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate(); final List<BindingSet> results = new ArrayList<>(); while(rez.hasNext()) { final BindingSet bs = rez.next(); results.add(bs); } final MapBindingSet expected1 = new MapBindingSet(); expected1.addBinding("point", VF.createLiteral("POINT (0 0)")); expected1.addBinding("time", VF.createLiteral("2015-12-30T12:00:00Z")); final MapBindingSet expected2 = new MapBindingSet(); expected2.addBinding("point", VF.createLiteral("POINT (1 1)")); expected2.addBinding("time", VF.createLiteral("2015-12-30T12:00:00Z")); assertEquals(2, results.size()); assertEquals(expected1, results.get(0)); assertEquals(expected2, results.get(1)); }
Source:
public String getLoginStatus(@Context HttpServletRequest request, @Context HttpServletResponse resp, @QueryParam("logoutNotification") String logoutNotification) { String callBackUrl; callBackUrl = getCallBackUrl(); if (logoutNotification.equals(OAuthConstants.LOG_OUT_NOTIFICATION)) { setIdTokenHint(null); removeStatusCookie(request, resp); } return "<html><head><script src=\"<LINK_0>\"></script>" + "<script> window.addEventListener ('message', OnMessage, false); " + "function OnMessage (event) {\n" + "if(event.data==(\"none\")){\n" + "parent.postMessage('" + getIdTokenHint() + "', '" + callBackUrl + "');\n" + "}" + "else{\n" + "var salt = event.data.split('.')[1].split(' ')[0];" + " var client_id=event.data.split(' ')[1];" + " var opss='" + getCookie(request) + "';var saltMaker=client_id + event.origin + opss + salt;" + "var stat;" + "console.log(\"Receiving the Polling Message From RP Client:.............\"+saltMaker);\n" + " var ss = CryptoJS.SHA256(saltMaker) + \".\" + salt+\" \"+client_id;" + " console.log (\" session state at th OP side: \"+opss);\n" + " if (event.data == ss) {\n" + " stat = 'unchanged';\n" + " } else {\n" + " stat = 'changed';\n" + " }" + " console.log (\" stat \"+stat);\n" + " if (event.origin.indexOf('" + callBackUrl + "')<0) {\n" + " parent.postMessage(stat, '" + callBackUrl + "');\n" + " }\n" + " else{\n" + " return;\n" + " }" + "}\n" + " }</script></head><body></body></html>"; }

Target:
public String getLoginStatus(@Context HttpServletRequest request, @Context HttpServletResponse resp, @QueryParam("logoutNotification") String logoutNotification) { String callBackUrl; callBackUrl = getCallBackUrl(); if (OAuthConstants.LOG_OUT_NOTIFICATION.equals(logoutNotification)) { setIdTokenHint(null); removeStatusCookie(request, resp); } return "<html><head><script src=\"<LINK_0>\"></script>" + "<script> window.addEventListener ('message', OnMessage, false); " + "function OnMessage (event) {\n" + "if(event.data==(\"none\")){\n" + "parent.postMessage('" + getIdTokenHint() + "', '" + callBackUrl + "');\n" + "}" + "else{\n" + "var salt = event.data.split('.')[1].split(' ')[0];" + " var client_id=event.data.split(' ')[1];" + " var opss='" + getCookie(request) + "';var saltMaker=client_id + event.origin + opss + salt;" + "var stat;" + "console.log(\"Receiving the Polling Message From RP Client:.............\"+saltMaker);\n" + " var ss = CryptoJS.SHA256(saltMaker) + \".\" + salt+\" \"+client_id;" + " console.log (\" session state at th OP side: \"+opss);\n" + " if (event.data == ss) {\n" + " stat = 'unchanged';\n" + " } else {\n" + " stat = 'changed';\n" + " }" + " console.log (\" stat \"+stat);\n" + " if (event.origin.indexOf('" + callBackUrl + "')<0) {\n" + " parent.postMessage(stat, '" + callBackUrl + "');\n" + " }\n" + " else{\n" + " return;\n" + " }" + "}\n" + " }</script></head><body></body></html>"; }
Source:
private void persistAllProjectPrefs() { Map<String, Map<String, String>> modelCacheMap = this.modelCache.asMap(); for (String projectName : modelCacheMap.keySet()) { persistPrefs(projectName, modelCacheMap.get(projectName)); } }

Target:
private void persistAllProjectPrefs() { Map<IProject, DefaultPersistentModel> modelCacheMap = this.modelCache.asMap(); for (Entry<IProject, DefaultPersistentModel> entry : modelCacheMap.entrySet()) { persistPrefs(entry.getKey(), entry.getValue()); } }
Source:
private void assertStudentDataMatches(StudentData studentData, StudentAttributes student, boolean isRequestFromInstructor) { assertNull(studentData.getGoogleId()); assertEquals(student.getEmail(), studentData.getEmail()); assertEquals(student.getCourse(), studentData.getCourseId()); assertEquals(student.getName(), studentData.getName()); if (student.getLastName() == null) { String[] name = StringHelper.splitName(student.name); assertEquals(name[1], studentData.getLastName()); } else { assertEquals(student.getLastName(), studentData.getLastName()); } assertEquals(student.getTeam(), studentData.getTeamName()); assertEquals(student.getSection(), studentData.getSectionName()); if (isRequestFromInstructor) { assertEquals(student.getComments(), studentData.getComments()); if (student.isRegistered()) { assertTrue(studentData.getJoinState().equals(JoinState.JOINED)); } else { assertTrue(studentData.getJoinState().equals(JoinState.NOT_JOINED)); } } else { assertNull(studentData.getComments()); assertNull(studentData.getJoinState()); } }

Target:
private void assertStudentDataMatches(StudentData studentData, StudentAttributes student, boolean isRequestFromInstructor) { assertNull(studentData.getGoogleId()); assertNull(studentData.getKey()); assertEquals(student.getEmail(), studentData.getEmail()); assertEquals(student.getCourse(), studentData.getCourseId()); assertEquals(student.getName(), studentData.getName()); if (student.getLastName() == null) { String[] name = StringHelper.splitName(student.name); assertEquals(name[1], studentData.getLastName()); } else { assertEquals(student.getLastName(), studentData.getLastName()); } assertEquals(student.getTeam(), studentData.getTeamName()); assertEquals(student.getSection(), studentData.getSectionName()); if (isRequestFromInstructor) { assertEquals(student.getComments(), studentData.getComments()); if (student.isRegistered()) { assertTrue(studentData.getJoinState().equals(JoinState.JOINED)); } else { assertTrue(studentData.getJoinState().equals(JoinState.NOT_JOINED)); } } else { assertNull(studentData.getComments()); assertNull(studentData.getJoinState()); } }
Source:
private static File fileTileMetricsFile(File illuminaRunDirectory, Integer numCycles, boolean isNovaSeq) { Path interOpDir = illuminaRunDirectory.toPath().resolve(INTEROP_SUBDIRECTORY_NAME); final List<Path> pathsToTest = new ArrayList<>(); pathsToTest.add(interOpDir.resolve(TILE_METRICS_OUT_FILE_NAME)); if (isNovaSeq) { pathsToTest.addAll(IntStream.range(1, numCycles + 1).map(i -> 1 + (numCycles - i)).mapToObj( cycleNum -> interOpDir.resolve(String.format("C%d.1/%s", cycleNum, TILE_METRICS_OUT_FILE_NAME))) .collect(Collectors.toList())); } return pathsToTest.stream().filter(path -> Files.exists(path)).findFirst().orElseThrow(() -> { StringBuilder message = new StringBuilder( String.format("No %s file found in %s", INTEROP_SUBDIRECTORY_NAME, interOpDir)); if (isNovaSeq) { message.append(" or any of its cycle directories."); } return new IllegalStateException(message.toString()); }).toFile(); }

Target:
private static File fileTileMetricsFile(File illuminaRunDirectory, Integer numCycles, boolean isNovaSeq) { Path interOpDir = illuminaRunDirectory.toPath().resolve(INTEROP_SUBDIRECTORY_NAME); final List<Path> pathsToTest = new ArrayList<>(); pathsToTest.add(interOpDir.resolve(TILE_METRICS_OUT_FILE_NAME)); if (isNovaSeq) { for (int i = numCycles; i > 0; i--) { pathsToTest.add(interOpDir.resolve(String.format("C%d.1/%s", i, TILE_METRICS_OUT_FILE_NAME))); } } return pathsToTest.stream().filter(Files::exists).findFirst().orElseThrow(() -> { StringBuilder message = new StringBuilder( String.format("No %s file found in %s", INTEROP_SUBDIRECTORY_NAME, interOpDir)); if (isNovaSeq) { message.append(" or any of its cycle directories."); } return new IllegalStateException(message.toString()); }).toFile(); }
Source:
protected void notify(List<URL> urls) { if (urls == null || urls.isEmpty()) { return; } for (Map.Entry<URL, Set<NotifyListener>> entry : getSubscribed().entrySet()) { URL url = entry.getKey(); if (!UrlUtils.isMatch(url, urls.get(0))) { continue; } Set<NotifyListener> listeners = entry.getValue(); if (listeners != null && !listeners.isEmpty()) { for (NotifyListener listener : listeners) { try { notify(url, listener, filterEmpty(url, urls)); } catch (Throwable t) { logger.error("Failed to notify registry event, urls: " + urls + ", cause: " + t.getMessage(), t); } } } } }

Target:
protected void notify(List<URL> urls) { if (urls == null || urls.isEmpty()) { return; } for (Map.Entry<URL, Set<NotifyListener>> entry : getSubscribed().entrySet()) { URL url = entry.getKey(); if (!UrlUtils.isMatch(url, urls.get(0))) { continue; } Set<NotifyListener> listeners = entry.getValue(); if (listeners != null) { for (NotifyListener listener : listeners) { try { notify(url, listener, filterEmpty(url, urls)); } catch (Throwable t) { logger.error("Failed to notify registry event, urls: " + urls + ", cause: " + t.getMessage(), t); } } } } }
Source:
public void setLeftButton(String text, Runnable action) { find("leftButton", UIButton.class).setText(text); leftActon = action; }

Target:
public void setLeftButton(String text, Runnable action) { UIButton leftButton = find("leftButton", UIButton.class); if (leftButton != null) { leftButton.setText(text); } leftActon = action; }
Source:
public List<ChePlugin> execute() throws InfrastructureException { Span tracingSpan = startTracingPhase(); volumesStrategy.prepare( brokerEnvironment, workspaceId, startSynchronizer.getStartTimeoutMillis()); finishSpanIfExists(tracingSpan); return nextPhase.execute(); }

Target:
public List<ChePlugin> execute() throws InfrastructureException { Span tracingSpan = tracerUtil.buildSpan(SPAN_NAME, null, workspaceId, null); try { volumesStrategy.prepare( brokerEnvironment, workspaceId, startSynchronizer.getStartTimeoutMillis()); } catch (InfrastructureException e) { tracerUtil.finishSpanAsFailure(tracingSpan, e.getMessage()); throw e; } tracerUtil.finishSpan(tracingSpan); return nextPhase.execute(); }
Source:
public void joseEncoded() throws IOException { final byte[] code = new Token.Jose(256).encoded(); final JsonObject jose = new Token.Jose(256).json(); MatcherAssert.assertThat( code, Matchers.equalTo( Base64.getEncoder().encode(jose.toString().getBytes()) ) ); }

Target:
public void joseEncoded() throws IOException { final byte[] code = new Token.Jose(256).encoded(); MatcherAssert.assertThat( code, new IsEqual<>( Base64.getEncoder().encode( "{\"alg\":\"HS256\",\"typ\":\"JWT\"}".getBytes() ) ) ); }
Source:
protected ICommand getCreateRelationshipCommand(final CreateRelationshipRequest req) { EObject source = req.getSource(); EObject target = req.getTarget(); if (false == source instanceof Vertex) { return UnexecutableCommand.INSTANCE; } if (target == null) { return IdentityCommand.INSTANCE; } if (false == target instanceof Vertex) { return UnexecutableCommand.INSTANCE; } Region container = findRegionContainer((Vertex) source); if (container == null) { container = findRegionContainer((Vertex) target); if (null == container) { return UnexecutableCommand.INSTANCE; } } setContainerAndFeature(req, container); return super.getCreateRelationshipCommand(req); }

Target:
protected ICommand getCreateRelationshipCommand(final CreateRelationshipRequest req) { EObject source = req.getSource(); EObject target = req.getTarget(); if (false == source instanceof Vertex) { return UnexecutableCommand.INSTANCE; } if (null == target) { return IdentityCommand.INSTANCE; } if (false == target instanceof Vertex) { return UnexecutableCommand.INSTANCE; } Region container = findRegionContainer((Vertex) source); if (null == container) { container = findRegionContainer((Vertex) target); if (null == container) { container = getFirstRegionStateMachine((Vertex) source); if (null == container) { return UnexecutableCommand.INSTANCE; } } } setContainerAndFeature(req, container); return super.getCreateRelationshipCommand(req); }
Source:
public static void initialize() throws APIManagerDatabaseException { if (artifactSynchronizerDataSource != null) { return; } synchronized (APIMgtDBUtil.class) { if (artifactSynchronizerDataSource == null) { if (log.isDebugEnabled()) { log.debug("Initializing data source"); } GatewayArtifactSynchronizerProperties gatewayArtifactSynchronizerProperties = ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService() .getAPIManagerConfiguration().getGatewayArtifactSynchronizerProperties(); String artifactSynchronizerDataSourceName = gatewayArtifactSynchronizerProperties.getArtifactSynchronizerDataSource(); if (artifactSynchronizerDataSourceName != null) { try { Context ctx = new InitialContext(); artifactSynchronizerDataSource = (DataSource) ctx.lookup(artifactSynchronizerDataSourceName); } catch (NamingException e) { throw new APIManagerDatabaseException("Error while looking up the data " + "source: " + artifactSynchronizerDataSourceName, e); } } else { log.error("AS" + artifactSynchronizerDataSourceName + " not defined in api-manager.xml."); } } } }

Target:
public static void initialize() throws APIManagerDatabaseException { if (artifactSynchronizerDataSource != null) { return; } initDatasource(); }
Source:
public void visit(Comparison obj) { if(this.table.getProperty(ParquetMetadataProcessor.PARTITIONING_SCHEME) == null){ } else { if (this.table.getProperty(ParquetMetadataProcessor.PARTITIONING_SCHEME).equals("directory")) { directoryBasedPartitioning(obj); } else { } } }

Target:
public void visit(Comparison obj) { ColumnReference cr = (ColumnReference) obj.getLeftExpression(); Column column = cr.getMetadataObject(); String columnName = column.getSourceName(); columnPredicates.put(columnName, obj); }
Source:
public static boolean isVisible(MCoreExpression exp, final ExpressionContext eContext) { final Expression ref; if (exp.getCoreExpression() instanceof Expression) { ref = (Expression) exp.getCoreExpression(); } else { ref = new ReferenceExpression(exp.getCoreExpressionId()); exp.setCoreExpression(ref); } ExpressionInfo info = ref.computeExpressionInfo(); String[] names = info.getAccessedPropertyNames(); for (String name : names) { eContext.getVariable(name + ".evaluationServiceLink"); } final boolean[] ret = new boolean[1]; ret[0] = false; try { ret[0] = ref.evaluate(eContext) != EvaluationResult.FALSE; } catch (CoreException e) { trace("isVisible exception", e); } return ret[0]; }

Target:
public static boolean isVisible(MCoreExpression exp, final ExpressionContext eContext) { final Expression ref; if (exp.getCoreExpression() instanceof Expression) { ref = (Expression) exp.getCoreExpression(); } else { ref = new ReferenceExpression(exp.getCoreExpressionId()); exp.setCoreExpression(ref); } ExpressionInfo info = ref.computeExpressionInfo(); String[] names = info.getAccessedPropertyNames(); for (String name : names) { eContext.getVariable(name + ".evaluationServiceLink"); } final boolean[] ret = new boolean[1]; ret[0] = false; try { ret[0] = ref.evaluate(eContext) != EvaluationResult.FALSE; } catch (Exception e) { trace("isVisible exception", e); } return ret[0]; }
Source:
public static Geocache searchByGeoCode(final String geocode) { final Parameters params = new Parameters("id", cleanCode(geocode)); params.add("cgeo", "1"); final HttpResponse response = apiRequest("<LINK_0>", params); final Collection<Geocache> caches = importCachesFromGPXResponse(response); if (CollectionUtils.isNotEmpty(caches)) { return caches.iterator().next(); } return null; }

Target:
public static Geocache searchByGeoCode(final String geocode) { final Parameters params = new Parameters("id", cleanCode(geocode), "cgeo", "1"); final HttpResponse response = apiRequest("gpx.php", params); final Collection<Geocache> caches = importCachesFromGPXResponse(response); if (CollectionUtils.isNotEmpty(caches)) { return caches.iterator().next(); } return null; }
Source:
private void initializeTest() { IDialogTestPass test = _dialogTests[TEST_TYPE]; setTitle(test.title()); setMessage(test.description()); Iterator<?> iterator = test.checkListTexts().iterator(); for (int i = 0; i < _checkList.length; i++) { if (iterator.hasNext()) { _checkList[i].setText(iterator.next().toString()); _checkList[i].setVisible(true); _checkList[i].update(); } else { _checkList[i].setVisible(false); _checkList[i].update(); } _checkList[i].setSelection(true); } _queryLabel.setText(test.queryText()); }

Target:
private void initializeTest() { IDialogTestPass test = _dialogTests[TEST_TYPE]; setTitle(test.title()); setMessage(test.description()); Iterator<?> iterator = test.checkListTexts().iterator(); for (Button checkButton : _checkList) { if (iterator.hasNext()) { checkButton.setText(iterator.next().toString()); checkButton.setVisible(true); checkButton.update(); } else { checkButton.setVisible(false); checkButton.update(); } checkButton.setSelection(true); } _queryLabel.setText(test.queryText()); }
Source:
public void testMigration() { assertEquals(1, session.getOwnedViews().size()); DView dView = session.getOwnedViews().iterator().next(); assertEquals(1, dView.getOwnedRepresentations().size()); DRepresentation dRepresentation = dView.getOwnedRepresentations().get(0); assertTrue(dRepresentation instanceof DDiagram); DDiagram dDiagram = (DDiagram) dRepresentation; ComputedStyleDescriptionRegistry computedStyleDescriptionRegistry = new DDiagramInternalQuery(dDiagram).getComputedStyleDescriptionRegistry(false); assertNotNull(computedStyleDescriptionRegistry); assertEquals("Computed StyleDescriptiosshould have been shared among styles within the DDiagram", 3, computedStyleDescriptionRegistry.getComputedStyleDescriptions().size()); assertEquals("As the maps of ComputedStyleDescriptionRegistry are no more used, it should remains only the 3 computed StyleDescriptions", 3, computedStyleDescriptionRegistry.eContents() .size()); }

Target:
public void testMigration() { assertEquals(1, session.getOwnedViews().size()); DView dView = session.getOwnedViews().iterator().next(); assertEquals(1, dView.getOwnedRepresentations().size()); DRepresentation dRepresentation = dView.getOwnedRepresentations().get(0); assertTrue(dRepresentation instanceof DDiagram); DDiagram dDiagram = (DDiagram) dRepresentation; ComputedStyleDescriptionRegistry computedStyleDescriptionRegistry = new DDiagramInternalQuery(dDiagram).getComputedStyleDescriptionRegistry(false); assertNotNull(computedStyleDescriptionRegistry); assertEquals("Computed StyleDescriptiosshould have been shared among styles within the DDiagram", 3, computedStyleDescriptionRegistry.getComputedStyleDescriptions().size()); assertEquals("As the maps of ComputedStyleDescriptionRegistry are no more used, it should remains only the 3 computed StyleDescriptions", 3, computedStyleDescriptionRegistry.eContents() .size()); XMLResource airdResource = (XMLResource) session.getSessionResource(); assertEquals("As the migration has done its job, the map of unknown data should be empty", 0, airdResource.getEObjectToExtensionMap().size()); }
Source:
public static void setVisibility (boolean visible, Context context) { try { MainApplication.visible = visible; ServerApi.setVisibility(context, visible); if (visible == false) { LocationService.stop(context); } else { LocationService.start(context); } } catch (Exception ex) { Log.e(TAG, "Could not set visibility:" + ex.getMessage()); } }

Target:
public static void setVisibility (boolean visible, Context context) { try { MainApplication.visible = visible; ServerApi.setVisibility(context, visible); if (visible == false) { LocationService.stop(context); } else { LocationService.start(context); } } catch (JSONException ex) { Log.e(TAG, "Could not set visibility:" + ex.getMessage()); } }
Source:
public ProfileProxyAuthenticator(ProxyConfig proxyConfig) throws MalformedChallengeException { this.proxyConfig = proxyConfig; basicScheme = new BasicScheme(); basicScheme.processChallenge(new BasicHeader(AUTH.PROXY_AUTH, "BASIC realm=\"proxy\"")); }

Target:
public ProfileProxyAuthenticator(ProxyConfig proxyConfig) throws MalformedChallengeException { this.proxyConfig = proxyConfig; basicScheme = new BasicScheme(); basicScheme.processChallenge(new BasicHeader(AUTH.PROXY_AUTH, PassThroughConstants.PROXY_BASIC_REALM)); }
Source:
public static void savePeople(List<Person> peopleList) { for (Person person : peopleList) { PeopleTable.save(person); } }

Target:
public static void savePeople(List<Person> peopleList) { getWritableDb().beginTransaction(); try { for (Person person : peopleList) { PeopleTable.save(person); } getWritableDb().setTransactionSuccessful(); } finally { getWritableDb().endTransaction(); } }
Source:
private static void registerEventualTransactionsSchemaVersionMetric(MetricsManager metricsManager, CoordinationService<InternalSchemaMetadata> metadataCoordinationService) { metricsManager.registerMetric( MetadataCoordinationServiceMetrics.class, EVENTUAL_TRANSACTIONS_SCHEMA_VERSION, new CachedGauge<Integer>(Clock.defaultClock(), DEFAULT_CACHE_TTL, TimeUnit.SECONDS) { @Override protected Integer loadValue() { try { Optional<ValueAndBound<InternalSchemaMetadata>> latestValue = metadataCoordinationService.getLastKnownLocalValue(); return latestValue .map(ValueAndBound::value) .flatMap(Function.identity()) .map(InternalSchemaMetadata::timestampToTransactionsTableSchemaVersion) .map(timestampMap -> timestampMap.getValueForTimestamp(latestValue.get().bound())) .orElse(null); } catch (Exception e) { log.info("An exception occurred when trying to retrieve the metric.", SafeArg.of("gaugeName", EVENTUAL_TRANSACTIONS_SCHEMA_VERSION), e); return null; } } } ); }

Target:
private static void registerEventualTransactionsSchemaVersionMetric(MetricsManager metricsManager, CoordinationService<InternalSchemaMetadata> metadataCoordinationService) { metricsManager.registerMetric( MetadataCoordinationServiceMetrics.class, AtlasDbMetricNames.COORDINATION_EVENTUAL_TRANSACTIONS_SCHEMA_VERSION, TrackerUtils.createCachingExceptionHandlingGauge( log, Clock.defaultClock(), AtlasDbMetricNames.COORDINATION_EVENTUAL_TRANSACTIONS_SCHEMA_VERSION, () -> { Optional<ValueAndBound<InternalSchemaMetadata>> latestValue = metadataCoordinationService.getLastKnownLocalValue(); return latestValue .map(ValueAndBound::value) .flatMap(Function.identity()) .map(InternalSchemaMetadata::timestampToTransactionsTableSchemaVersion) .map(timestampMap -> timestampMap.getValueForTimestamp(latestValue.get().bound())) .orElse(null); })); }
Source:
private DbUser getTargetDbUser() { DbUser dbUser = new DbUser(); dbUser.setLoginName(getSearchString()); dbUser.setDomain(getProfile().getSelectedItem().toString()); return dbUser; }

Target:
private DbUser getTargetDbUser() { DbUser dbUser = new DbUser(); dbUser.setLoginName(getSearchString()); dbUser.setDomain(((ProfileEntry) getProfile().getSelectedItem()).getAuthz()); return dbUser; }
Source:
public PartitioningScheme translateOutputLayout(List<VariableReferenceExpression> newOutputLayout) { requireNonNull(newOutputLayout, "newOutputLayout is null"); checkArgument(newOutputLayout.size() == outputLayout.size()); Partitioning newPartitioning = partitioning.translate(variable -> newOutputLayout.get(outputLayout.indexOf((VariableReferenceExpression) variable))); Optional<VariableReferenceExpression> newHashSymbol = hashColumn .map(outputLayout::indexOf) .map(newOutputLayout::get); return new PartitioningScheme(newPartitioning, newOutputLayout, newHashSymbol, replicateNullsAndAny, bucketToPartition); }

Target:
public PartitioningScheme translateOutputLayout(List<VariableReferenceExpression> newOutputLayout) { requireNonNull(newOutputLayout, "newOutputLayout is null"); checkArgument(newOutputLayout.size() == outputLayout.size()); Partitioning newPartitioning = partitioning.translateVariable(variable -> newOutputLayout.get(outputLayout.indexOf(variable))); Optional<VariableReferenceExpression> newHashSymbol = hashColumn .map(outputLayout::indexOf) .map(newOutputLayout::get); return new PartitioningScheme(newPartitioning, newOutputLayout, newHashSymbol, replicateNullsAndAny, bucketToPartition); }
Source:
public BAMIndex getIndex() { if(!hasIndex()) throw new SAMException("No index is available for this BAM file."); if(mIndex == null) { if (mIndexFile != null) { if (getIndexType().equals(SamIndexes.BAI)) { mIndex = mEnableIndexCaching ? new CachingBAMFileIndex(mIndexFile, getFileHeader().getSequenceDictionary(), mEnableIndexMemoryMapping) : new DiskBasedBAMFileIndex(mIndexFile, getFileHeader().getSequenceDictionary(), mEnableIndexMemoryMapping); } else if (getIndexType().equals(SamIndexes.CSI)) { mIndex = new CSIIndex(mIndexFile, mEnableIndexMemoryMapping, getFileHeader().getSequenceDictionary()); } } else { mIndex = mEnableIndexCaching ? new CachingBAMFileIndex(mIndexStream, getFileHeader().getSequenceDictionary()) : new DiskBasedBAMFileIndex(mIndexStream, getFileHeader().getSequenceDictionary()); } } return mIndex; }

Target:
public BAMIndex getIndex() { if(!hasIndex()) throw new SAMException("No index is available for this BAM file."); if(mIndex == null) { SamIndexes samIndex = getIndexType(); if (samIndex == null) { mIndex = mEnableIndexCaching ? new CachingBAMFileIndex(mIndexStream, getFileHeader().getSequenceDictionary()) : new DiskBasedBAMFileIndex(mIndexStream, getFileHeader().getSequenceDictionary()); } else if (samIndex.equals(SamIndexes.BAI)) { mIndex = mEnableIndexCaching ? new CachingBAMFileIndex(mIndexFile, getFileHeader().getSequenceDictionary(), mEnableIndexMemoryMapping) : new DiskBasedBAMFileIndex(mIndexFile, getFileHeader().getSequenceDictionary(), mEnableIndexMemoryMapping); } else if (samIndex.equals(SamIndexes.CSI)) { mIndex = new CSIIndex(mIndexFile, mEnableIndexMemoryMapping, getFileHeader().getSequenceDictionary()); } else { throw new SAMFormatException("Unsupported BAM index file: " + mIndexFile.getName()); } } return mIndex; }
Source:
static String[] parseRequireBundleValue(String value, List<String> bundlesToExclude) { return Arrays.stream(value.split(",")) .map( (it) -> { return it.split(";")[0]; }) .filter( (it) -> { return !bundlesToExclude.contains(it); }) .toArray(String[]::new); }

Target:
private static String[] parseRequireBundleValue(String value, List<String> bundlesToExclude) { return Arrays.stream(value.split(",")) .map(it -> it.split(";")[0]) .filter(it -> !bundlesToExclude.contains(it)) .toArray(String[]::new); }
Source:
public void setProjectionParameters(Map projectionParameters) { if (projectionParameters.containsKey("advancedProjectionDensify")) { densify = (Double) projectionParameters.get("advancedProjectionDensify"); } this.projectionParameters = projectionParameters; }

Target:
public void setProjectionParameters(Map projectionParameters) { if (projectionParameters.containsKey(ADVANCED_PROJECTION_DENSIFY)) { densify = (Double) projectionParameters.get(ADVANCED_PROJECTION_DENSIFY); } this.projectionParameters = projectionParameters; }
Source:
public void setupMocks() { elide = mock(Elide.class); asyncQueryDao = mock(DefaultAsyncQueryDAO.class); ElideSettings elideSettings = mock(ElideSettings.class); EntityDictionary dictionary = mock(EntityDictionary.class); JsonApiMapper mapper = mock(JsonApiMapper.class); ObjectMapper objectMapper = mock(ObjectMapper.class); Set<Class<?>> boundclasses = new HashSet<Class<?>>(); boundclasses.add(AsyncQuery.class); boundclasses.add(AsyncQueryResult.class); Set<String> apiCollection = new HashSet<String>(); apiCollection.add("v1"); when(elide.getElideSettings()).thenReturn(elideSettings); when(elideSettings.getDictionary()).thenReturn(dictionary); when(dictionary.getBoundClassesByVersion("v1")).thenReturn(boundclasses); when(dictionary.getApiVersions()).thenReturn(apiCollection); when(elideSettings.getMapper()).thenReturn(mapper); when(mapper.getObjectMapper()).thenReturn(objectMapper); AsyncExecutorService.init(elide, 5, 60, asyncQueryDao); service = AsyncExecutorService.getInstance(); }

Target:
public void setupMocks() { HashMapDataStore inMemoryStore = new HashMapDataStore(AsyncQuery.class.getPackage()); Map<String, Class<? extends Check>> checkMappings = new HashMap<>(); elide = new Elide( new ElideSettingsBuilder(inMemoryStore) .withEntityDictionary(new EntityDictionary(checkMappings)) .build()); asyncQueryDao = mock(DefaultAsyncQueryDAO.class); AsyncExecutorService.init(elide, 5, 60, asyncQueryDao); service = AsyncExecutorService.getInstance(); }
Source:
protected void run(Server server, User user, String commandLabel, String[] args) throws Exception { CommandSource sender = user.getSource(); if (args.length > 0 && user.isAuthorized("essentials.back.others")) { this.parseCommand(server, sender, args); return; } teleportBack(sender, user); }

Target:
protected void run(Server server, User user, String commandLabel, String[] args) throws Exception { CommandSource sender = user.getSource(); if (args.length > 0 && user.isAuthorized("essentials.back.others")) { parseOthers(server, sender, args, commandLabel); return; } teleportBack(sender, user, commandLabel); }
Source:
public void executeCommand(Command command, ExecutionHandlerContext context) { List<byte[]> commandElems = command.getProcessedCommand(); if (commandElems.size() < 3) { command.setResponse(Coder.getErrorResponse(context.getByteBufAllocator(), ArityDef.SADD)); return; } ByteArrayWrapper key = command.getKey(); Region<ByteArrayWrapper, Set<ByteArrayWrapper>> region = getRegion(context); ByteArrayWrapper keyPlaceHolder = null; region.compute( key, (ByteArrayWrapper localKey, Set<ByteArrayWrapper> oldRegionData) -> { Long entriesAdded = 0L; Set<ByteArrayWrapper> regionCopy = oldRegionData; if (regionCopy == null) { regionCopy = new HashSet<>(); } for (int i = 2; i < commandElems.size(); i++) { if (regionCopy.add(new ByteArrayWrapper(commandElems.get(i)))) { entriesAdded++; } } return regionCopy; } ); context.getKeyRegistrar().register(command.getKey(), RedisDataType.REDIS_SET); }

Target:
public void executeCommand(Command command, ExecutionHandlerContext context) { List<byte[]> commandElems = command.getProcessedCommand(); AtomicLong entriesAdded = new AtomicLong(0L); if (commandElems.size() < 3) { command.setResponse(Coder.getErrorResponse(context.getByteBufAllocator(), ArityDef.SADD)); return; } ByteArrayWrapper key = command.getKey(); Region<ByteArrayWrapper, Set<ByteArrayWrapper>> region = getRegion(context); context.getKeyRegistrar().register(command.getKey(), RedisDataType.REDIS_SET); region.compute( key, (ByteArrayWrapper localKey, Set<ByteArrayWrapper> oldSetValue) -> { entriesAdded.set(0L); Set<ByteArrayWrapper> setCopy; if (oldSetValue == null) { setCopy = new HashSet<>(); } else { setCopy = new HashSet<>(oldSetValue); } for (int i = 2; i < commandElems.size(); i++) { if (setCopy.add(new ByteArrayWrapper(commandElems.get(i)))) { entriesAdded.incrementAndGet(); } } return setCopy; }); command .setResponse(Coder.getIntegerResponse(context.getByteBufAllocator(), entriesAdded.get())); }
Source:
private boolean isNfsSupportEnabled(Config config) { Boolean result = isNfsSupportEnabled; if (result == null) { isNfsSupportEnabled = result = Boolean.valueOf( config.getBoolean(ConfigConstants.CONFIG_CORE_SECTION, null, ConfigConstants.ENABLE_NFS_SUPPORT, false)); } return result.booleanValue(); }

Target:
private boolean isNfsSupportEnabled(Config config) { if (config == null) { return false; } Boolean result = nfsSupportEnabled; if (result == null) { nfsSupportEnabled = result = Boolean.valueOf( config.getBoolean(ConfigConstants.CONFIG_CORE_SECTION, null, ConfigConstants.ENABLE_NFS_SUPPORT, false)); } return result.booleanValue(); }
Source:
public void log(){ LicenseManager license = LicenseManager.getInstance(); Company company = PublicCompanyFactory.getDefaultCompany(); TimeZone companyTimeZone = company.getTimeZone(); TimeZone.setDefault(companyTimeZone); Logger.info(this, "InitServlet: Setting Default Timezone: " + companyTimeZone.getDisplayName()); String _dbType = DbConnectionFactory.getDBType(); String _dailect = ""; try { _dailect = HibernateUtil.getDialect(); } catch (DotHibernateException e3) { Logger.error(InitServlet.class, e3.getMessage(), e3); } String expires = (license.isPerpetual()) ? "never" : UtilMethods.dateToLongPrettyHTMLDate(license.getValidUntil()); String _companyId = PublicCompanyFactory.getDefaultCompanyId(); Logger.info(this, ""); Logger.info(this, " Initializing dotCMS"); Logger.info(this, " Using database: " + _dbType); Logger.info(this, " Using dialect : " + _dailect); Logger.info(this, " Company Name : " + _companyId); Logger.info(this, ""); Logger.info(this, " License : " + license.getLevelName(license.getLevel())); Logger.info(this, " Licensed to : " + license.getClientName()); Logger.info(this, " Server id : " + license.getDisplayServerId()); Logger.info(this, " License id : " + license.getDisplaySerial()); Logger.info(this, " Valid until : " + expires); if(Config.getBooleanProperty("DIST_INDEXATION_ENABLED", false)){ Logger.info(this, " Clustering : Enabled"); } else{ Logger.info(this, " Clustering : Disabled"); } Logger.info(this, ""); }

Target:
public void log(){ LicenseManager license = LicenseManager.getInstance(); Company company = PublicCompanyFactory.getDefaultCompany(); TimeZone companyTimeZone = company.getTimeZone(); TimeZone.setDefault(companyTimeZone); Logger.info(this, "InitServlet: Setting Default Timezone: " + companyTimeZone.getDisplayName()); String dbType = DbConnectionFactory.getDBType(); String dailect = ""; try { dailect = HibernateUtil.getDialect(); } catch (DotHibernateException e3) { Logger.error(InitServlet.class, e3.getMessage(), e3); } String expires = (license.isPerpetual()) ? "never" : UtilMethods.dateToLongPrettyHTMLDate(license.getValidUntil()); String companyId = PublicCompanyFactory.getDefaultCompanyId(); Logger.info(this, ""); Logger.info(this, " Initializing dotCMS"); Logger.info(this, " Using database: " + dbType); Logger.info(this, " Using dialect : " + dailect); Logger.info(this, " Company Name : " + companyId); Logger.info(this, ""); Logger.info(this, " License : " + license.getLevelName(license.getLevel())); Logger.info(this, " Licensed to : " + license.getClientName()); Logger.info(this, " Server id : " + license.getDisplayServerId()); Logger.info(this, " License id : " + license.getDisplaySerial()); Logger.info(this, " Valid until : " + expires); if(Config.getBooleanProperty("DIST_INDEXATION_ENABLED", false)){ Logger.info(this, " Clustering : Enabled"); } else{ Logger.info(this, " Clustering : Disabled"); } Logger.info(this, ""); }
Source:
private static boolean isClassInNamespaceContext(ClassDeclarationTree classDec) { Tree parent = classDec.getParent(); if (parent != null && parent.is(Kind.SCRIPT)) { ScriptTree scriptTree = (ScriptTree) parent; for (Tree statement : scriptTree.statements()) { if (statement.is(Kind.NAMESPACE_STATEMENT)) { return true; } } } return false; }

Target:
private boolean isClassInNamespaceContext(ClassDeclarationTree classDec) { Symbol symbol = context().symbolTable().getSymbol(classDec.name()); QualifiedName qualifiedName = symbol.qualifiedName(); return qualifiedName != null && !qualifiedName.toString().equals(symbol.name()); }
Source:
public void extractJudges() { Judge judge = new Judge("Jan Kowalski"); when(sourceJudgeExtractorHelper.extractJudges(sJudgment, correctionList)).thenReturn(Lists.newArrayList(judge)); List<Judge> judges = judgmentExtractor.extractJudges(sJudgment, correctionList); assertEquals(1, judges.size()); assertEquals(judge.getName(), judges.get(0).getName()); }

Target:
public void extractJudges() { Judge judge = new Judge("Jan Kowalski"); List<Judge> judges = ImmutableList.of(judge); when(sourceJudgeExtractorHelper.extractJudges(sJudgment, correctionList)).thenReturn(judges); List<Judge> returnedJudges = judgmentExtractor.extractJudges(sJudgment, correctionList); assertTrue(returnedJudges == judges); }
Source:
private String getResourcePath(String resource) throws Exception { return URLDecoder.decode(this.getClass().getClassLoader().getResource(resource).getPath(), UTF_8.name()); }

Target:
private String getResourcePath(String resource) throws Exception { return this.getClass().getClassLoader().getResource(resource).toURI().getPath(); }
Source:
public Callable<AdaptiveExercise> getAdaptiveExercise() throws OAuthSystemException, OAuthProblemException, NotLoggedInException { return wrapWithNotLoggedInException(new Callable<AdaptiveExercise>() { @Override public AdaptiveExercise call() throws Exception { try { Callable<String> download = new HttpTasks() .getForText(getSkillifierUrl("next.json?username=" + oauth.getToken())); String json = download.call(); return adaptiveExerciseParser.parseFromJson(json); } catch (Exception ex) { LOG.log(Level.WARNING, "Downloading and parsing adaptive exercise URL failed."); return null; } } }); }

Target:
public Callable<AdaptiveExercise> getAdaptiveExercise() throws OAuthSystemException, OAuthProblemException, NotLoggedInException { return wrapWithNotLoggedInException(new Callable<AdaptiveExercise>() { @Override public AdaptiveExercise call() throws Exception { try { Callable<String> download = new HttpTasks() .getForText(getSkillifierUrl("next.json?username=" + oauth.getToken())); String json = download.call(); return adaptiveExerciseParser.parseFromJson(json); } catch (Exception ex) { LOG.log(Level.WARNING, "Downloading and parsing adaptive exercise URL failed with exception: " + ex.getMessage(), ex); return null; } } }); }
Source:
public synchronized void waitForWorkToFinish() { m_doneProducing = true; while (m_workProduced != m_workConsumed.longValue()) { try { wait(); } catch (InterruptedException unexpected) { } assert m_workProduced == m_workConsumed.longValue(); } }

Target:
public boolean waitForWorkToFinish() { final int attemptIntervalMs = 100; final int maxAttempts = (int) (TimeUnit.SECONDS.toMillis(KAFKA_IMPORTER_MAX_SHUTDOWN_WAIT_TIME_SECONDS) / attemptIntervalMs); int attemptCount = 0; while (m_workProduced != m_workConsumed.longValue() && attemptCount < maxAttempts) { try { Thread.sleep(attemptIntervalMs); } catch (InterruptedException unexpected) { } attemptCount++; } return m_workProduced == m_workConsumed.longValue(); }
Source:
public ListenableFuture<ImmutableSet<Digest>> findMissingDigests(Iterable<Digest> digests) { if (Iterables.isEmpty(digests)) { return Futures.immediateFuture(ImmutableSet.of()); } FindMissingBlobsRequest.Builder requestBuilder = FindMissingBlobsRequest.newBuilder().setInstanceName(options.remoteInstanceName); List<ListenableFuture<FindMissingBlobsResponse>> getMissingDigestCalls = new ArrayList<>(); for (Digest digest : digests) { requestBuilder.addBlobDigests(digest); if (requestBuilder.getBlobDigestsCount() == maxMissingBlobsDigestsPerMessage) { getMissingDigestCalls.add(getMissingDigests(requestBuilder.build())); requestBuilder.clearBlobDigests(); } } if (requestBuilder.getBlobDigestsCount() > 0) { getMissingDigestCalls.add(getMissingDigests(requestBuilder.build())); } ListenableFuture<ImmutableSet<Digest>> success = Futures.whenAllSucceed(getMissingDigestCalls) .call( () -> { ImmutableSet.Builder<Digest> result = ImmutableSet.builder(); for (ListenableFuture<FindMissingBlobsResponse> callFuture : getMissingDigestCalls) { result.addAll(callFuture.get().getMissingBlobDigestsList()); } return result.build(); }, MoreExecutors.directExecutor()); return Futures.catchingAsync( success, Exception.class, (e) -> Futures.immediateFailedFuture( new IOException( String.format( "findMissingBlobs(%d) for %s", requestBuilder.getBlobDigestsCount(), TracingMetadataUtils.fromCurrentContext().getActionId()), e)), MoreExecutors.directExecutor()); }

Target:
public ListenableFuture<ImmutableSet<Digest>> findMissingDigests(Iterable<Digest> digests) { if (Iterables.isEmpty(digests)) { return Futures.immediateFuture(ImmutableSet.of()); } FindMissingBlobsRequest.Builder requestBuilder = FindMissingBlobsRequest.newBuilder().setInstanceName(options.remoteInstanceName); List<ListenableFuture<FindMissingBlobsResponse>> getMissingDigestCalls = new ArrayList<>(); for (Digest digest : digests) { requestBuilder.addBlobDigests(digest); if (requestBuilder.getBlobDigestsCount() == maxMissingBlobsDigestsPerMessage) { getMissingDigestCalls.add(getMissingDigests(requestBuilder.build())); requestBuilder.clearBlobDigests(); } } if (requestBuilder.getBlobDigestsCount() > 0) { getMissingDigestCalls.add(getMissingDigests(requestBuilder.build())); } ListenableFuture<ImmutableSet<Digest>> success = Futures.whenAllSucceed(getMissingDigestCalls) .call( () -> { ImmutableSet.Builder<Digest> result = ImmutableSet.builder(); for (ListenableFuture<FindMissingBlobsResponse> callFuture : getMissingDigestCalls) { result.addAll(callFuture.get().getMissingBlobDigestsList()); } return result.build(); }, MoreExecutors.directExecutor()); return Futures.catchingAsync( success, RuntimeException.class, (e) -> Futures.immediateFailedFuture( new IOException( String.format( "findMissingBlobs(%d) for %s", requestBuilder.getBlobDigestsCount(), TracingMetadataUtils.fromCurrentContext().getActionId()), e)), MoreExecutors.directExecutor()); }