auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected void replay(long windowId) throws SQLException { try { MutablePair<Integer, Integer> recoveredData = (MutablePair<Integer, Integer>)windowManager.load(operatorId, windowId); if (recoveredData != null && shouldReplayWindow(recoveredData)) { LOG.debug("[Recovering Window ID - for record range: {}, {}]", windowId, recoveredData.left, recoveredData.right); ps = store.getConnection().prepareStatement( buildRangeQuery(rangeQueryPair.getKey(), (rangeQueryPair.getValue() - rangeQueryPair.getKey())), TYPE_FORWARD_ONLY, CONCUR_READ_ONLY); LOG.info("Query formed to recover data - {}", ps.toString()); emitReplayedTuples(ps); } if (currentWindowId == windowManager.getLargestRecoveryWindow()) { try { if (!isPollerPartition && rangeQueryPair.getValue() != null) { ps = store.getConnection().prepareStatement( buildRangeQuery(lastEmittedRecord, (rangeQueryPair.getValue() - lastEmittedRecord)), TYPE_FORWARD_ONLY, CONCUR_READ_ONLY); } else { Integer bound = null; if (lastEmittedRecord == null) { bound = rangeQueryPair.getKey(); } else { bound = lastEmittedRecord; } ps = store.getConnection().prepareStatement(buildRangeQuery(bound, Integer.MAX_VALUE), TYPE_FORWARD_ONLY, CONCUR_READ_ONLY); } scanService.scheduleAtFixedRate(new DBPoller(), 0, pollInterval, TimeUnit.MILLISECONDS); } catch (SQLException e) { throw new RuntimeException(e); } } } catch (IOException e) { throw new RuntimeException("replay", e); } }

Target:
protected void replay(long windowId) throws SQLException { try { MutablePair<Integer, Integer> recoveredData = (MutablePair<Integer, Integer>)windowManager.load(operatorId, windowId); if (recoveredData != null && shouldReplayWindow(recoveredData)) { LOG.debug("[Recovering Window ID - for record range: {}, {}]", windowId, recoveredData.left, recoveredData.right); ps = store.getConnection().prepareStatement( buildRangeQuery(recoveredData.left, (recoveredData.right - recoveredData.left)), TYPE_FORWARD_ONLY, CONCUR_READ_ONLY); LOG.info("Query formed to recover data - {}", ps.toString()); emitReplayedTuples(ps); } if (currentWindowId == windowManager.getLargestRecoveryWindow()) { try { if (!isPollerPartition && rangeQueryPair.getValue() != null) { ps = store.getConnection().prepareStatement( buildRangeQuery(lastEmittedRow, (rangeQueryPair.getValue() - lastEmittedRow)), TYPE_FORWARD_ONLY, CONCUR_READ_ONLY); } else { Integer bound = null; if (lastEmittedRow == null) { bound = rangeQueryPair.getKey(); } else { bound = lastEmittedRow; } ps = store.getConnection().prepareStatement(buildRangeQuery(bound, Integer.MAX_VALUE), TYPE_FORWARD_ONLY, CONCUR_READ_ONLY); } scanService.scheduleAtFixedRate(new DBPoller(), 0, pollInterval, TimeUnit.MILLISECONDS); } catch (SQLException e) { throw new RuntimeException(e); } } } catch (IOException e) { throw new RuntimeException("Exception during replay of records.", e); } }
Source:
public CollectionFuture<Boolean> asyncLopInsert(String key, int index, Object value, CollectionAttributes attributesForCreate) { ListInsert<Object> listStore = new ListInsert<Object>(value, (attributesForCreate != null), null, attributesForCreate); return asyncCollectionInsert(key, String.valueOf(index), listStore, collectionTranscoder); }

Target:
public CollectionFuture<Boolean> asyncLopInsert(String key, int index, Object value, CollectionAttributes attributesForCreate) { ListInsert<Object> listInsert = new ListInsert<Object>(value, (attributesForCreate != null), null, attributesForCreate); return asyncCollectionInsert(key, String.valueOf(index), listInsert, collectionTranscoder); }
Source:
public Optional<T> getFirstResult() { Collection<T> list = getResult(); Iterator<T> iterator = list.iterator(); if (iterator.hasNext()) { return Optional.of(iterator.next()); } return Optional.empty(); }

Target:
public Optional<T> getFirstResult() { if (result != null) { return result.stream().findFirst(); } return Optional.empty(); }
Source:
protected void configureMoveCommand(String source, String destination) { Connection connection = getHandlerConnection(); command = new RemoteMoveFileCommand(); command.setConnectionConfiguration(connection.getConfiguration()); ((RemoteCommand) command).setConnection(connection); ((RemoteMoveFileCommand) command).setConfiguration(source, destination); ((RemoteMoveFileCommand) command).setMoveType(HANDLE_TYPE); }

Target:
protected void configureMoveCommand(String source, String destination) { RemoteMoveFileCommand cmd = new RemoteMoveFileCommand(); cmd.setConfiguration(source, destination); cmd.setMoveType(HANDLE_TYPE); cmd.setPermissions(permissions); cmd.setConnectionConfiguration(connection.get().getConfiguration()); cmd.setConnection(connection.get()); command.set(cmd); }
Source:
private static Meter getMeter(String name) { return metricsManager.registerMeter(SnapshotTransaction.class, name); }

Target:
private static Meter getMeter(String name) { return metricsManager.registerOrGetMeter(SnapshotTransaction.class, name); }
Source:
private static String getAvaticaConnectionId(Map<String, Object> requestMap) throws IOException { Object connectionIdObj = requestMap.get("connectionId"); if (connectionIdObj == null) { throw new IAE("Received an Avatica request without a connectionId."); } if (!(connectionIdObj instanceof String)) { throw new IAE("Received an Avatica request with a non-String connectionId."); } return (String) requestMap.get("connectionId"); }

Target:
private static String getAvaticaConnectionId(Map<String, Object> requestMap) throws IOException { Object connectionIdObj = requestMap.get("connectionId"); if (connectionIdObj == null) { throw new IAE("Received an Avatica request without a connectionId."); } if (!(connectionIdObj instanceof String)) { throw new IAE("Received an Avatica request with a non-String connectionId."); } return (String) connectionIdObj; }
Source:
public static String generateHtmlSnippet(String id, URI baseUri) { StringBuilder sb = new StringBuilder(); Formatter formatter = new Formatter(sb); formatter.format("<script type=\"text/javascript\" language=\"javascript\" " + "src=\"%1$s/factory/resources/embed.js?%2$s\"></script>", UriBuilder.fromUri(baseUri).replacePath("").build(), id); return sb.toString(); }

