auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void init(IWorkbench workbench) { setDescription("Capra Generic Preferences"); setPreferenceStore(new ScopedPreferenceStore(InstanceScope.INSTANCE, CAPRA_PREFERENCE_PAGE_ID)); }

Target:
public void init(IWorkbench workbench) { setDescription(PREFERENCE_PAGE_DESCRIPTION); setPreferenceStore(new ScopedPreferenceStore(InstanceScope.INSTANCE, CAPRA_PREFERENCE_PAGE_ID)); }
Source:
public void cleanup() { for (Map.Entry<View, int[]> original:mOriginalValues.entrySet()) { final View changedView = original.getKey(); final int[] originalValue = original.getValue(); RelativeLayout.LayoutParams originalParams = (RelativeLayout.LayoutParams) changedView.getLayoutParams(); for (int i = 0; i < originalValue.length; i++) { originalParams.addRule(i, originalValue[i]); } changedView.setLayoutParams(originalParams); } mAlive = false; }

Target:
public void cleanup() { for (Map.Entry<View, int[]> original:mOriginalValues.entrySet()) { final View changedView = original.getKey(); final int[] originalValue = original.getValue(); final RelativeLayout.LayoutParams originalParams = (RelativeLayout.LayoutParams) changedView.getLayoutParams(); for (int i = 0; i < originalValue.length; i++) { originalParams.addRule(i, originalValue[i]); } changedView.setLayoutParams(originalParams); } mAlive = false; }
Source:
private static Page somePage(List<Type> types) { int[] initialValues = new int[types.size()]; Arrays.setAll(initialValues, i -> 100 * i); return SequencePageBuilder.createSequencePage(types, 7, initialValues); }

Target:
private static Page somePage(List<Type> types) { int[] initialValues = new int[types.size()]; Arrays.setAll(initialValues, i -> 100 * i); return createSequencePage(types, 7, initialValues); }
Source:
public KubernetesClient createKubernetesClient() { Config config = new ConfigBuilder() .withMasterUrl(masterUrl) .withUsername(user) .withPassword(password) .build(); return new DefaultKubernetesClient(config); }

Target:
public KubernetesClient createKubernetesClient() { final Config config = new ConfigBuilder() .withMasterUrl(masterUrl) .withUsername(user) .withPassword(password) .build(); return new DefaultKubernetesClient(config); }
Source:
public String toString() { StringBuilder str = new StringBuilder(); str.append('['); if (this.countArray.length > 0) { str.append(this.countArray[0]); } for (int index = 1; index < this.countArray.length; index++) { str.append(", "); str.append(this.countArray[index]); } str.append(']'); return str.toString(); }

Target:
public String toString() { updateCount(); return Arrays.toString(this.countArray); }
Source:
public CompletableFuture<PollerResult> execute() { Map<String, Object> props = new HashMap<>(); attributes.forEach(props::put); MonitoredService service = new SimpleMonitoredService(address, serviceName); CompletableFuture<PollerResponse> future = pollerClient.poll() .withService(service) .withMonitorClassName(className) .withTimeToLive(ttlInMs) .withAttributes(props) .execute(); CompletableFuture<PollerResult> result = new CompletableFuture<>(); PollStatus pollStatus; try { PollerResponse pollerResponse = future.get(); pollStatus = pollerResponse.getPollStatus(); switch (Status.valueOf(pollStatus.getStatusName())) { case Up: result.complete(new PollerResultImpl(Status.Up, pollStatus.getProperties())); break; case Down: result.complete(new PollerResultImpl(Status.Down, pollStatus.getReason())); break; case Unknown: result.complete(new PollerResultImpl(Status.Unknown, pollStatus.getReason())); break; case UnResponsive: result.complete(new PollerResultImpl(Status.UnResponsive, pollStatus.getReason())); break; default: result.complete(new PollerResultImpl(Status.Unknown, pollStatus.getReason())); } } catch (InterruptedException | ExecutionException e) { result.complete(new PollerResultImpl(Status.Unknown, e.getMessage())); } return result; }

Target:
public CompletableFuture<PollerResult> execute() { Map<String, Object> props = Collections.unmodifiableMap(attributes); MonitoredService service = new SimpleMonitoredService(address, serviceName); CompletableFuture<PollerResponse> future = pollerClient.poll() .withService(service) .withMonitorClassName(className) .withTimeToLive(ttlInMs) .withAttributes(props) .execute(); CompletableFuture<PollerResult> result = new CompletableFuture<>(); try { PollerResponse pollerResponse = future.get(); result.complete(new PollerResultImpl(pollerResponse.getPollStatus())); } catch (InterruptedException | ExecutionException e) { result.completeExceptionally(e); } return result; }
Source:
public void usingManagementRegistry() throws Exception { CacheConfiguration<Long, String> cacheConfiguration = CacheConfigurationBuilder.newCacheConfigurationBuilder() .withResourcePools(ResourcePoolsBuilder.newResourcePoolsBuilder().heap(10, EntryUnit.ENTRIES).build()) .buildConfig(Long.class, String.class); DefaultManagementRegistryConfiguration registryConfiguration = new DefaultManagementRegistryConfiguration().setCacheManagerAlias("myCacheManager"); ManagementRegistry managementRegistry = new DefaultManagementRegistry(registryConfiguration); CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder() .withCache("aCache", cacheConfiguration) .using(managementRegistry) .build(true); Cache<Long, String> aCache = cacheManager.getCache("aCache", Long.class, String.class); aCache.get(0L); aCache.get(0L); aCache.get(0L); Map<String, String> context = createContext(managementRegistry); Collection<Statistic<?, ?>> counters = managementRegistry.withCapability("StatisticsCapability") .queryStatistic("GetCounter") .on(context) .build() .execute() .get(0) .getStatistics(); Assert.assertThat(counters.size(), Matchers.is(1)); Counter getCounter = (Counter) counters.iterator().next(); Assert.assertThat(getCounter.getValue(), Matchers.equalTo(3L)); cacheManager.close(); }

Target:
public void usingManagementRegistry() throws Exception { CacheConfiguration<Long, String> cacheConfiguration = CacheConfigurationBuilder.newCacheConfigurationBuilder() .withResourcePools(ResourcePoolsBuilder.newResourcePoolsBuilder().heap(10, EntryUnit.ENTRIES).build()) .buildConfig(Long.class, String.class); DefaultManagementRegistryConfiguration registryConfiguration = new DefaultManagementRegistryConfiguration().setCacheManagerAlias("myCacheManager"); ManagementRegistry managementRegistry = new DefaultManagementRegistry(registryConfiguration); CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder() .withCache("aCache", cacheConfiguration) .using(managementRegistry) .build(true); Cache<Long, String> aCache = cacheManager.getCache("aCache", Long.class, String.class); aCache.get(0L); aCache.get(0L); aCache.get(0L); Context context = createContext(managementRegistry); ContextualStatistics counters = managementRegistry.withCapability("StatisticsCapability") .queryStatistic("GetCounter") .on(context) .build() .execute() .getSingleResult(); Assert.assertThat(counters.size(), Matchers.is(1)); Counter getCounter = counters.getStatistic(Counter.class); Assert.assertThat(getCounter.getValue(), Matchers.equalTo(3L)); cacheManager.close(); }
Source:
public void setUp() { final HashMap<String, String> keyStoreMap = new HashMap<>(); keyStoreMap.put(CertificateManagerImpl.KEY_STORE_KEY, KEY_STORE_PATH); keyStoreMap.put(CertificateManagerImpl.KEY_STORE_PSWRD_KEY, "changeit"); keyStoreMap.put(CertificateManagerImpl.KEY_STORE_TYPE_KEY, "JKS"); final HashMap<String, String> trustStoreMap = new HashMap<>(); trustStoreMap.put(CertificateManagerImpl.TRUST_STORE_KEY, TRUST_STORE_PATH); trustStoreMap.put(CertificateManagerImpl.TRUST_STORE_PSWRD_KEY, "changeit"); trustStoreMap.put(CertificateManagerImpl.TRUST_STORE_TYPE_KEY, "JKS"); certManager = (CertificateManagerImpl) CertificateManagerImpl.getInstance(keyStoreMap, trustStoreMap); }

Target:
public void setUp() { final HashMap<String, String> keyStoreMap = new HashMap<>(); keyStoreMap.put(CertificateManagerImpl.KEY_STORE_KEY, KEY_STORE_PATH); keyStoreMap.put(CertificateManagerImpl.KEY_STORE_PASSWORD_KEY, "changeit"); keyStoreMap.put(CertificateManagerImpl.KEY_STORE_TYPE_KEY, "JKS"); final HashMap<String, String> trustStoreMap = new HashMap<>(); trustStoreMap.put(CertificateManagerImpl.TRUST_STORE_KEY, TRUST_STORE_PATH); trustStoreMap.put(CertificateManagerImpl.TRUST_STORE_PASSWORD_KEY, "changeit"); trustStoreMap.put(CertificateManagerImpl.TRUST_STORE_TYPE_KEY, "JKS"); certManager = (CertificateManagerImpl) CertificateManagerImpl.getInstance(keyStoreMap, trustStoreMap); }
Source:
public void showDialog(Project project) { this.project = project; getCommitsLog(); selectedRevision = null; view.selectProjectChangesButton(true); view.selectResourceChangesButton(false); showChangesInProject = true; view.selectDiffWithPrevVersionButton(true); diffType = DiffWith.DIFF_WITH_PREV_VERSION; displayCommitA(null); displayCommitB(null); view.setDiffContext(""); view.setCompareType(constant.historyNothingToDisplay()); if (isViewClosed) { workspaceAgent.openPart(this, PartStackType.TOOLING); isViewClosed = false; } partStack.setActivePart(HistoryPresenter.this); }

Target:
public void showDialog(Project project) { this.project = project; getCommitsLog(); selectedRevision = null; view.selectProjectChangesButton(true); view.selectResourceChangesButton(false); showChangesInProject = true; view.selectDiffWithPrevVersionButton(true); diffType = DiffWith.DIFF_WITH_PREV_VERSION; displayCommitA(null); displayCommitB(null); view.setDiffContext(""); view.setCompareType(constant.historyNothingToDisplay()); if (isViewClosed) { workspaceAgent.openPart(this, PartStackType.TOOLING); isViewClosed = false; } partStack.setActivePart(this); }
Source:
public void testConcurrentMoveSiblings() throws Exception { final int N = 5; final Fqn X = Fqn.fromString("/x"), Y = Fqn.fromString("/y"); Node<Object, Object> rootNode = treeCache.getRoot(); Node<Object, Object> nodeA = rootNode.addChild(A); nodeA.addChild(X); nodeA.addChild(Y); Node<Object, Object> nodeB = rootNode.addChild(B); Node<Object, Object> nodeC = rootNode.addChild(C); Callable<Object>[] movers = new Callable[N]; for (int i = 0; i < N; i++) { final Fqn source = Fqn.fromRelativeFqn(A, i % 2 == 0 ? X : Y); final Fqn dest = i % 2 == 0 ? B : C; movers[i] = new Callable<Object>() { public Object call() { try { treeCache.move(source, dest); } catch (Exception e) { } return null; } }; } runConcurrently(movers[0], movers[1], Arrays.copyOfRange(movers, 2, movers.length)); log.info("Tree: " + TreeStructureSupport.printTree(treeCache, true)); assertNoLocks(); assertTrue(nodeA.getChildrenNames().contains("x") ^ nodeB.getChildrenNames().contains("x")); assertTrue(nodeA.getChildrenNames().contains("y") ^ nodeC.getChildrenNames().contains("y")); }