Target:
public static String generateHtmlSnippet(String id, URI baseUri) { Formatter formatter = new Formatter(); formatter.format("<script type=\"text/javascript\" language=\"javascript\" " + "src=\"%1$s/factory/resources/embed.js?%2$s\"></script>", UriBuilder.fromUri(baseUri).replacePath("").build().toString(), id); return formatter.toString(); }
Source:
private Tracing newTracing(String serviceName) { return Tracing.newBuilder() .currentTraceContext(ThreadLocalCurrentTraceContext.newBuilder() .addScopeDecorator(MDCScopeDecorator.create()).build()) .localServiceName(serviceName) .sampler(Sampler.create(rate)) .spanReporter(spanReporter).build(); }

Target:
private Tracing newTracing(String serviceName) { Tracing brave = null; if (camelContext.isUseMDCLogging()) { brave = Tracing.newBuilder() .currentTraceContext(ThreadLocalCurrentTraceContext.newBuilder() .addScopeDecorator(MDCScopeDecorator.create()).build()) .localServiceName(serviceName) .sampler(Sampler.create(rate)) .spanReporter(spanReporter).build(); } else { brave = Tracing.newBuilder() .localServiceName(serviceName) .sampler(Sampler.create(rate)) .spanReporter(spanReporter).build(); } return brave; }
Source:
public boolean setZoneTemperatureControlValues(String sessionToken, Integer zoneID, String zoneName, List<Object[]> controlValues) { if (checkRequiredZone(zoneID, zoneName)) { try { if (checkRequiredZone(zoneID, zoneName)) { if (controlValues != null) { SimpleRequestBuilder builder = SimpleRequestBuilder.buildNewRequest(InterfaceKeys.JSON) .addRequestClass(ClassKeys.ZONE) .addFunction(FunctionKeys.SET_TEMEPERATURE_CONTROL_VALUE) .addParameter(ParameterKeys.TOKEN, sessionToken) .addParameter(ParameterKeys.ID, convertIntegerToString(zoneID)) .addParameter(ParameterKeys.NAME, zoneName); for (Object[] objAry : controlValues) { if (objAry.length == 2 && objAry[0] instanceof String && objAry[1] instanceof Integer) { builder.addParameter((String) objAry[0], convertIntegerToString((Integer) objAry[1])); } else { builder.buildRequestString(); throw new IllegalArgumentException( "The first field of the object array have to be a String and the second have to be a Integer."); } } String response = transport.execute(builder.buildRequestString()); return JSONResponseHandler.checkResponse(JSONResponseHandler.toJsonObject(response)); } } } catch (Exception e) { logger.debug("An exception occurred", e); } } return false; }

Target:
public boolean setZoneTemperatureControlValues(String sessionToken, Integer zoneID, String zoneName, List<Object[]> controlValues) { if (checkRequiredZone(zoneID, zoneName)) { if (checkRequiredZone(zoneID, zoneName)) { if (controlValues != null) { SimpleRequestBuilder builder = SimpleRequestBuilder.buildNewRequest(InterfaceKeys.JSON) .addRequestClass(ClassKeys.ZONE).addFunction(FunctionKeys.SET_TEMEPERATURE_CONTROL_VALUE) .addDefaultZoneParameter(sessionToken, zoneID, zoneName); for (Object[] objAry : controlValues) { if (objAry.length == 2 && objAry[0] instanceof String && objAry[1] instanceof Integer) { builder.addParameter((String) objAry[0], SimpleRequestBuilder.objectToString(objAry[1])); } else { builder.buildRequestString(); throw new IllegalArgumentException( "The first field of the object array have to be a String and the second have to be a Integer."); } } String response = transport.execute(builder.buildRequestString()); return JSONResponseHandler.checkResponse(JSONResponseHandler.toJsonObject(response)); } } } return false; }
Source:
public void init() { Assert.notNull(serverUriResolver, "serverUriResolver must be configured."); IdSiteController controller = new LogoutIdSiteController(); controller.setServerUriResolver(serverUriResolver); controller.setCallbackUri(idSiteResultUri); controller.setIdSiteOrganizationResolver(idSiteOrganizationResolver); controller.setAlreadyLoggedInUri(nextUri); controller.init(); this.idSiteController = controller; }

Target:
public void init() { Assert.notNull(serverUriResolver, "serverUriResolver must be configured."); IdSiteController controller = new LogoutIdSiteController(); controller.setServerUriResolver(serverUriResolver); controller.setCallbackUri(idSiteResultUri); controller.setIdSiteOrganizationResolver(idSiteOrganizationResolver); controller.setAlreadyLoggedInUri(nextUri); controller.init(); this.idSiteController = controller; super.init(); }
Source:
public Certificate getCertificateForGateway() throws KeystoreServiceException, KeyStoreException { Certificate cert = null; readLock.lock(); try { KeyStore ks = getKeystoreForGateway(); if (ks != null) { cert = ks.getCertificate(config.getIdentityKeyAlias()); } return cert; } finally { readLock.unlock(); } }

Target:
public Certificate getCertificateForGateway() throws KeystoreServiceException, KeyStoreException { KeyStore ks = getKeystoreForGateway(); return (ks == null) ? null : ks.getCertificate(config.getIdentityKeyAlias()); }
Source:
public void findAllTest() throws Exception { context.turnOffAuthorisationSystem(); parentCommunity = CommunityBuilder.createCommunity(context) .withName("Parent Community") .build(); Community child1 = CommunityBuilder.createSubCommunity(context, parentCommunity) .withName("Sub Community") .build(); Community child2 = CommunityBuilder.createSubCommunity(context, parentCommunity) .withName("Sub Community Two") .build(); Collection col1 = CollectionBuilder.createCollection(context, child1).withName("Collection 1").build(); Collection col2 = CollectionBuilder.createCollection(context, child2).withName("Collection 2").build(); getClient().perform(get("/api/core/collections") .param("embed", CollectionMatcher.getFullEmbedsParameter())) .andExpect(status().isOk()) .andExpect(content().contentType(contentType)) .andExpect(jsonPath("$._embedded.collections", Matchers.containsInAnyOrder( CollectionMatcher.matchCollectionEntryFullProjection(col1.getName(), col1.getID(), col1.getHandle()), CollectionMatcher.matchCollectionEntryFullProjection(col2.getName(), col2.getID(), col2.getHandle()) ))); }