Target:
public void testConcurrentMoveSiblings() throws Exception { final int N = 5; final Fqn X = Fqn.fromString("/x"), Y = Fqn.fromString("/y"); Node<Object, Object> rootNode = treeCache.getRoot(); Node<Object, Object> nodeA = rootNode.addChild(A); nodeA.addChild(X); nodeA.addChild(Y); Node<Object, Object> nodeB = rootNode.addChild(B); Node<Object, Object> nodeC = rootNode.addChild(C); Callable<Object>[] movers = new Callable[N]; for (int i = 0; i < N; i++) { final Fqn source = Fqn.fromRelativeFqn(A, i % 2 == 0 ? X : Y); final Fqn dest = i % 2 == 0 ? B : C; movers[i] = new Callable<Object>() { public Object call() { try { treeCache.move(source, dest); } catch (Exception e) { } return null; } }; } runConcurrently(movers); log.info("Tree: " + TreeStructureSupport.printTree(treeCache, true)); assertNoLocks(); assertTrue(nodeA.getChildrenNames().contains("x") ^ nodeB.getChildrenNames().contains("x")); assertTrue(nodeA.getChildrenNames().contains("y") ^ nodeC.getChildrenNames().contains("y")); }
Source:
private ChangeDetail cherryPickRest(Id id, String message, String destBranch, IProgressMonitor monitor) throws GerritException { String url = "/changes/" + id.getParentKey() + "/revisions/" + id.get() + "/cherrypick"; CherryPickInput input = new CherryPickInput(message, destBranch); ChangeInfo result = executePostRestRequest(url, input, ChangeInfo.class, new ErrorHandler() { @Override public void handleError(HttpMethodBase method) throws GerritException { String errorMsg = getResponseBodyAsString(method); if (isNotPermitted(method, errorMsg)) { errorMsg = NLS.bind("Cannot cherry pick: {0}", errorMsg); } else if (isConflict(method)) { errorMsg = NLS.bind("Request Conflict: {0}", errorMsg); } else if (isBadRequest(method)) { errorMsg = NLS.bind("Bad Request: {0}", errorMsg); } throw new GerritException(errorMsg); } private String getResponseBodyAsString(HttpMethodBase method) { try { return method.getResponseBodyAsString(); } catch (IOException e) { return null; } } private boolean isNotPermitted(HttpMethodBase method, String msg) { return method.getStatusCode() == HttpURLConnection.HTTP_FORBIDDEN && "cherry pick not permitted\n".equals(msg); } private boolean isConflict(HttpMethodBase method) { return method.getStatusCode() == HttpURLConnection.HTTP_CONFLICT; } private boolean isBadRequest(HttpMethodBase method) { return method.getStatusCode() == HttpURLConnection.HTTP_BAD_REQUEST; } }, monitor); return getChangeDetail(result.getNumber(), monitor); }

Target:
private ChangeDetail cherryPickRest(Id id, String message, String destBranch, IProgressMonitor monitor) throws GerritException { String url = "/changes/" + id.getParentKey() + "/revisions/" + id.get() + "/cherrypick"; CherryPickInput input = new CherryPickInput(message, destBranch); ChangeInfo result = executePostRestRequest(url, input, ChangeInfo.class, new ErrorHandler() { @Override public void handleError(HttpMethodBase method) throws GerritException { String errorMsg = getResponseBodyAsString(method); if (isNotPermitted(method, errorMsg)) { errorMsg = NLS.bind("Cannot cherry pick: {0}", errorMsg); } else if (isConflict(method)) { errorMsg = NLS.bind("Request Conflict: {0}", errorMsg); } else if (isBadRequest(method)) { errorMsg = NLS.bind("Bad Request: {0}", errorMsg); } throw new GerritException(errorMsg); } private String getResponseBodyAsString(HttpMethodBase method) { try { return method.getResponseBodyAsString(); } catch (IOException e) { return null; } } private boolean isNotPermitted(HttpMethodBase method, String msg) { return method.getStatusCode() == HttpURLConnection.HTTP_FORBIDDEN && msg.toLowerCase().startsWith("cherry pick not permitted"); } private boolean isConflict(HttpMethodBase method) { return method.getStatusCode() == HttpURLConnection.HTTP_CONFLICT; } private boolean isBadRequest(HttpMethodBase method) { return method.getStatusCode() == HttpURLConnection.HTTP_BAD_REQUEST; } }, monitor); return getChangeDetail(result.getNumber(), monitor); }
Source:
public List<String> getBrokersForTable( @ApiParam(value = "Name of the table", required = true) @PathParam("tableName") String tableName, @ApiParam(value = "OFFLINE|REALTIME") @QueryParam("type") String tableTypeStr, @ApiParam(value = "ONLINE|OFFLINE") @QueryParam("state") String state) { try { List<String> tableNamesWithType = _pinotHelixResourceManager .getExistingTableNamesWithType(tableName, Constants.validateTableType(tableTypeStr)); if (tableNamesWithType.isEmpty()) { throw new ControllerApplicationException(LOGGER, String.format("Table [%s] not found.", tableName), Response.Status.NOT_FOUND); } Set<String> tableBrokers = new HashSet<>(_pinotHelixResourceManager.getBrokerInstancesFor(tableNamesWithType.get(0))); applyStateChanges(tableBrokers, state); return ImmutableList.copyOf(tableBrokers); } catch (TableNotFoundException e) { throw new ControllerApplicationException(LOGGER, e.getMessage(), Response.Status.NOT_FOUND); } catch (IllegalArgumentException e) { throw new ControllerApplicationException(LOGGER, e.getMessage(), Response.Status.FORBIDDEN); } }

Target:
public List<String> getBrokersForTable( @ApiParam(value = "Name of the table", required = true) @PathParam("tableName") String tableName, @ApiParam(value = "OFFLINE|REALTIME") @QueryParam("type") String tableTypeStr, @ApiParam(value = "ONLINE|OFFLINE") @QueryParam("state") String state) { try { List<String> tableNamesWithType = _pinotHelixResourceManager .getExistingTableNamesWithType(tableName, Constants.validateTableType(tableTypeStr)); if (tableNamesWithType.isEmpty()) { throw new ControllerApplicationException(LOGGER, String.format("Table '%s' not found.", tableName), Response.Status.NOT_FOUND); } Set<String> tableBrokers = new HashSet<>(_pinotHelixResourceManager.getBrokerInstancesFor(tableNamesWithType.get(0))); applyStateChanges(tableBrokers, state); return ImmutableList.copyOf(tableBrokers); } catch (TableNotFoundException e) { throw new ControllerApplicationException(LOGGER, String.format("Table '%s' not found.", tableName), Response.Status.NOT_FOUND); } catch (IllegalArgumentException e) { throw new ControllerApplicationException(LOGGER, e.getMessage(), Response.Status.FORBIDDEN); } }
Source:
private void cannedReply(String message) { final PatchLineComment newComment = newComment(); newComment.setMessage(message); CommentEditorPanel p = createEditor(newComment, false); if (p == null) { PatchUtil.DETAIL_SVC.saveDraft(newComment, new GerritCallback<PatchLineComment>() { public void onSuccess(final PatchLineComment result) { enableButtons(true); notifyDraftDelta(1); createEditor(result, true).setOpen(false); } @Override public void onFailure(Throwable caught) { enableButtons(true); super.onFailure(caught); } }); } else { if (!p.isOpen()) { p.setOpen(true); } p.setFocus(true); } }