Target:
public void findAllTest() throws Exception { context.turnOffAuthorisationSystem(); parentCommunity = CommunityBuilder.createCommunity(context) .withName("Parent Community") .build(); Community child1 = CommunityBuilder.createSubCommunity(context, parentCommunity) .withName("Sub Community") .build(); Community child2 = CommunityBuilder.createSubCommunity(context, parentCommunity) .withName("Sub Community Two") .build(); Collection col1 = CollectionBuilder.createCollection(context, child1).withName("Collection 1").build(); Collection col2 = CollectionBuilder.createCollection(context, child2).withName("Collection 2").build(); getClient().perform(get("/api/core/collections") .param("embed", CollectionMatcher.getEmbedsParameter())) .andExpect(status().isOk()) .andExpect(content().contentType(contentType)) .andExpect(jsonPath("$._embedded.collections", Matchers.containsInAnyOrder( CollectionMatcher.matchCollectionEntrySpecificEmbedProjection(col1.getName(), col1.getID(), col1.getHandle()), CollectionMatcher.matchCollectionEntrySpecificEmbedProjection(col2.getName(), col2.getID(), col2.getHandle()) ))); }
Source:
protected final void check() { checkArgument(!password().equals(""), "password cannot be empty"); }

Target:
protected final void check() { Preconditions.checkArgument(!uri().equals(URI.create("")), "uri cannot be empty"); Preconditions.checkArgument(!password().equals(""), "password cannot be empty"); }
Source:
public void deleteSupplementaryFolder() { IFolder supplFolder = getTraceSupplementaryFolder(getResourceName()); if (supplFolder.exists()) { try { supplFolder.delete(true, new NullProgressMonitor()); } catch (CoreException e) { Activator.getDefault().logError("Error deleting supplementary folder " + supplFolder, e); } } }

Target:
public void deleteSupplementaryFolder() { IFolder supplFolder = getTraceSupplementaryFolder(getResourceName()); if (supplFolder.exists()) { try { supplFolder.delete(true, new NullProgressMonitor()); } catch (CoreException e) { Activator.getDefault().logError(Messages.TmfCommonProjectElement_ErrorDeletingSF + supplFolder, e); } } }
Source:
public void makeUnDiscoverablePatchTest() throws Exception { context.turnOffAuthorisationSystem(); parentCommunity = CommunityBuilder.createCommunity(context) .withName("Parent Community") .build(); Community child1 = CommunityBuilder.createSubCommunity(context, parentCommunity) .withName("Sub Community") .build(); Collection col1 = CollectionBuilder.createCollection(context, child1).withName("Collection 1").build(); Item item = ItemBuilder.createItem(context, col1) .withTitle("Public item 1") .withIssueDate("2017-10-17") .withAuthor("Smith, Donald").withAuthor("Doe, John") .withSubject("ExtraEntry") .build(); String token = getAuthToken(admin.getEmail(), password); List<Operation> ops = new ArrayList<Operation>(); ReplaceOperation replaceOperation = new ReplaceOperation("/discoverable", "false"); ops.add(replaceOperation); String patchBody = getPatchContent(ops); getClient(token).perform(patch("/api/core/items/" + item.getID()) .content(patchBody) .contentType(MediaType.APPLICATION_JSON_PATCH_JSON)) .andExpect(status().isOk()) .andExpect(jsonPath("$.uuid", Matchers.is(item.getID().toString()))) .andExpect(jsonPath("$.discoverable", Matchers.is(false))); getClient(token).perform(get("/api/core/items/" + item.getID())) .andExpect(status().isOk()) .andExpect(jsonPath("$.uuid", Matchers.is(item.getID().toString()))) .andExpect(jsonPath("$.discoverable", Matchers.is(false))); }

Target:
public void makeUnDiscoverablePatchTest() throws Exception { context.turnOffAuthorisationSystem(); parentCommunity = CommunityBuilder.createCommunity(context) .withName("Parent Community") .build(); Community child1 = CommunityBuilder.createSubCommunity(context, parentCommunity) .withName("Sub Community") .build(); Collection col1 = CollectionBuilder.createCollection(context, child1).withName("Collection 1").build(); Item item = ItemBuilder.createItem(context, col1) .withTitle("Public item 1") .withIssueDate("2017-10-17") .withAuthor("Smith, Donald").withAuthor("Doe, John") .withSubject("ExtraEntry") .build(); String token = getAuthToken(admin.getEmail(), password); List<Operation> ops = new ArrayList<Operation>(); ReplaceOperation replaceOperation = new ReplaceOperation("/discoverable", false); ops.add(replaceOperation); String patchBody = getPatchContent(ops); getClient(token).perform(patch("/api/core/items/" + item.getID()) .content(patchBody) .contentType(MediaType.APPLICATION_JSON_PATCH_JSON)) .andExpect(status().isOk()) .andExpect(jsonPath("$.uuid", Matchers.is(item.getID().toString()))) .andExpect(jsonPath("$.discoverable", Matchers.is(false))); getClient(token).perform(get("/api/core/items/" + item.getID())) .andExpect(status().isOk()) .andExpect(jsonPath("$.uuid", Matchers.is(item.getID().toString()))) .andExpect(jsonPath("$.discoverable", Matchers.is(false))); }
Source:
public Optional<String> getETag() { return Optional.ofNullable(_eTag); }

Target:
public Optional<String> getETag() { return _eTag; }
Source:
protected HistoryEvent getHistoricTaskInstance(CommandContext commandContext) { String historicTaskInstanceId = authorization.getResourceId(); if (historicTaskInstanceId == null) { return null; } return commandContext.getHistoricTaskInstanceManager() .findHistoricTaskInstanceById(historicTaskInstanceId); }

Target:
protected HistoryEvent getHistoricTaskInstance(CommandContext commandContext) { String historicTaskInstanceId = authorization.getResourceId(); if (historicTaskInstanceId == null || isAny(historicTaskInstanceId)) { return null; } return commandContext.getHistoricTaskInstanceManager() .findHistoricTaskInstanceById(historicTaskInstanceId); }
Source:
protected TimeEvent createTimeEvent(TimeGraphEntry entry, ITimeGraphState state) { if (state.getValue() == Integer.MIN_VALUE) { return new NullTimeEvent(entry, state.getStartTime(), state.getDuration(), state.getActiveProperties()); } String label = state.getLabel(); if (label != null) { return new NamedTimeEvent(entry, state.getStartTime(), state.getDuration(), state.getValue(), label, state.getActiveProperties()); } return new TimeEvent(entry, state.getStartTime(), state.getDuration(), state.getValue(), state.getActiveProperties()); }

Target:
protected TimeEvent createTimeEvent(TimeGraphEntry entry, ITimeGraphState state) { if (state.getValue() == Integer.MIN_VALUE) { return new NullTimeEvent(entry, state.getStartTime(), state.getDuration()); } String label = state.getLabel(); if (label != null) { return new NamedTimeEvent(entry, state.getStartTime(), state.getDuration(), state.getValue(), label, state.getActiveProperties()); } return new TimeEvent(entry, state.getStartTime(), state.getDuration(), state.getValue(), state.getActiveProperties()); }
Source:
public void shouldReturnOnlyTestUnitsForClassesWithinReach() throws IOException { when( this.extractor.extractCallDependenciesForPackages( eq(this.aTestUnit.getDescription().getFirstTestClass()), isNull())).thenReturn(Arrays.asList("foo")); when( this.extractor.extractCallDependenciesForPackages( eq(this.anotherTestUnit.getDescription().getFirstTestClass()), isNull())).thenReturn(Collections.<String> emptyList()); assertEquals(Arrays.asList(this.aTestUnit), this.testee.filterTestsByDependencyAnalysis(this.tus)); }

Target:
public void shouldReturnOnlyTestUnitsForClassesWithinReach() throws IOException { when( this.extractor.extractCallDependenciesForPackages( eq(this.aTestUnit.getDescription().getFirstTestClass()), any(Predicate.class))).thenReturn(Arrays.asList("foo")); when( this.extractor.extractCallDependenciesForPackages( eq(this.anotherTestUnit.getDescription().getFirstTestClass()), any(Predicate.class))).thenReturn(Collections.<String> emptyList()); assertEquals(Arrays.asList(this.aTestUnit), this.testee.filterTestsByDependencyAnalysis(this.tus)); }
Source:
private void loadGalleryItem() { updateProgressBar(true, true, 0); new GalleryItemFetchTask(app.getAPIForSite(imageTitle.getWikiSite()), imageTitle.getWikiSite(), imageTitle, FileUtil.isVideo(mimeType)) { @Override public void onFinish(Map<PageTitle, GalleryItem> result) { if (!isAdded()) { return; } if (result.size() > 0) { galleryItem = (GalleryItem) result.values().toArray()[0]; parentActivity.getGalleryCache().put((PageTitle) result.keySet().toArray()[0], galleryItem); loadMedia(); } else { updateProgressBar(false, true, 0); parentActivity.showError(null, true); } } @Override public void onCatch(Throwable caught) { if (!isAdded()) { return; } updateProgressBar(false, true, 0); parentActivity.showError(caught, true); L.e("caught " + caught.getMessage()); } }.execute(); }

Target:
private void loadGalleryItem() { updateProgressBar(true, true, 0); new GalleryItemFetchTask(app.getAPIForSite(imageTitle.getWikiSite()), imageTitle.getWikiSite(), imageTitle, FileUtil.isVideo(mimeType)) { @Override public void onFinish(Map<PageTitle, GalleryItem> result) { if (!isAdded()) { return; } if (result.size() > 0) { galleryItem = (GalleryItem) result.values().toArray()[0]; parentActivity.getGalleryCache().put((PageTitle) result.keySet().toArray()[0], galleryItem); loadMedia(); } else { updateProgressBar(false, true, 0); parentActivity.showError(null, true); } } @Override public void onCatch(Throwable caught) { if (!isAdded()) { return; } updateProgressBar(false, true, 0); parentActivity.showError(caught, true); L.e(caught); } }.execute(); }
Source:
public KeyEncryptionKeyClientBuilder credential(TokenCredential credential) { Objects.requireNonNull(credential); this.credential = credential; return this; }

Target:
public KeyEncryptionKeyClientBuilder credential(TokenCredential credential) { super.credential(credential); return this; }
Source:
protected boolean isRegisteredStudent(){ if(student != null){ return student.googleId != null && !student.googleId.isEmpty(); }else{ return false; } }

Target:
protected boolean isRegisteredStudent(){ return (student != null) && (student.googleId != null) && (!student.googleId.isEmpty()); }
Source:
protected static void checkNonNull(Object thing) { if(thing == null) { throw new NullPointerException(); } }

Target:
protected static void checkNonNull(Object thing) { Objects.requireNonNull(thing); }
Source:
public DataStoreIT() { goodUser = new User(new Principal() { @Override public String getName() { return "1"; } }); badUser = new User(new Principal() { @Override public String getName() { return "-1"; } }); mapper = new ObjectMapper(); Map<String, Class<? extends Check>> checks = new HashMap(TestCheckMappings.MAPPINGS); checks.put("filterCheck", Filtered.FilterCheck.class); checks.put("filterCheck3", Filtered.FilterCheck3.class); elide = new Elide(new ElideSettingsBuilder(dataStore) .withAuditLogger(new TestAuditLogger()) .withEntityDictionary(new EntityDictionary(checks)) .build()); }

Target:
public DataStoreIT() { goodUser = new User(() -> "1"); badUser = new User(() -> "-1"); mapper = new ObjectMapper(); Map<String, Class<? extends Check>> checks = new HashMap(TestCheckMappings.MAPPINGS); checks.put("filterCheck", Filtered.FilterCheck.class); checks.put("filterCheck3", Filtered.FilterCheck3.class); elide = new Elide(new ElideSettingsBuilder(dataStore) .withAuditLogger(new TestAuditLogger()) .withEntityDictionary(new EntityDictionary(checks)) .build()); }
Source:
public int hashCode() { long bits = 1; bits = 31 * bits + Double.doubleToLongBits(this.scalar); bits = 31 * bits + ((this.vector == null) ? 0 : this.vector.hashCode()); final int b = (int) bits; return b; }

Target:
public int hashCode() { long bits = 1; bits = 31 * bits + Double.doubleToLongBits(this.scalar); bits = 31 * bits + ((this.vector == null) ? 0 : this.vector.hashCode()); final int b = (int) bits; return b ^ (b >> 31); }
Source:
public void shouldBlockUntilCancellation() throws Exception { AtomicReference<Exception> testThreadException = new AtomicReference<>(); TestConvertingFutureCallback testCallback = new TestConvertingFutureCallback(); runSeparateTestThread(() -> { try { testCallback.waitForGet(); testCallback.cancel(true); } catch (Exception e) { testThreadException.compareAndSet(null, e); } }); assertFalse(testCallback.isDone()); testCallback.get(); if (testThreadException.get() != null) { throw testThreadException.get(); } }