Target:
private void cannedReply(String message) { final PatchLineComment newComment = newComment(); newComment.setMessage(message); CommentEditorPanel p = createEditor(newComment, false); if (p == null) { enableButtons(false); PatchUtil.DETAIL_SVC.saveDraft(newComment, new GerritCallback<PatchLineComment>() { public void onSuccess(final PatchLineComment result) { enableButtons(true); notifyDraftDelta(1); createEditor(result, true).setOpen(false); } @Override public void onFailure(Throwable caught) { enableButtons(true); super.onFailure(caught); } }); } else { if (!p.isOpen()) { p.setOpen(true); } p.setFocus(true); } }
Source:
public void cleanEnvironment() throws Exception { System.clearProperty("java.security.auth.login.config"); try { ArrayList<Starter<?>> reversedStarters = new ArrayList<>(STARTERS.values()); Collections.reverse(reversedStarters); for (Starter<?> starter : reversedStarters) { starter.stop(); } zookeeper.close(); logger.info("Environment cleaned"); } catch (Exception e) { logger.error("Exception during environment cleaning", e); } }

Target:
public void cleanEnvironment() throws Exception { try { ArrayList<Starter<?>> reversedStarters = new ArrayList<>(STARTERS.values()); Collections.reverse(reversedStarters); for (Starter<?> starter : reversedStarters) { starter.stop(); } zookeeper.close(); logger.info("Environment cleaned"); } catch (Exception e) { logger.error("Exception during environment cleaning", e); } }
Source:
public static String bytesToHex(byte[] data) { if (data == null) { return null; } int len = data.length; String str = ""; for (int i = 0; i < len; i++) { if ((data[i] & 0xFF) < 16) { str = str + "0" + java.lang.Integer.toHexString(data[i] & 0xFF); } else { str = str + java.lang.Integer.toHexString(data[i] & 0xFF); } } return str; }

Target:
public static String bytesToHex(byte[] data) { if (data == null) { return null; } int len = data.length; String str = ""; for (int i = 0; i < len; i++) { if ((data[i] & 0xFF) < 16) { str = str + "0" + Integer.toHexString(data[i] & 0xFF); } else { str = str + Integer.toHexString(data[i] & 0xFF); } } return str; }
Source:
public void start() { ScheduledExecutors.scheduleAtFixedRate( processingExecutor, Period.ZERO.toStandardDuration(), Period.millis(100).toStandardDuration(), new Runnable() { @Override public void run() { processSegmentChangeRequest(); } } ); }

Target:
public void start() { ScheduledExecutors.scheduleAtFixedRate( processingExecutor, config.getLoadQueuePeonRepeatDelay(), config.getLoadQueuePeonRepeatDelay(), new Callable<ScheduledExecutors.Signal>() { @Override public ScheduledExecutors.Signal call() { processSegmentChangeRequest(); if (stopped) { return ScheduledExecutors.Signal.STOP; } else { return ScheduledExecutors.Signal.REPEAT; } } } ); }
Source:
private static AggregationConfiguration getAggregationConfigurationForSSP() { return AggregationConfiguration.newBuilder() .addAggregationClient(SynchronizationManager.AGGREGATION_CLIENT_NAME, SynchronizationManager.MessageHandler.class, WorkerSynchronizer.MessageHandler.class) .addAggregationClient(WorkerConstants.AGGREGATION_CLIENT_NAME, DriverSideMetricsMsgHandlerForWorker.class, EvalSideMetricsMsgHandlerForWorker.class) .addAggregationClient(ServerConstants.AGGREGATION_CLIENT_NAME, DriverSideMetricsMsgHandlerForServer.class, EvalSideMetricsMsgHandlerForServer.class) .addAggregationClient(ClockManager.AGGREGATION_CLIENT_NAME, ClockManager.MessageHandler.class, SSPWorkerClock.MessageHandler.class) .build(); }

Target:
private static AggregationConfiguration getAggregationConfigurationForSSP() { return getAggregationConfigurationDefaultBuilder() .addAggregationClient(ClockManager.AGGREGATION_CLIENT_NAME, ClockManager.MessageHandler.class, SSPWorkerClock.MessageHandler.class) .build(); }
Source:
private void initRenderGraph() { RenderGraph renderGraph = new RenderGraph(); addShadowMapNodes(renderGraph); addReflectionNodes(renderGraph); addSkyNodes(renderGraph); addWorldRenderingNodes(renderGraph); addLightingNodes(renderGraph); addRefractiveReflectiveNode(renderGraph); add3dDecorationNodes(renderGraph); addPrePostProcessingNodes(renderGraph); addPostProcessingNodes(renderGraph); addImageToSceeenNodes(renderGraph); renderTaskListGenerator = new RenderTaskListGenerator(); List<Node> orderedNodes = renderGraph.getNodesInTopologicalOrder(); renderPipelineTaskList = renderTaskListGenerator.generateFrom(orderedNodes); }

Target:
private void initRenderGraph() { RenderGraph renderGraph = new RenderGraph(); addShadowMapNodes(renderGraph); addReflectionNodes(renderGraph); addSkyNodes(renderGraph); addWorldRenderingNodes(renderGraph); addLightingNodes(renderGraph); addRefractiveReflectiveNode(renderGraph); add3dDecorationNodes(renderGraph); addPrePostProcessingNodes(renderGraph); addPostProcessingNodes(renderGraph); addCopyOutputNodes(renderGraph); renderTaskListGenerator = new RenderTaskListGenerator(); List<Node> orderedNodes = renderGraph.getNodesInTopologicalOrder(); renderPipelineTaskList = renderTaskListGenerator.generateFrom(orderedNodes); }
Source:
ConfigurationPanel(ExportConfiguration initialConfiguration, ConfigurationPanelForm form) { this.form = form; configuration = initialConfiguration.copy(); configuration.ifExportDirPresent(form::setExportDir); configuration.ifPemFilePresent(form::setPemFile); configuration.ifStartDatePresent(form::setStartDate); configuration.ifEndDatePresent(form::setEndDate); configuration.ifPullBeforePresent(form::setPullBefore); configuration.ifPullBeforeOverridePresent(form::setPullBeforeOverride); form.onSelectExportDir(path -> { configuration.setExportDir(path); triggerOnChange(); }); form.onSelectPemFile(path -> { if (path == null) { configuration.removePemFile(); } else { configuration.setPemFile(path); } triggerOnChange(); }); form.onSelectDateRangeStart(date -> { configuration.setStartDate(date); triggerOnChange(); }); form.onSelectDateRangeEnd(date -> { configuration.setEndDate(date); triggerOnChange(); }); form.onChangePullBefore(pullBefore -> { configuration.setPullBefore(pullBefore); triggerOnChange(); }); form.onChangePullBeforeOverride(pullBeforeOverrideOption -> { configuration.setPullBeforeOverride(pullBeforeOverrideOption); triggerOnChange(); }); }