Target:
public void shouldBlockUntilCancellation() throws Exception { AtomicReference<Exception> testThreadException = new AtomicReference<>(); TestConvertingFutureCallback testCallback = new TestConvertingFutureCallback(); executor.submit(() -> { try { testCallback.waitForGet(); testCallback.cancel(true); } catch (Exception e) { testThreadException.compareAndSet(null, e); } }); assertFalse(testCallback.isDone()); testCallback.get(); if (testThreadException.get() != null) { throw testThreadException.get(); } }
Source:
private HashSet<Account.Id> getWatchers() throws EmailException { HashSet<Account.Id> watchers = new HashSet<Account.Id>(); try { for (AccountProjectWatch p : args.db.get().accountProjectWatches() .byProject(project.getNameKey())) { watchers.add(p.getAccountId()); } } catch (OrmException e) { log.error("Invalid watcher is set", e); } return watchers; }

Target:
private Set<Account.Id> getWatchers() throws EmailException { Set<Account.Id> watchers = new HashSet<Account.Id>(); try { for (AccountProjectWatch p : args.db.get().accountProjectWatches() .byProject(project.getNameKey())) { watchers.add(p.getAccountId()); } Project.NameKey parent = project.getParent(); while (parent != null) { for (AccountProjectWatch p : args.db.get().accountProjectWatches() .byProject(parent)) { watchers.add(p.getAccountId()); } parent = args.projectCache.get(parent).getProject().getParent(); } } catch (OrmException e) { log.error("Invalid watcher is set", e); } return watchers; }
Source:
private void setupBrightness() { if (activity == null) { return; } final WindowManager.LayoutParams lp = activity.getWindow().getAttributes(); if (player == null || !player.videoPlayerSelected() || !player.isFullscreen() || bottomSheetState != BottomSheetBehavior.STATE_EXPANDED) { restoreDefaultBrightness(); } else { if (!PlayerHelper.isBrightnessGestureEnabled(getContext())) { return; } final float brightnessLevel = PlayerHelper.getScreenBrightness(activity); if (brightnessLevel == lp.screenBrightness) { return; } lp.screenBrightness = brightnessLevel; activity.getWindow().setAttributes(lp); } }

Target:
private void setupBrightness() { if (activity == null) { return; } final WindowManager.LayoutParams lp = activity.getWindow().getAttributes(); if (player == null || !player.videoPlayerSelected() || !player.isFullscreen() || bottomSheetState != BottomSheetBehavior.STATE_EXPANDED) { restoreDefaultBrightness(); } else { if (!PlayerHelper.isBrightnessGestureEnabled(activity)) { return; } final float brightnessLevel = PlayerHelper.getScreenBrightness(activity); if (brightnessLevel == lp.screenBrightness) { return; } lp.screenBrightness = brightnessLevel; activity.getWindow().setAttributes(lp); } }
Source:
public static TableLayoutParams getFor(@Nullable View view) { ViewGroup.LayoutParams lp = view == null ? null : view.getLayoutParams(); return lp instanceof TableLayoutParams ? (TableLayoutParams) lp : null; }

Target:
public static TableLayoutParams getFor(@Nullable View view) { return getFor(view, false); }
Source:
protected int getOffscreenPageLimit() { return 1; }

Target:
protected int getOffscreenPageLimit() { return 2; }
Source:
private void updateFormRecord(SqlStorage<FormRecord> formRecordStorage, boolean incomplete) throws FormInstanceTransactionException { String status; if (incomplete || !mMarkCompleted) { status = FormRecord.STATUS_INCOMPLETE; } else { status = FormRecord.STATUS_COMPLETE; } FormRecord formRecord = null; String recordName = mRecordName; if (mFormRecordId != -1) { formRecord = FormRecord.getFormRecord(formRecordStorage, mFormRecordId); } else if (mFormDefId != -1) { formRecord = CommCareApplication.instance().getCurrentSessionWrapper().getFormRecord(); formRecord.setFilePath(mFormRecordPath); if (recordName == null) { FormDefRecord formDefRecord = FormDefRecord.getFormDef( CommCareApplication.instance().getAppStorage(FormDefRecord.class), mFormDefId); recordName = formDefRecord.getDisplayname(); } } if (formRecord != null) { try { formRecord.updateStatus(formRecordStorage, status, recordName); } catch (IllegalStateException e) { throw new FormInstanceTransactionException(e); } } }

Target:
private void updateFormRecord(SqlStorage<FormRecord> formRecordStorage, boolean incomplete) throws FormInstanceTransactionException { String status; if (incomplete || !mMarkCompleted) { status = FormRecord.STATUS_INCOMPLETE; } else { status = FormRecord.STATUS_COMPLETE; } FormRecord formRecord = null; String recordName = mRecordName; if (mFormRecordId != -1) { formRecord = FormRecord.getFormRecord(formRecordStorage, mFormRecordId); } else if (mFormDefId != -1) { formRecord = CommCareApplication.instance().getCurrentSessionWrapper().getFormRecord(); formRecord.setFilePath(mFormRecordPath); if (recordName == null) { FormDefRecord formDefRecord = FormDefRecord.getFormDef( CommCareApplication.instance().getAppStorage(FormDefRecord.class), mFormDefId); recordName = formDefRecord.getDisplayname(); } } if (formRecord != null) { try { formRecord.setDisplayName(recordName); formRecord.updateStatus(formRecordStorage, status); } catch (IllegalStateException e) { throw new FormInstanceTransactionException(e); } } }
Source:
public void initialize(FlowletContext context) throws IOException { zkQuorum = Programs.getRequiredArgOrProperty(context, Constants.Realtime.Sink.HBase.ARG_HBASE_ZOOKEEPER_QUORUM); zkClientPort = Integer.valueOf(Programs.getRequiredArgOrProperty(context, Constants.Realtime.Sink.HBase.ARG_HBASE_ZOOKEEPER_CLIENT_PORT)); tableName = Programs.getRequiredArgOrProperty(context, Constants.Realtime.Sink.HBase.ARG_TABLE_NAME); family = Programs.getRequiredArgOrProperty(context, Constants.Realtime.Sink.HBase.ARG_COLFAM); familyBytes = Bytes.toBytes(family); rowKeyField = Programs.getRequiredArgOrProperty(context, Constants.Realtime.Sink.HBase.ARG_ROW_KEY_FIELD); zkParentNode = Programs.getRequiredArgOrProperty(context, Constants.Realtime.Sink.HBase.ARG_HBASE_ZOOKEEPER_PARENT_NODE); Configuration conf = HBaseConfiguration.create(); <LINK_0> conf.setClassLoader(HBaseConfiguration.class.getClassLoader()); conf.set(HConstants.ZOOKEEPER_QUORUM, zkQuorum); conf.setInt(HConstants.ZOOKEEPER_CLIENT_PORT, zkClientPort); conf.set(HConstants.ZOOKEEPER_ZNODE_PARENT, zkParentNode); createTableIfNotExists(tableName, conf); hTable = new HTable(conf, tableName); }

Target:
public void initialize(FlowletContext context) throws IOException { zkQuorum = Programs.getRequiredArgOrProperty(context, Constants.Realtime.Sink.HBase.ARG_HBASE_ZOOKEEPER_QUORUM); zkClientPort = Integer.valueOf(Programs.getRequiredArgOrProperty(context, Constants.Realtime.Sink.HBase.ARG_HBASE_ZOOKEEPER_CLIENT_PORT)); tableName = Programs.getRequiredArgOrProperty(context, Constants.Realtime.Sink.HBase.ARG_TABLE_NAME); family = Programs.getRequiredArgOrProperty(context, Constants.Realtime.Sink.HBase.ARG_COLFAM); familyBytes = Bytes.toBytes(family); rowKeyField = Programs.getRequiredArgOrProperty(context, Constants.Realtime.Sink.HBase.ARG_ROW_KEY_FIELD); zkParentNode = Programs.getRequiredArgOrProperty(context, Constants.Realtime.Sink.HBase.ARG_HBASE_ZOOKEEPER_PARENT_NODE); Configuration conf = HBaseConfiguration.create(); conf.setClassLoader(HBaseConfiguration.class.getClassLoader()); conf.set(HConstants.ZOOKEEPER_QUORUM, zkQuorum); conf.setInt(HConstants.ZOOKEEPER_CLIENT_PORT, zkClientPort); conf.set(HConstants.ZOOKEEPER_ZNODE_PARENT, zkParentNode); createTableIfNotExists(tableName, conf); hTable = new HTable(conf, tableName); }
Source:
public E getElement() { return (E)item.getData(); }

Target:
public E getElement() { @SuppressWarnings("unchecked") E element = (E)item.getData(); return element; }
Source:
void transportFactory() { assertThrows(NullPointerException.class, () -> builder().setTransportFactory(Tests.nullRef())); }

Target:
void transportFactory() { assertThrows(NullPointerException.class, () -> builder().setTransportFactory(nullRef())); }
Source:
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (StringUtils.isEmpty(request.getParameter(SSOUtils.POST_ACTION_URL))) { throw new RuntimeException("No post action url found in request."); } boolean enableExternalAuth = (boolean) request.getSession().getServletContext().getAttribute(SSOUtils.ENABLE_EXTERNAL_AUTH); boolean acceptBasicAuth = (boolean) request.getSession().getServletContext().getAttribute(SSOUtils.ACCEPT_BASIC_AUTH_HEADERS); request.getSession(true).setAttribute(SSOUtils.PARAMS_MAP, new HashMap<>(request.getParameterMap())); if (enableExternalAuth) { response.sendRedirect(request.getContextPath() + SSOUtils.LOGIN_EXTERNAL_URI); } else if (acceptBasicAuth) { response.sendRedirect(request.getContextPath() + SSOUtils.LOGIN_BASIC_URI); } else { response.sendRedirect(request.getContextPath() + SSOUtils.LOGIN_PHASE2_URI); } }

Target:
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (StringUtils.isEmpty(request.getParameter(SSOUtils.POST_ACTION_URL))) { throw new RuntimeException("No post action url found in request."); } boolean enableExternalAuth = (boolean) request.getSession().getServletContext().getAttribute(SSOUtils.ENABLE_EXTERNAL_AUTH); request.getSession(true).setAttribute(SSOUtils.PARAMS_MAP, new HashMap<>(request.getParameterMap())); if (enableExternalAuth) { response.sendRedirect(request.getContextPath() + SSOUtils.LOGIN_EXTERNAL_URI); } else { response.sendRedirect(request.getContextPath() + SSOUtils.LOGIN_PHASE2_URI); } }
Source:
public String declareQueue(final Queue queue) { try { return this.rabbitTemplate.execute(channel -> { DeclareOk[] declared = declareQueues(channel, queue); String declaredName = declared.length > 0 ? declared[0].getQueue() : null; if (StringUtils.hasText(declaredName)) { queue.setDeclaredName(declaredName); } return declaredName; }); } catch (AmqpException e) { logOrRethrowDeclarationException(queue, "queue", e); return null; } }

Target:
public String declareQueue(final Queue queue) { try { return this.rabbitTemplate.execute(channel -> { DeclareOk[] declared = declareQueues(channel, queue); return declared.length > 0 ? declared[0].getQueue() : null; }); } catch (AmqpException e) { logOrRethrowDeclarationException(queue, "queue", e); return null; } }
Source:
protected String resolvePrincipalInternal(final X509Certificate certificate) { LOGGER.debug("Resolving principal from Subject Alternative Name RFC8222 type (email) for [{}]", certificate); try { val subjectAltNames = certificate.getSubjectAlternativeNames(); val email = getRFC822EmailAddress(subjectAltNames); if (email != null) { return email; } } catch (final CertificateParsingException e) { LOGGER.error("Error is encountered while trying to retrieve subject alternative names collection from certificate", e); return getAlternatePrincipal(certificate); } return getAlternatePrincipal(certificate); }

Target:
protected String resolvePrincipalInternal(final X509Certificate certificate) { LOGGER.debug("Resolving principal from Subject Alternative Name RFC8222 type (email) for [{}]", certificate); try { val subjectAltNames = certificate.getSubjectAlternativeNames(); val email = getRFC822EmailAddress(subjectAltNames); if (email != null) { return email; } } catch (final CertificateParsingException e) { LOGGER.error("Error encountered while trying to retrieve subject alternative names collection from certificate [{}]", e.getMessage(), e); } return getAlternatePrincipal(certificate); }
Source:
public boolean equals(EmbeddedServerInfo info) { if (this.serverName.equals(info.serverName) && this.userDir.getAbsolutePath().equals(info.userDir.getAbsolutePath()) && this.outputDir.getAbsolutePath().equals(info.outputDir.getAbsolutePath())) { return true; } return false; }