Target:
ConfigurationPanel(ExportConfiguration initialConfiguration, ConfigurationPanelForm form) { this.form = form; configuration = initialConfiguration.copy(); configuration.ifExportDirPresent(form::setExportDir); configuration.ifPemFilePresent(form::setPemFile); configuration.ifStartDatePresent(form::setStartDate); configuration.ifEndDatePresent(form::setEndDate); configuration.ifPullBeforePresent(form::setPullBefore); configuration.ifPullBeforeOverridePresent(form::setPullBeforeOverride); configuration.ifOverwriteExistingFilesPresent(form::setOverwriteExistingFiles); form.onSelectExportDir(path -> { configuration.setExportDir(path); triggerOnChange(); }); form.onSelectPemFile(path -> { configuration.setPemFile(path); triggerOnChange(); }); form.onSelectDateRangeStart(date -> { configuration.setStartDate(date); triggerOnChange(); }); form.onSelectDateRangeEnd(date -> { configuration.setEndDate(date); triggerOnChange(); }); form.onChangePullBefore(pullBefore -> { configuration.setPullBefore(pullBefore); triggerOnChange(); }); form.onChangePullBeforeOverride(pullBeforeOverrideOption -> { configuration.setPullBeforeOverride(pullBeforeOverrideOption); triggerOnChange(); }); form.onChangeOverwriteExistingFiles(overwriteExistingFiles -> { configuration.setOverwriteExistingFiles(overwriteExistingFiles); triggerOnChange(); }); }
Source:
public PersonMetrics(PersonService personService) { this.personService = personService; }

Target:
PersonMetrics(PersonService personService) { this.personService = personService; }
Source:
public static Type getReturnType(int functionId) { for (FunctionDescriptor func : FunctionDescriptor.m_defined_functions.values()) { if (func.getId() == functionId) { return func.getDataType(); } } return null; }

Target:
public static Type getReturnType(int functionId) { return m_defined_functions_by_id.get(functionId).getDataType(); }
Source:
public JSONObject getObjects(List<String> objectIDs, List<String> attributesToRetrieve) throws AlgoliaException { try { JSONArray requests = new JSONArray(); for (String id : objectIDs) { JSONObject request = new JSONObject(); request.put("indexName", this.indexName); request.put("objectID", id); request.put("attributesToRetrieve", encodeAttributes(attributesToRetrieve, false)); requests.put(request); } JSONObject body = new JSONObject(); body.put("requests", requests); return client.postRequest("/1/indexes/*/objects", body.toString(), false, false); } catch (JSONException e) { throw new AlgoliaException(e.getMessage()); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } }

Target:
public JSONObject getObjects(List<String> objectIDs, List<String> attributesToRetrieve) throws AlgoliaException { try { JSONArray requests = new JSONArray(); for (String id : objectIDs) { JSONObject request = new JSONObject(); request.put("indexName", this.indexName); request.put("objectID", id); request.put("attributesToRetrieve", encodeAttributes(attributesToRetrieve, false)); requests.put(request); } JSONObject body = new JSONObject(); body.put("requests", requests); return client.postRequest("/1/indexes/*/objects", body.toString(), false, false); } catch (JSONException e) { throw new AlgoliaException(e.getMessage()); } catch (UnsupportedEncodingException e) { throw new AlgoliaException(e.getMessage()); } }
Source:
private SSLEngineResult.HandshakeStatus unwrap(SocketChannel socketChannel, SSLEngine engine) throws IOException { if (socketChannel.read(m_netEncData) < 0) { if (engine.isInboundDone() && engine.isOutboundDone()) { return null; } try { engine.closeInbound(); } catch (SSLException e) { } engine.closeOutbound(); return engine.getHandshakeStatus(); } m_netEncData.flip(); SSLEngineResult.HandshakeStatus hs; SSLEngineResult res; try { res = engine.unwrap(m_netEncData, m_netClearData); m_netEncData.compact(); hs = res.getHandshakeStatus(); } catch (SSLException e) { System.err.println("unwrap: see ssl exception " + e.getMessage()); engine.closeOutbound(); return engine.getHandshakeStatus(); } switch (res.getStatus()) { case OK: break; case BUFFER_OVERFLOW: m_netClearData = ByteBuffer.allocate(m_netClearData.capacity() * 2);; break; case BUFFER_UNDERFLOW: break; case CLOSED: if (engine.isOutboundDone()) { return null; } else { engine.closeOutbound(); hs = engine.getHandshakeStatus(); } break; } return hs; }

Target:
private SSLEngineResult.HandshakeStatus unwrap(SocketChannel socketChannel, SSLEngine engine) throws IOException { if (socketChannel.read(m_encrypted) < 0) { if (engine.isInboundDone() && engine.isOutboundDone()) { return null; } try { engine.closeInbound(); } catch (SSLException e) { } engine.closeOutbound(); return engine.getHandshakeStatus(); } m_encrypted.flip(); SSLEngineResult.HandshakeStatus hs; SSLEngineResult res; try { res = engine.unwrap(m_encrypted, m_clear); m_encrypted.compact(); hs = res.getHandshakeStatus(); } catch (SSLException e) { engine.closeOutbound(); throw e; } switch (res.getStatus()) { case OK: break; case BUFFER_OVERFLOW: m_clear = ByteBuffer.allocate(m_clear.capacity() << 1); break; case BUFFER_UNDERFLOW: break; case CLOSED: if (engine.isOutboundDone()) { return null; } else { engine.closeOutbound(); hs = engine.getHandshakeStatus(); } break; } return hs; }
Source:
public List<Bitstream> getBitstreams(Context context, Process process, String type) { List<Bitstream> allBitstreams = process.getBitstreams(); if (type == null) { return allBitstreams; } else { List<Bitstream> filteredBitstreams = new ArrayList<>(); for (Bitstream bitstream : allBitstreams) { if (StringUtils.equals(bitstreamService.getMetadata(bitstream, "dspace.process.type"), type)) { filteredBitstreams.add(bitstream); } } return filteredBitstreams; } }