Target:
public boolean equals(EmbeddedServerInfo info) { return this.serverName.equals(info.serverName) && this.userDir.getAbsolutePath().equals(info.userDir.getAbsolutePath()) && this.outputDir.getAbsolutePath().equals(info.outputDir.getAbsolutePath()); }
Source:
public List<Member> findMembersInParentGroup(PerunSession sess, Group group, String searchString) throws InternalErrorException, ParentGroupNotExistsException{ List<User> users = getPerunBl().getUsersManagerBl().findUsers(sess, searchString); List<Member> allGroupMembers; if(group.getParentGroupId() == null) { Vo vo; try { vo = getPerunBl().getVosManagerBl().getVoById(sess, group.getVoId()); } catch (VoNotExistsException ex) { throw new ConsistencyErrorException("Vo does not exist."); } allGroupMembers = getPerunBl().getMembersManagerBl().getMembers(sess, vo); } else { allGroupMembers = getPerunBl().getGroupsManagerBl().getParentGroupMembers(sess, group); } List<Member> allFoundMembers = new ArrayList<>(); for(User user: users){ allFoundMembers.addAll(getMembersByUser(sess, user)); } allGroupMembers.retainAll(allFoundMembers); return allGroupMembers; }

Target:
public List<Member> findMembersInParentGroup(PerunSession sess, Group group, String searchString) throws InternalErrorException { List<User> users = getPerunBl().getUsersManagerBl().findUsers(sess, searchString); List<Member> allGroupMembers; if(group.getParentGroupId() == null) { Vo vo; try { vo = getPerunBl().getVosManagerBl().getVoById(sess, group.getVoId()); } catch (VoNotExistsException ex) { throw new ConsistencyErrorException("Vo for group " + group + " does not exist."); } allGroupMembers = getPerunBl().getMembersManagerBl().getMembers(sess, vo); } else { allGroupMembers = getPerunBl().getGroupsManagerBl().getParentGroupMembers(sess, group); } List<Member> allFoundMembers = new ArrayList<>(); for(User user: users){ allFoundMembers.addAll(getMembersByUser(sess, user)); } allGroupMembers.retainAll(allFoundMembers); return allGroupMembers; }
Source:
protected void executeCommand() { if (getDiskImage() != null) { VDSReturnValue vdsReturnValue = performImageVdsmOperation(); getReturnValue().getInternalTaskIdList().add( createTask(vdsReturnValue.getCreationInfo(), getParameters().getParentCommand(), VdcObjectType.Storage, getParameters().getStorageDomainId())); if (getParameters().getPerformDbOperationsStage() == PerformOperationStage.EXECUTION && getParameters().getParentCommand() != VdcActionType.RemoveVmFromImportExport && getParameters().getParentCommand() != VdcActionType.RemoveVmTemplateFromImportExport) { removeImageFromDB(false); } } else { log.warn("DiskImage is null, nothing to remove"); } setSucceeded(true); }

Target:
protected void executeCommand() { if (getDiskImage() != null) { VDSReturnValue vdsReturnValue = performImageVdsmOperation(); getReturnValue().getInternalTaskIdList().add( createTask(vdsReturnValue.getCreationInfo(), getParameters().getParentCommand(), VdcObjectType.Storage, getParameters().getStorageDomainId())); if (getParameters().getPerformDbOperationsStage() == PerformOperationsStage.EXECUTION && getParameters().getParentCommand() != VdcActionType.RemoveVmFromImportExport && getParameters().getParentCommand() != VdcActionType.RemoveVmTemplateFromImportExport) { removeImageFromDB(false); } } else { log.warn("DiskImage is null, nothing to remove"); } setSucceeded(true); }
Source:
public static String dumpCert(ConfigurationContext configurationContext, byte[] cert, String fileName) { if (!verifyCertExistence(fileName, configurationContext)) { String workDir = (String) configurationContext.getProperty(ServerConstants.WORK_DIR); File pubCert = new File(workDir + File.separator + "pub_certs"); if (fileName == null) { fileName = String.valueOf(System.currentTimeMillis() + Math.random()) + ".cert"; } if (!pubCert.exists()) { pubCert.mkdirs(); } String filePath = workDir + File.separator + "pub_certs" + File.separator + fileName; OutputStream outStream = null; try { outStream = new FileOutputStream(filePath); outStream.write(cert); } catch (Exception e) { String msg = "Error when writing the public certificate to a file"; log.error(msg); throw new SecurityException("msg", e); } finally { IdentityIOStreamUtils.closeOutputStream(outStream); } Map fileResourcesMap = (Map) configurationContext.getProperty(WSO2Constants.FILE_RESOURCE_MAP); if (fileResourcesMap == null) { fileResourcesMap = new Hashtable(); configurationContext.setProperty(WSO2Constants.FILE_RESOURCE_MAP, fileResourcesMap); } fileResourcesMap.put(fileName, filePath); } return WSO2Constants.ContextPaths.DOWNLOAD_PATH + "?id=" + fileName; }

Target:
public static String dumpCert(ConfigurationContext configurationContext, byte[] cert, String fileName) { if (!verifyCertExistence(fileName, configurationContext)) { String workDir = (String) configurationContext.getProperty(ServerConstants.WORK_DIR); File pubCert = new File(workDir + File.separator + "pub_certs"); if (fileName == null) { fileName = String.valueOf(System.currentTimeMillis() + Math.random()) + ".cert"; } if (!pubCert.exists()) { pubCert.mkdirs(); } String filePath = workDir + File.separator + "pub_certs" + File.separator + fileName; OutputStream outStream = null; try { outStream = new FileOutputStream(filePath); outStream.write(cert); } catch (Exception e) { String msg = "Error when writing the public certificate to a file"; log.error(msg); throw new SecurityException("msg", e); } finally { IdentityIOStreamUtils.flushOutputStream(outStream); IdentityIOStreamUtils.closeOutputStream(outStream); } Map fileResourcesMap = (Map) configurationContext.getProperty(WSO2Constants.FILE_RESOURCE_MAP); if (fileResourcesMap == null) { fileResourcesMap = new Hashtable(); configurationContext.setProperty(WSO2Constants.FILE_RESOURCE_MAP, fileResourcesMap); } fileResourcesMap.put(fileName, filePath); } return WSO2Constants.ContextPaths.DOWNLOAD_PATH + "?id=" + fileName; }
Source:
public void testNonStaticInnerClasses() { boolean successful = false; try { ReflectData.get().getSchema(Definition.class); } catch (AvroTypeException ex) { if (ex.getMessage().contains("must be a static inner class")) { successful = true; } } assertTrue(successful); }