Target:
public List<Bitstream> getBitstreams(Context context, Process process, String type) { List<Bitstream> allBitstreams = process.getBitstreams(); if (type == null) { return allBitstreams; } else { List<Bitstream> filteredBitstreams = new ArrayList<>(); for (Bitstream bitstream : allBitstreams) { if (StringUtils.equals(bitstreamService.getMetadata(bitstream, Process.BITSTREAM_TYPE_METADATAFIELD), type)) { filteredBitstreams.add(bitstream); } } return filteredBitstreams; } }
Source:
public void cache_instance_of_StorageFactory_in_production() { Supplier<StorageFactory> productionSupplier = spy(inMemorySupplier); storageFactorySwitch.init(productionSupplier, inMemorySupplier); Environment.getInstance().setToProduction(); storageFactorySwitch.get(); storageFactorySwitch.get(); verify(productionSupplier, times(1)).get(); }

Target:
public void cache_instance_of_StorageFactory_in_production() { final Supplier<StorageFactory> productionSupplier = spy(inMemorySupplier); storageFactorySwitch.init(productionSupplier, inMemorySupplier); Environment.getInstance().setToProduction(); storageFactorySwitch.get(); storageFactorySwitch.get(); verify(productionSupplier, times(1)).get(); }
Source:
public void getOnlyRequestedAttributes() { Set<String> requestedAttributes = new HashSet<>(); requestedAttributes.add("attribute1"); Set<AttributeDescriptor> onlyRequestedAttributes = CsvTransformer.getOnlyRequestedAttributes( metacardList, requestedAttributes, Collections.emptySet()); assertThat(onlyRequestedAttributes, hasSize(1)); final String name = onlyRequestedAttributes.stream().findFirst().get().getName(); assertThat(name, is("attribute1")); }

Target:
public void getOnlyRequestedAttributes() { Set<String> requestedAttributes = new HashSet<>(); requestedAttributes.add("attribute1"); Set<AttributeDescriptor> onlyRequestedAttributes = CsvTransformer.getOnlyRequestedAttributes(metacardList, requestedAttributes); assertThat(onlyRequestedAttributes, hasSize(1)); final Optional<AttributeDescriptor> attributeDescriptorOptional = onlyRequestedAttributes.stream().findFirst(); assertThat(attributeDescriptorOptional.isPresent(), is(true)); final AttributeDescriptor attributeDescriptor = attributeDescriptorOptional.get(); assertThat(attributeDescriptor, notNullValue()); final String name = attributeDescriptor.getName(); assertThat(name, is("attribute1")); }
Source:
void refreshPoolsWithRegeneration(Owner owner, boolean lazy) { log.info("Refreshing pools for owner: " + owner.getKey()); List<String> subIds = subAdapter.getSubscriptionIds(owner); log.debug("Found " + subIds.size() + " existing subscriptions."); List<String> deletedSubs = new LinkedList<String>(); for (String subId : subIds) { Subscription sub = subAdapter.getSubscription(subId); if (sub == null) { deletedSubs.add(subId); log.warn("Couldn't load subscription, assuming it has been deleted: " + subId); continue; } if (isExpired(sub)) { deletedSubs.add(subId); log.info("Deleting expired subscription: " + sub); subAdapter.deleteSubscription(sub); continue; } refreshPoolsForSubscription(sub, lazy); } Pool ueberPool = this.findUeberPool(owner); String ueberPoolId = ueberPool != null ? ueberPool.getId() : null; subIds.removeAll(deletedSubs); List<Pool> poolsToDelete = new ArrayList<Pool>(); for (Pool p : poolCurator.getPoolsFromBadSubs(owner, subIds)) { if ((p.getType() == PoolType.NORMAL || p.getType() == PoolType.BONUS) && (ueberPoolId == null || !ueberPoolId.equals(p.getId()))) { poolsToDelete.add(p); } } if (!poolsToDelete.isEmpty()) { deletePools(poolsToDelete); } List<Pool> floatingPools = poolCurator.getOwnersFloatingPools(owner); updateFloatingPools(floatingPools, lazy); }

Target:
void refreshPoolsWithRegeneration(Owner owner, boolean lazy) { log.info("Refreshing pools for owner: " + owner.getKey()); List<String> subIds = subAdapter.getSubscriptionIds(owner); log.debug("Found " + subIds.size() + " existing subscriptions."); List<String> deletedSubs = new LinkedList<String>(); for (String subId : subIds) { Subscription sub = subAdapter.getSubscription(subId); if (sub == null) { deletedSubs.add(subId); log.warn("Couldn't load subscription, assuming it has been deleted: " + subId); continue; } if (isExpired(sub)) { deletedSubs.add(subId); log.info("Deleting expired subscription: " + sub); subAdapter.deleteSubscription(sub); continue; } refreshPoolsForSubscription(sub, lazy); } Pool ueberPool = this.findUeberPool(owner); String ueberPoolId = ueberPool != null ? ueberPool.getId() : null; subIds.removeAll(deletedSubs); List<Pool> poolsToDelete = new ArrayList<Pool>(); for (Pool p : poolCurator.getPoolsFromBadSubs(owner, subIds)) { if ((p.getType() == PoolType.NORMAL || p.getType() == PoolType.BONUS) && (ueberPoolId == null || !ueberPoolId.equals(p.getId()))) { poolsToDelete.add(p); } } deletePools(poolsToDelete); List<Pool> floatingPools = poolCurator.getOwnersFloatingPools(owner); updateFloatingPools(floatingPools, lazy); }
Source:
public void run() { if (!isComplete()) { encryptJobMetricsTracker.onJobProcessingStart(); ByteBuffer encryptedBlobContent = null; ByteBuffer encryptedUserMetadata = null; ByteBuffer encryptedKey = null; Exception exception = null; if (!isComplete()) { try { if (blobContentToEncrypt != null) { encryptedBlobContent = cryptoService.encrypt(blobContentToEncrypt, perBlobKey); } if (userMetadataToEncrypt != null) { encryptedUserMetadata = cryptoService.encrypt(userMetadataToEncrypt, perBlobKey); } Object containerKey = kms.getKey(accountId, containerId); encryptedKey = cryptoService.encryptKey(perBlobKey, containerKey); } catch (Exception e) { exception = e; } finally { encryptJobMetricsTracker.onJobProcessingComplete(); } completeJob( exception == null ? new EncryptJobResult(encryptedKey, encryptedBlobContent, encryptedUserMetadata) : null, exception); } } }