Target:
public void testNonStaticInnerClasses() { ReflectData.get().getSchema(Definition.class); }
Source:
public DeltaByteArrayWriter(int initialCapacity, int pageSize, ByteBufferAllocator allocator) { this.allocator=allocator; this.prefixLengthWriter = new DeltaBinaryPackingValuesWriter(128, 4, initialCapacity, pageSize, this.allocator); this.suffixWriter = new DeltaLengthByteArrayValuesWriter(initialCapacity, pageSize, this.allocator); this.previous = new byte[0]; }

Target:
public DeltaByteArrayWriter(int initialCapacity, int pageSize, ByteBufferAllocator allocator) { this.prefixLengthWriter = new DeltaBinaryPackingValuesWriter(128, 4, initialCapacity, pageSize, allocator); this.suffixWriter = new DeltaLengthByteArrayValuesWriter(initialCapacity, pageSize, allocator); this.previous = new byte[0]; }
Source:
public final int hashCode() { final int prime = 31; int result = 1; result = prime * result; result += (int) (absEndVar ^ (absEndVar >>> SHIFTDISTANCE)); result = prime * result + (int) (absStartVar ^ (absStartVar >>> SHIFTDISTANCE)); result = prime * result; if (contentVar != null) { result += contentVar.hashCode(); } result = prime * result + (int) (endVar ^ (endVar >>> SHIFTDISTANCE)); result = prime * result; if (mutationVar != null) { result += mutationVar.hashCode(); } result = prime * result; if (sourcesVar != null) { result += sourcesVar.hashCode(); } result = prime * result + (int) (startVar ^ (startVar >>> SHIFTDISTANCE)); return result; }

Target:
public final int hashCode() { final int prime = 31; int result = 1; result = prime * result; result += (int) (absEndVar ^ (absEndVar >>> prime + 1)); result = prime * result + (int) (absStartVar ^ (absStartVar >>> prime + 1)); result = prime * result; if (contentVar != null) { result += contentVar.hashCode(); } result = prime * result + (int) (endVar ^ (endVar >>> prime + 1)); result = prime * result; if (mutationVar != null) { result += mutationVar.hashCode(); } result = prime * result; if (sourcesVar != null) { result += sourcesVar.hashCode(); } result = prime * result + (int) (startVar ^ (startVar >>> prime + 1)); return result; }
Source:
public void sendPushMessage(Variant variant, Collection<String> clientIdentifiers, UnifiedPushMessage pushMessage, NotificationSenderCallback senderCallback) { if (clientIdentifiers.isEmpty()) { return; } final WindowsVariant windowsVariant = (WindowsVariant) variant; WnsService wnsService = new WnsService(windowsVariant.getSid(), windowsVariant.getClientSecret(), true); WnsToast toast = new WnsToastBuilder().bindingTemplateToastText01(pushMessage.getMessage().getAlert()).build(); try { Set<String> expiredClientIdentifiers = new HashSet<String>(clientIdentifiers.size()); final List<WnsNotificationResponse> responses = wnsService.pushToast(new ArrayList<String>(clientIdentifiers), toast); for (WnsNotificationResponse response : responses) { if (response.code == HttpServletResponse.SC_GONE) { expiredClientIdentifiers.add(response.channelUri); } } if (!expiredClientIdentifiers.isEmpty()) { logger.log(Level.INFO, String.format("Deleting '%d' expired WNS installations", expiredClientIdentifiers.size())); clientInstallationService.removeInstallationsForVariantByDeviceTokens(variant.getVariantID(), expiredClientIdentifiers); } logger.log(Level.INFO, "Message to WNS has been submitted"); senderCallback.onSuccess(); } catch (WnsException exception) { senderCallback.onError(exception.getMessage()); } }

Target:
public void sendPushMessage(Variant variant, Collection<String> clientIdentifiers, UnifiedPushMessage pushMessage, NotificationSenderCallback senderCallback) { if (clientIdentifiers.isEmpty()) { return; } final WindowsVariant windowsVariant = (WindowsVariant) variant; WnsService wnsService = new WnsService(windowsVariant.getSid(), windowsVariant.getClientSecret(), true); WnsToast toast = new WnsToastBuilder().bindingTemplateToastText01(pushMessage.getMessage().getAlert()).build(); try { Set<String> expiredClientIdentifiers = new HashSet<String>(clientIdentifiers.size()); final List<WnsNotificationResponse> responses = wnsService.pushToast(new ArrayList<String>(clientIdentifiers), toast); for (WnsNotificationResponse response : responses) { if (response.code == HttpServletResponse.SC_GONE) { expiredClientIdentifiers.add(response.channelUri); } } if (!expiredClientIdentifiers.isEmpty()) { logger.log(Level.INFO, String.format("Deleting '%d' expired WNS installations", expiredClientIdentifiers.size())); clientInstallationService.removeInstallationsForVariantByDeviceTokens(variant.getVariantID(), expiredClientIdentifiers); } logger.log(Level.FINE, "Message to WNS has been submitted"); senderCallback.onSuccess(); } catch (WnsException exception) { senderCallback.onError(exception.getMessage()); } }
Source:
void testSnapshotterTriggeredOnUnitOfWorkCommit() { SnapshotTrigger trigger = testSubject.prepareTrigger(aggregate.rootType()); GenericDomainEventMessage<String> msg = new GenericDomainEventMessage<>("type", aggregateIdentifier, 0, "Mock contents", MetaData.emptyInstance()); trigger.initializationFinished(); trigger.eventHandled(msg); trigger.eventHandled(msg); trigger.eventHandled(msg); trigger.eventHandled(msg); verify(mockSnapshotter, never()).scheduleSnapshot(aggregate.rootType(), aggregateIdentifier); CurrentUnitOfWork.get() .onCommit(uow -> verify(mockSnapshotter) .scheduleSnapshot(aggregate.rootType(), aggregateIdentifier)); CurrentUnitOfWork.commit(); }

Target:
void testSnapshotterTriggeredOnUnitOfWorkCommit() { SnapshotTrigger trigger = testSubject.prepareTrigger(aggregate.rootType()); GenericDomainEventMessage<String> msg = new GenericDomainEventMessage<>( "type", aggregateIdentifier, 0, "Mock contents", MetaData.emptyInstance() ); trigger.initializationFinished(); trigger.eventHandled(msg); trigger.eventHandled(msg); trigger.eventHandled(msg); trigger.eventHandled(msg); verify(mockSnapshotter, never()).scheduleSnapshot(aggregate.rootType(), aggregateIdentifier); CurrentUnitOfWork.commit(); verify(mockSnapshotter).scheduleSnapshot(aggregate.rootType(), aggregateIdentifier); }