Target:
public void run() { if (!isComplete()) { encryptJobMetricsTracker.onJobProcessingStart(); ByteBuffer encryptedBlobContent = null; ByteBuffer encryptedUserMetadata = null; ByteBuffer encryptedKey = null; Exception exception = null; if (!isComplete()) { try { if (blobContentToEncrypt != null) { encryptedBlobContent = cryptoService.encrypt(blobContentToEncrypt, perBlobKey); } if (userMetadataToEncrypt != null) { encryptedUserMetadata = cryptoService.encrypt(userMetadataToEncrypt, perBlobKey); } Object containerKey = kms.getKey(accountId, containerId); encryptedKey = cryptoService.encryptKey(perBlobKey, containerKey); } catch (Exception e) { exception = e; } finally { encryptJobMetricsTracker.onJobProcessingComplete(); completeJob( exception == null ? new EncryptJobResult(encryptedKey, encryptedBlobContent, encryptedUserMetadata) : null, exception); } } } }
Source:
private void checkInputPriorities(ExecNode<?, ?> node) { TreeMap<Integer, List<Integer>> inputPriorityGroupMap = new TreeMap<>(); Preconditions.checkState( node.getInputNodes().size() == node.getInputEdges().size(), "Number of inputs nodes does not equal to number of input edges for node " + node.getClass().getName() + ". This is a bug."); for (int i = 0; i < node.getInputNodes().size(); i++) { int priority = node.getInputEdges().get(i).getPriority(); inputPriorityGroupMap.computeIfAbsent(priority, k -> new ArrayList<>()).add(i); } List<List<Integer>> inputPriorityGroups = new ArrayList<>(inputPriorityGroupMap.values()); for (int i = 0; i + 1 < inputPriorityGroups.size(); i++) { List<Integer> higherGroup = inputPriorityGroups.get(i); List<Integer> lowerGroup = inputPriorityGroups.get(i + 1); for (int higher : higherGroup) { for (int lower : lowerGroup) { addTopologyEdges(node, higher, lower); } } } }

Target:
private void checkInputPriorities(ExecNode<?, ?> node) { TreeMap<Integer, List<Integer>> inputPriorityGroupMap = new TreeMap<>(); Preconditions.checkState( node.getInputNodes().size() == node.getInputEdges().size(), "Number of inputs nodes does not equal to number of input edges for node " + node.getClass().getName() + ". This is a bug."); for (int i = 0; i < node.getInputEdges().size(); i++) { int priority = node.getInputEdges().get(i).getPriority(); inputPriorityGroupMap.computeIfAbsent(priority, k -> new ArrayList<>()).add(i); } List<List<Integer>> inputPriorityGroups = new ArrayList<>(inputPriorityGroupMap.values()); for (int i = 0; i + 1 < inputPriorityGroups.size(); i++) { List<Integer> higherGroup = inputPriorityGroups.get(i); List<Integer> lowerGroup = inputPriorityGroups.get(i + 1); for (int higher : higherGroup) { for (int lower : lowerGroup) { addTopologyEdges(node, higher, lower); } } } }
Source:
public MulticlassMetrics (MulticlassConfusionMatrix multiclassConfusionMatrix) { this.multiclassConfusionMatrix = multiclassConfusionMatrix; double[][] matrix = multiclassConfusionMatrix.getMatrix(); double truePositive = matrix[0][0]; double falseNegative = matrix[0][1]; double falsePositive = matrix[1][0]; double trueNegative = matrix[1][1]; this.f1Score = (2 * truePositive / (2 * truePositive + falsePositive + falseNegative)); this.accuracy = ((truePositive + trueNegative) / (truePositive + trueNegative + falsePositive + falseNegative)) * 100; this.precision = (truePositive / (truePositive + falsePositive)) * 100; this.recall = (truePositive / (truePositive + falseNegative)) * 100; }

Target:
public MulticlassMetrics (MulticlassConfusionMatrix multiclassConfusionMatrix) { this.multiclassConfusionMatrix = multiclassConfusionMatrix; double[][] matrix = multiclassConfusionMatrix.getMatrix(); double truePositive = matrix[0][0]; double falseNegative = matrix[0][1]; double falsePositive = matrix[1][0]; double trueNegative = matrix[1][1]; if (isDenominatorZero(truePositive, falsePositive, falseNegative)) { this.f1Score = 0; } else { this.f1Score = (2 * truePositive / (2 * truePositive + falsePositive + falseNegative)); } if (isDenominatorZero(truePositive, trueNegative, falsePositive, falseNegative)) { this.accuracy = 0; } else { this.accuracy = ((truePositive + trueNegative) / (truePositive + trueNegative + falsePositive + falseNegative)) * 100; } if (isDenominatorZero(truePositive, falsePositive)) { this.precision = 0; } else { this.precision = (truePositive / (truePositive + falsePositive)) * 100; } if (isDenominatorZero(truePositive, falseNegative)) { this.recall = 0; } else { this.recall = (truePositive / (truePositive + falseNegative)) * 100; } }
Source:
public ValidationResult validate(NamespaceInfo namespace, boolean isNew) { if (namespace.isIsolated() && !getCatalogCapabilities().areIsolatedWorkspacesSupported()) { throw new IllegalArgumentException(String.format( "Namespace '%s:%s' is isolated but isolated workspaces are not supported by this catalog.", namespace.getPrefix(), namespace.getURI())); } if ( isNull(namespace.getPrefix()) ) { throw new NullPointerException( "Namespace prefix must not be null"); } if(namespace.getPrefix().equals(DEFAULT)) { throw new IllegalArgumentException(DEFAULT + " is a reserved keyword, can't be used as the namespace prefix"); } NamespaceInfo existing = getNamespaceByPrefix( namespace.getPrefix() ); if ( existing != null && !existing.getId().equals( namespace.getId() ) ) { throw new IllegalArgumentException( "Namespace with prefix '" + namespace.getPrefix() + "' already exists."); } if (!namespace.isIsolated()) { existing = getNamespaceByURI(namespace.getURI()); if (existing != null && !existing.getId().equals(namespace.getId())) { throw new IllegalArgumentException("Namespace with URI '" + namespace.getURI() + "' already exists."); } } if ( isNull(namespace.getURI()) ) { throw new NullPointerException( "Namespace uri must not be null"); } try { new URI(namespace.getURI()); } catch(Exception e) { throw new IllegalArgumentException("Invalid URI syntax for '" + namespace.getURI() + "' in namespace '" + namespace.getPrefix() + "'"); } return postValidate(namespace, isNew); }

Target:
public ValidationResult validate(NamespaceInfo namespace, boolean isNew) { if (namespace.isIsolated() && !getCatalogCapabilities().supportsIsolatedWorkspaces()) { throw new IllegalArgumentException(String.format( "Namespace '%s:%s' is isolated but isolated workspaces are not supported by this catalog.", namespace.getPrefix(), namespace.getURI())); } if ( isNull(namespace.getPrefix()) ) { throw new NullPointerException( "Namespace prefix must not be null"); } if(namespace.getPrefix().equals(DEFAULT)) { throw new IllegalArgumentException(DEFAULT + " is a reserved keyword, can't be used as the namespace prefix"); } NamespaceInfo existing = getNamespaceByPrefix( namespace.getPrefix() ); if ( existing != null && !existing.getId().equals( namespace.getId() ) ) { throw new IllegalArgumentException( "Namespace with prefix '" + namespace.getPrefix() + "' already exists."); } if (!namespace.isIsolated()) { existing = getNamespaceByURI(namespace.getURI()); if (existing != null && !existing.getId().equals(namespace.getId())) { throw new IllegalArgumentException("Namespace with URI '" + namespace.getURI() + "' already exists."); } } if ( isNull(namespace.getURI()) ) { throw new NullPointerException( "Namespace uri must not be null"); } try { new URI(namespace.getURI()); } catch(Exception e) { throw new IllegalArgumentException("Invalid URI syntax for '" + namespace.getURI() + "' in namespace '" + namespace.getPrefix() + "'"); } return postValidate(namespace, isNew); }
Source:
private static File getDevServerPortFile(File npmFolder) { String threadGroup = String .valueOf(Thread.currentThread().getThreadGroup().hashCode()); String frontendBuildPath = npmFolder.getAbsolutePath(); String uniqueUid = UUID .nameUUIDFromBytes((threadGroup + frontendBuildPath) .getBytes(StandardCharsets.UTF_8)) .toString(); return new File(System.getProperty("java.io.tmpdir"), uniqueUid); }

Target:
private static File getDevServerPortFile(File npmFolder) { String jvmUuid = System.getProperty(WEBPACK_PORTFILE_UUID_PROPERTY); if (jvmUuid == null) { jvmUuid = UUID.randomUUID().toString(); System.setProperty(WEBPACK_PORTFILE_UUID_PROPERTY, jvmUuid); } String frontendBuildPath = npmFolder.getAbsolutePath(); String uniqueUid = UUID.nameUUIDFromBytes( (jvmUuid + frontendBuildPath).getBytes(StandardCharsets.UTF_8)) .toString(); return new File(System.getProperty("java.io.tmpdir"), uniqueUid); }
Source:
protected ICommand getReparentViewCommand(IGraphicalEditPart gep) { if (gep instanceof ConnectionEditPart) { return EmptyExecutableCommand.INSTANCE; } return super.getReparentViewCommand(gep); }

Target:
protected ICommand getReparentViewCommand(IGraphicalEditPart gep) { if (gep instanceof ConnectionEditPart && gep.getParent() instanceof DiagramRootEditPart) { return null; } return super.getReparentViewCommand(gep); }
Source:
public Boolean getXD_JMX_ENABLED() { return (jmxEnabled != null && jmxEnabled) ? jmxEnabled : null; }

Target:
public Boolean getXD_JMX_ENABLED() { return jmxEnabled; }
Source:
private void addAllExpectedMsgs() throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { for (File file : inputFiles) { String fileClassName = this.getClass().getPackage().getName() + "." + file.getName().substring(0, file.getName().indexOf(".swift")); RuleTest ruleTest = (RuleTest) Class.forName(fileClassName).getConstructor().newInstance(); ruleTest.inputFile = new File(TEST_INPUT_DIR + ruleTest.getInputFilePath()); ruleTest.expectedMessages = new ArrayList<>(); ruleTest.addAllExpectedMsgs(); this.expectedMessages.addAll(ruleTest.expectedMessages); } }

Target:
private void addAllExpectedMsgs() throws ReflectiveOperationException { for (File file : inputFiles) { String fileClassName = this.getClass().getPackage().getName() + "." + file.getName().substring(0, file.getName().indexOf(".swift")); RuleTest ruleTest = (RuleTest) Class.forName(fileClassName).getConstructor().newInstance(); ruleTest.inputFile = new File(TEST_INPUT_DIR + ruleTest.getInputFilePath()); ruleTest.expectedMessages = new ArrayList<>(); ruleTest.addAllExpectedMsgs(); this.expectedMessages.addAll(ruleTest.expectedMessages); } }
Source:
public void testConsumerAlreadyExistsMultipleCalls() throws Exception { final CompletableFuture<DescribeStreamSummaryResponse> dssFuture = CompletableFuture .completedFuture(createDescribeStreamSummaryResponse()); final CompletableFuture<DescribeStreamConsumerResponse> dscFuture = CompletableFuture .completedFuture(createDescribeStreamConsumerResponse(ConsumerStatus.ACTIVE)); when(client.describeStreamSummary(any(DescribeStreamSummaryRequest.class))).thenReturn(dssFuture); when(client.describeStreamConsumer(any(DescribeStreamConsumerRequest.class))).thenReturn(dscFuture); final String firstCall = consumerRegistration.getOrCreateStreamConsumerArn(); final String secondCall = consumerRegistration.getOrCreateStreamConsumerArn(); assertThat(firstCall, equalTo(CONSUMER_ARN)); assertThat(secondCall, equalTo(CONSUMER_ARN)); verify(client, times(2)).describeStreamConsumer(any(DescribeStreamConsumerRequest.class)); verify(client).describeStreamSummary(any(DescribeStreamSummaryRequest.class)); verify(client, never()).registerStreamConsumer(any(RegisterStreamConsumerRequest.class)); }

Target:
public void testConsumerAlreadyExistsMultipleCalls() throws Exception { final CompletableFuture<DescribeStreamSummaryResponse> dssFuture = CompletableFuture .completedFuture(createDescribeStreamSummaryResponse()); final CompletableFuture<DescribeStreamConsumerResponse> dscFuture = CompletableFuture .completedFuture(createDescribeStreamConsumerResponse(ConsumerStatus.ACTIVE)); when(client.describeStreamSummary(any(DescribeStreamSummaryRequest.class))).thenReturn(dssFuture); when(client.describeStreamConsumer(any(DescribeStreamConsumerRequest.class))).thenReturn(dscFuture); final String firstCall = consumerRegistration.getOrCreateStreamConsumerArn(); final String secondCall = consumerRegistration.getOrCreateStreamConsumerArn(); assertThat(firstCall, equalTo(CONSUMER_ARN)); assertThat(secondCall, equalTo(CONSUMER_ARN)); verify(client, never()).registerStreamConsumer(any(RegisterStreamConsumerRequest.class)); }