auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void insertIntoChannel() { this.manager.channel().config().setAutoRead(false); this.manager.channel().pipeline().addBefore("packet_handler", "fml:packet_handler", this); ChannelPipeline cp = this.manager.channel().pipeline().addBefore("packet_handler", "fml:packet_handler", this); cp.context(this).executor().execute(() -> { if (this.state != null) { FMLLog.log.info("Opening channel which already seems to have a state set. This is a vanilla connection. Handshake handler will stop now"); this.manager.channel().config().setAutoRead(true); return; } FMLLog.log.trace("Handshake channel activating"); this.state = ConnectionState.OPENING; this.handshakeChannel.pipeline().fireUserEventTriggered(this); this.manager.channel().config().setAutoRead(true); }); }

Target:
private void insertIntoChannel() { this.manager.channel().config().setAutoRead(false); this.manager.channel().pipeline().addBefore("packet_handler", "fml:packet_handler", this); if (this.state != null) { FMLLog.log.info("Opening channel which already seems to have a state set. This is a vanilla connection. Handshake handler will stop now"); this.manager.channel().config().setAutoRead(true); return; } FMLLog.log.trace("Handshake channel activating"); this.state = ConnectionState.OPENING; this.handshakeChannel.pipeline().fireUserEventTriggered(this); this.manager.channel().config().setAutoRead(true); }
Source:
public ActionsCategory handleMultipleNodes(ActionsCategory category, ActionsManager manager, List<Element> elements) { final List<Classifier> classifiers = new ArrayList<Classifier>(); final List<InstanceSpecification> instances = new ArrayList<InstanceSpecification>(); final List<Element> validatableElements = new ArrayList<Element>(); boolean hasUneditable = false; for (Element element : elements) { if (element != null) { if (element instanceof Classifier) { classifiers.add((Classifier) element); validatableElements.add(element); } else if (element instanceof InstanceSpecification) { instances.add((InstanceSpecification) element); validatableElements.add(element); } if (!hasUneditable && !element.isEditable()) { hasUneditable = true; } } } if (validatableElements.isEmpty()) { return null; } validateAction = new ValidateAction(validatableElements); category.addAction(validateAction); if (!classifiers.isEmpty()) { } if (!instances.isEmpty()) { instance2BSTAction = new Instance2BSTAction(instances); } return category; }

Target:
public ActionsCategory handleMultipleNodes(ActionsCategory category, ActionsManager manager, List<Element> elements) { final List<Classifier> classifiers = new ArrayList<Classifier>(); final List<InstanceSpecification> instances = new ArrayList<InstanceSpecification>(); final List<Element> validatableElements = new ArrayList<Element>(); boolean hasUneditable = false; for (Element element : elements) { if (element != null) { if (element instanceof Classifier) { classifiers.add((Classifier) element); validatableElements.add(element); } else if (element instanceof InstanceSpecification) { instances.add((InstanceSpecification) element); validatableElements.add(element); } if (!hasUneditable && !element.isEditable()) { hasUneditable = true; } } } if (validatableElements.isEmpty()) { return null; } validateAction = new ValidateAction(validatableElements); category.addAction(validateAction); if (!instances.isEmpty()) { instance2BSTAction = new Instance2BSTAction(instances); } return category; }
Source:
public void dropContentsOfInventory(DoDestroyEvent event, EntityRef entity) { Vector3f position = entity.getComponent(LocationComponent.class).getWorldPosition(); int slotCount = inventoryManager.getNumSlots(entity); for (int i=0; i<slotCount; i++) { EntityRef itemInSlot = inventoryManager.getItemInSlot(entity, 0); if (itemInSlot.exists()) { inventoryManager.removeItem(entity, itemInSlot); pickupBuilder.createPickupFor(itemInSlot, position, 60); } } }

Target:
public void dropContentsOfInventory(DoDestroyEvent event, EntityRef entity) { Vector3f position = entity.getComponent(LocationComponent.class).getWorldPosition(); FastRandom random = new FastRandom(); int slotCount = inventoryManager.getNumSlots(entity); for (int i = 0; i < slotCount; i++) { EntityRef itemInSlot = inventoryManager.getItemInSlot(entity, i); if (itemInSlot.exists()) { EntityRef pickup = pickupBuilder.createPickupFor(itemInSlot, position, 60, true); pickup.send(new ImpulseEvent(random.nextVector3f(30.0f))); } } }
Source:
public Response getConfiguration( @PathParam("serviceId") @ApiParam(value = "service ID", required = true) String serviceId) { try { Configuration configuration = configurationService.get(serviceId); return configuration != null ? Response.ok(configuration.getProperties()).build() : Response.ok(Collections.emptyMap()).build(); } catch (IOException ex) { logger.error("Cannot get configuration for service {}: {}", serviceId, ex.getMessage(), ex); return Response.status(Status.INTERNAL_SERVER_ERROR).build(); } }

Target:
public Response getConfiguration( @PathParam("serviceId") @ApiParam(value = "service ID", required = true) String serviceId) { try { Configuration configuration = configurationService.get(serviceId); return configuration != null ? Response.ok(configuration.getProperties()).build() : Response.ok(Collections.emptyMap()).build(); } catch (IOException ex) { logger.error("Cannot get configuration for service {}: ", serviceId, ex); return Response.status(Status.INTERNAL_SERVER_ERROR).build(); } }
Source:
private AuthenticationRequest getAuthenticationRequest(final String authority, final String resource, final String clientId, final boolean isExtendedLifetimeEnabled) { final AuthenticationRequest authRequest = new AuthenticationRequest(authority, resource, clientId, isExtendedLifetimeEnabled); return authRequest; }

Target:
private AuthenticationRequest getAuthenticationRequest(final String authority, final String resource, final String clientId, final boolean isExtendedLifetimeEnabled) { return new AuthenticationRequest(authority, resource, clientId, isExtendedLifetimeEnabled); }
Source:
public void onPlayerSlotChange(final PlayerItemHeldEvent event) { final Player player = event.getPlayer(); final int slot = event.getNewSlot() + 1; GeneralMethods.displayMovePreview(player, slot); if (ConfigManager.defaultConfig.get().getBoolean("Abilities.Water.WaterArms.DisplayBoundMsg")) { final WaterArms waterArms = CoreAbility.getAbility(player, WaterArms.class); if (waterArms != null) { waterArms.displayBoundMsg(event.getNewSlot() + 1); return; } } }

Target:
public void onPlayerSlotChange(final PlayerItemHeldEvent event) { final Player player = event.getPlayer(); final int slot = event.getNewSlot() + 1; if (ConfigManager.defaultConfig.get().getBoolean("Properties.BendingPreview")) { GeneralMethods.displayMovePreview(player, slot); } if (ConfigManager.defaultConfig.get().getBoolean("Abilities.Water.WaterArms.DisplayBoundMsg")) { final WaterArms waterArms = CoreAbility.getAbility(player, WaterArms.class); if (waterArms != null) { waterArms.displayBoundMsg(event.getNewSlot() + 1); return; } } }
Source:
public void connect() throws ZkInterruptedException { boolean isConnected = zkClient.waitUntilConnected(connectionTimeoutMs, TimeUnit.MILLISECONDS); if (!isConnected && metrics != null) { metrics.zkConnectionError.inc(); throw new RuntimeException("Unable to connect to Zookeeper within connectionTimeout " + connectionTimeoutMs + "ms. Shutting down!"); } }

Target:
public void connect() throws ZkInterruptedException { boolean isConnected = zkClient.waitUntilConnected(connectionTimeoutMs, TimeUnit.MILLISECONDS); if (!isConnected) { if (metrics != null) { metrics.zkConnectionError.inc(); } throw new RuntimeException("Unable to connect to Zookeeper within connectionTimeout " + connectionTimeoutMs + "ms. Shutting down!"); } }
Source:
private static boolean isAloneLambda(Details details) { final DetailAST lcurly = details.lcurly; final DetailAST rcurly = details.rcurly; final DetailAST previousSibling = rcurly.getPreviousSibling(); final int lcurlyNo = lcurly.getLineNo(); final int rcurlyNo = rcurly.getLineNo(); boolean result = false; if (lcurlyNo != rcurlyNo) { result = previousSibling == null || rcurlyNo != previousSibling.getLineNo(); } return result; }

Target:
private static boolean isAloneLambda(Details details) { final DetailAST lcurly = details.lcurly; final DetailAST rcurly = details.rcurly; final int lcurlyNo = lcurly.getLineNo(); final int rcurlyNo = rcurly.getLineNo(); boolean result = false; if (lcurlyNo != rcurlyNo) { result = rcurly.getPreviousSibling() == null || rcurlyNo != rcurly.getPreviousSibling().getLineNo(); } return result; }
Source:
public CertificationBodyDTO getByCode(String code) { Query query = entityManager.createQuery( "SELECT acb from CertificationBodyEntity acb " + "LEFT OUTER JOIN FETCH acb.address " + "WHERE (acb.deleted = false) " + "AND (UPPER(acb.acbCode) = :code) ", CertificationBodyEntity.class); query.setParameter("code", code.toUpperCase()); List<CertificationBodyEntity> result = query.getResultList(); if (result != null && result.size() > 0) { return new CertificationBodyDTO(result.get(0)); } return null; }

Target:
public CertificationBodyDTO getByCode(String code) { Query query = entityManager.createQuery("SELECT acb " + "FROM CertificationBodyEntity acb " + "LEFT OUTER JOIN FETCH acb.address " + "WHERE (acb.deleted = false) " + "AND (UPPER(acb.acbCode) = :code) ", CertificationBodyEntity.class); query.setParameter("code", code.toUpperCase()); List<CertificationBodyEntity> result = query.getResultList(); if (result != null && result.size() > 0) { return new CertificationBodyDTO(result.get(0)); } return null; }
Source:
public Response getProvider(@PathParam("providerId") String providerId, @Context HttpServletRequest request) throws IOException, RestOperationException { OAuth2ServiceProvider provider = Framework.getLocalService(OAuth2ServiceProviderRegistry.class) .getProvider(providerId); if (provider == null || !(provider instanceof NuxeoOAuth2ServiceProvider)) { RestOperationException err = new RestOperationException("Invalid provider: " + providerId); err.setStatus(HttpServletResponse.SC_BAD_REQUEST); throw err; } Map<String,Object> result = new HashMap<>(); result.put("serviceName", provider.getServiceName()); result.put("enabled", provider.isEnabled()); result.put("clientId", provider.getClientId()); result.put("scopes", provider.getScopes()); result.put("authorizationURL", provider.getClientId() == null ? null : provider.getAuthorizationUrl(request)); result.put("authorizationServerURL", provider.getAuthorizationServerURL()); result.put("tokenServerURL", provider.getTokenServerURL()); String username = request.getUserPrincipal().getName(); NuxeoOAuth2Token token = getToken((NuxeoOAuth2ServiceProvider)provider, username); boolean hasToken = (token != null); String login = hasToken ? token.getServiceLogin() : null; result.put("hasToken", hasToken); result.put("userId", login); return buildResponse(Status.OK, result); }

Target:
public Response getProvider(@PathParam("providerId") String providerId, @Context HttpServletRequest request) throws IOException, RestOperationException { NuxeoOAuth2ServiceProvider provider = getProvider(providerId); Map<String,Object> result = new HashMap<>(); result.put("serviceName", provider.getServiceName()); result.put("isAvailable", provider.isProviderAvailable()); result.put("clientId", provider.getClientId()); result.put("authorizationURL", provider.getClientId() == null ? null : provider.getAuthorizationUrl(request)); String username = request.getUserPrincipal().getName(); NuxeoOAuth2Token token = getToken(provider, username); boolean isAuthorized = (token != null); String login = isAuthorized ? token.getServiceLogin() : null; result.put("isAuthorized", isAuthorized); result.put("userId", login); return buildResponse(Status.OK, result); }
Source:
public void testRangesTransaction() { Transaction t = startTransaction(); put(t, "row1", "col1", "v1"); t.commit(); RangeRequest allRange = RangeRequest.builder().batchHint(3).build(); t = startTransaction(); verifyAllGetRangesImplsRangeSizes(t, Iterables.limit(Iterables.cycle(allRange), 1000), 1); }

Target:
public void testRangesTransaction() { Transaction t = startTransaction(); put(t, "row1", "col1", "v1"); t.commit(); RangeRequest allRange = RangeRequest.builder().batchHint(3).build(); t = startTransaction(); verifyAllGetRangesImplsRangeSizes(t, allRange, 1); }
Source:
public boolean performFinish() { if (selectedDataObservable.getValue() instanceof BusinessObjectData) { return perFormFinishForBusinessObjectData(); } if (selectedDataObservable.getValue() instanceof Document) { return performFinishForDocument(); } return true; }

Target:
public boolean performFinish() { final Object selectedData = selectedDataObservable.getValue(); if (selectedData instanceof BusinessObjectData) { return perFormFinishForBusinessObjectData(); } if (selectedData instanceof Document) { return performFinishForDocument(); } return true; }
Source:
public View getView(int position, View convertView, ViewGroup parent) { View view; if(!isInitialized){ visibleButtons = new LinkedList<SquareButtonWithNotification>(); Log.i("HomeScrnAdpt","Creating all buttons because got a null in position " + position); for (int i = 0; i < buttons.length; i++) { if (buttons[i] != null) continue; SquareButtonWithNotification button = (SquareButtonWithNotification) LayoutInflater.from(context) .inflate(buttonsResources[i], parent, false); buttons[i] = button; Log.i("HomeScrnAdpt","Added button " + button + "to position " + i); View.OnClickListener listener = buttonListeners[i]; if(listener != null) { button.setOnClickListener(listener); Log.i("HomeScrnAdpt","Added onClickListener " + listener + " to button in position " + i); } if( i == position ) view = button; if(!hiddenButtons[i]) visibleButtons.add(button); } isInitialized = true; } if(position < 0 || position >= getCount()) return null; if(convertView != null) { return convertView; } else { SquareButtonWithNotification btn = visibleButtons.get(position); if(btn == null) { Log.i("HomeScrnAdpt","Unexpected null button"); } return btn; } }

Target:
public View getView(int position, View convertView, ViewGroup parent) { if (position < 0 || position >= getCount()) { return null; } if (convertView != null) { return convertView; } else { SquareButtonWithNotification btn = visibleButtons.get(position); if (btn == null) { Log.i(TAG, "Unexpected null button"); } return btn; } }
Source:
String getDependentName(RuntimeCapability cap, OperationContext context) { if (cap.isDynamicallyNamed()) { return cap.fromBaseCapability(context.getCurrentAddress()).getName(); } else { return cap.getName(); } }

Target:
String getDependentName(RuntimeCapability cap, OperationContext context) { if (cap.isDynamicallyNamed()) { return cap.fromBaseCapability(context.getCurrentAddress()).getName(); } return cap.getName(); }
Source:
public Builder executor(@NonNull ExecutorService executorService) { checkNotNull(executorService, "executorService == null"); if (!isChild && this.service != null) { throw new IllegalStateException("Executor service already set."); } this.service = executorService; return this; }

Target:
public Builder executor(@NonNull ExecutorService executorService) { checkNotNull(executorService, "executorService == null"); this.service = executorService; return this; }
Source:
public void parseButtonClicked() { List<Path> fileList = checkedFileList.stream() .map(item -> item.getValue().getPath()) .filter(path -> path.toFile().isFile()) .collect(Collectors.toList()); if (fileList.isEmpty()) { LOGGER.warn("There are no valid files checked"); return; } BackgroundTask.wrap(() -> new TexBibEntriesResolver(databaseContext.getDatabase(), preferencesService.getImportFormatPreferences(), fileMonitor).resolve(new DefaultTexParser().parse(fileList))) .onRunning(() -> searchInProgress.set(true)) .onFinished(() -> searchInProgress.set(false)) .onSuccess(result -> new ParseTexResultView(result, databaseContext, Paths.get(texDirectory.get())).showAndWait()) .onFailure(dialogService::showErrorDialogAndWait) .executeWith(taskExecutor); }

Target:
public void parseButtonClicked() { List<Path> fileList = checkedFileList.stream() .map(item -> item.getValue().getPath()) .filter(path -> path.toFile().isFile()) .collect(Collectors.toList()); if (fileList.isEmpty()) { LOGGER.warn("There are no valid files checked"); return; } TexBibEntriesResolver entriesResolver = new TexBibEntriesResolver(databaseContext.getDatabase(), preferencesService.getImportFormatPreferences(), fileMonitor); BackgroundTask.wrap(() -> entriesResolver.resolve(new DefaultTexParser().parse(fileList))) .onRunning(() -> searchInProgress.set(true)) .onFinished(() -> searchInProgress.set(false)) .onSuccess(result -> new ParseTexResultView(result, databaseContext, Paths.get(texDirectory.get())).showAndWait()) .onFailure(dialogService::showErrorDialogAndWait) .executeWith(taskExecutor); }
Source:
public void reportIssue(Tree tree, String message, Set<List<JavaFileScannerContext.Location>> flows) { Preconditions.checkNotNull(tree); Optional<SEIssue> sameTreeIssue = issueWithTree(tree); sameTreeIssue.ifPresent(issue -> issue.flows.addAll(flows)); if (!sameTreeIssue.isPresent()) { issues.add(new SEIssue(tree, message, flows)); } }

Target:
public void reportIssue(Tree tree, String message, Set<List<JavaFileScannerContext.Location>> flows) { issues.add(issues.stream() .filter(seIssue -> seIssue.tree.equals(tree)) .findFirst() .map(seIssue -> { seIssue.flows.addAll(flows); return seIssue; }) .orElse(new SEIssue(tree, message, flows))); }
Source:
public void testReadBooleans() { V4Vm object = objectFromJson("{'properties': [false, true]}"); List<Boolean> expected = Arrays.asList(false, true); assertEquals(expected, object.properties()); }

Target:
public void testReadBooleans() { objectFromJson("{'properties': [false, true]}"); }
Source:
private void generateKey() { try { keyStore = KeyStore.getInstance("AndroidKeyStore"); } catch (Exception e) { e.printStackTrace(); } KeyGenerator keyGenerator; try { keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore"); } catch (NoSuchAlgorithmException | NoSuchProviderException e) { throw new RuntimeException("Failed to get KeyGenerator instance", e); } try { keyStore.load(null); keyGenerator.init(new KeyGenParameterSpec.Builder(KEY_NAME, KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT) .setBlockModes(KeyProperties.BLOCK_MODE_CBC) .setUserAuthenticationRequired(true) .setEncryptionPaddings( KeyProperties.ENCRYPTION_PADDING_PKCS7) .build()); keyGenerator.generateKey(); } catch (NoSuchAlgorithmException | InvalidAlgorithmParameterException | CertificateException | IOException e) { } }

Target:
private void generateKey() { try { keyStore = KeyStore.getInstance("AndroidKeyStore"); } catch (Exception e) { Log.e(TAG, "Error(0): " + e.getMessage()); } KeyGenerator keyGenerator; try { keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore"); } catch (NoSuchAlgorithmException | NoSuchProviderException e) { throw new RuntimeException("Failed to get KeyGenerator instance", e); } try { keyStore.load(null); keyGenerator.init(new KeyGenParameterSpec.Builder(KEY_NAME, KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT) .setBlockModes(KeyProperties.BLOCK_MODE_CBC) .setUserAuthenticationRequired(true) .setEncryptionPaddings( KeyProperties.ENCRYPTION_PADDING_PKCS7) .build()); keyGenerator.generateKey(); } catch (NoSuchAlgorithmException | InvalidAlgorithmParameterException | CertificateException | IOException e) { Log.e(TAG, "Error(1): " + e.getMessage()); } }
Source:
public static String parseMessage(final String i18nMessage, Object... args) { final String pattern = getPattern(i18nMessage); try { return parseFormat(pattern, args); } catch (IllegalArgumentException e) { LOGGER.warn(CORE, "Invalid translation pattern for key {}!", i18nMessage); return i18nMessage+" - invalid pattern"; } }

Target:
public static String parseMessage(final String i18nMessage, Object... args) { final String pattern = getPattern(i18nMessage); try { return parseFormat(pattern, args); } catch (IllegalArgumentException e) { LOGGER.warn(CORE, "Invalid translation pattern for key {}: {}!", i18nMessage, e.getLocalizedMessage()); return i18nMessage; } }
Source:
public Response updateSenseBlackList(@Scope(OAuthScope.ADMINISTRATION_READ) final AccessToken accessToken, @Valid final Set<String> updatedSenseBlackList) { Jedis jedis = null; try { jedis = jedisPool.getResource(); final Pipeline pipe = jedis.pipelined(); pipe.multi(); pipe.del(BlackListDevicesConfiguration.SENSE_BLACK_LIST_KEY); for (final String senseId : updatedSenseBlackList){ pipe.sadd(BlackListDevicesConfiguration.SENSE_BLACK_LIST_KEY, senseId); } pipe.exec(); } catch (JedisDataException e) { if (jedis != null) { jedisPool.returnBrokenResource(jedis); } throw new WebApplicationException(Response.status(Response.Status.INTERNAL_SERVER_ERROR) .entity(new JsonError(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), String.format("Failed to get data from redis - %s", e.getMessage()))).build()); } catch (Exception e) { if (jedis != null) { jedisPool.returnBrokenResource(jedis); } throw new WebApplicationException(Response.status(Response.Status.INTERNAL_SERVER_ERROR) .entity(new JsonError(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), String.format("Failed to update sense black list because %s", e.getMessage()))).build()); } finally { if (jedis != null) { jedisPool.returnResource(jedis); } } return Response.noContent().build(); }

Target:
public Response updateSenseBlackList(@Scope(OAuthScope.ADMINISTRATION_READ) final AccessToken accessToken, @Valid final Set<String> updatedSenseBlackList) { Jedis jedis = null; try { jedis = jedisPool.getResource(); final Pipeline pipe = jedis.pipelined(); pipe.multi(); pipe.del(BlackListDevicesConfiguration.SENSE_BLACK_LIST_KEY); for (final String senseId : updatedSenseBlackList){ pipe.sadd(BlackListDevicesConfiguration.SENSE_BLACK_LIST_KEY, senseId); } pipe.exec(); } catch (JedisDataException e) { if (jedis != null) { jedisPool.returnBrokenResource(jedis); jedis = null; } throw new WebApplicationException(Response.status(Response.Status.INTERNAL_SERVER_ERROR) .entity(new JsonError(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), String.format("Failed to get data from redis - %s", e.getMessage()))).build()); } catch (Exception e) { if (jedis != null) { jedisPool.returnBrokenResource(jedis); jedis = null; } throw new WebApplicationException(Response.status(Response.Status.INTERNAL_SERVER_ERROR) .entity(new JsonError(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), String.format("Failed to update sense black list because %s", e.getMessage()))).build()); } finally { if (jedis != null) { jedisPool.returnResource(jedis); } } return Response.noContent().build(); }
Source:
public ArrayList<EnrolledCoursesResponse> getDownloadedCoursesWithVideoCountAndSize() { ArrayList<EnrolledCoursesResponse> downloadedCourseList = new ArrayList<>(); List<EnrolledCoursesResponse> enrolledCourses = null; String username = getUsername(); if (username != null) { enrolledCourses = api.getUserEnrolledCourses(username, true); } if(enrolledCourses!=null && enrolledCourses.size()>0){ for(EnrolledCoursesResponse enrolledCoursesResponse : enrolledCourses){ int videoCount = db.getDownloadedVideoCountByCourse( enrolledCoursesResponse.getCourse().getId(),null); if(videoCount>0){ enrolledCoursesResponse.videoCount = videoCount; enrolledCoursesResponse.size = db.getDownloadedVideosSizeByCourse( enrolledCoursesResponse.getCourse().getId(),null); downloadedCourseList.add(enrolledCoursesResponse); } } } return downloadedCourseList; }

Target:
public ArrayList<EnrolledCoursesResponse> getDownloadedCoursesWithVideoCountAndSize() { ArrayList<EnrolledCoursesResponse> downloadedCourseList = new ArrayList<>(); List<EnrolledCoursesResponse> enrolledCourses = null; String username = getUsername(); if (username != null) { enrolledCourses = api.getUserEnrolledCourses(username, true); } if(enrolledCourses.size()>0){ for(EnrolledCoursesResponse enrolledCoursesResponse : enrolledCourses){ int videoCount = db.getDownloadedVideoCountByCourse( enrolledCoursesResponse.getCourse().getId(),null); if(videoCount>0){ enrolledCoursesResponse.videoCount = videoCount; enrolledCoursesResponse.size = db.getDownloadedVideosSizeByCourse( enrolledCoursesResponse.getCourse().getId(),null); downloadedCourseList.add(enrolledCoursesResponse); } } } return downloadedCourseList; }
Source:
public static void fhirResourceSearchPost(String fhirStoreName, String resourceType) throws IOException, URISyntaxException { CloudHealthcare client = createClient(); HttpClient httpClient = HttpClients.createDefault(); String uri = String.format( "%sv1beta1/%s/fhir/%s/_search", client.getRootUrl(), fhirStoreName, resourceType); URIBuilder uriBuilder = new URIBuilder(uri) .setParameter("access_token", getAccessToken()); StringEntity requestEntity = new StringEntity(""); HttpUriRequest request = RequestBuilder .post() .setUri(uriBuilder.build()) .setEntity(requestEntity) .addHeader("Content-Type", "application/fhir+json") .addHeader("Accept-Charset", "utf-8") .addHeader("Accept", "application/fhir+json; charset=utf-8") .build(); HttpResponse response = httpClient.execute(request); HttpEntity responseEntity = response.getEntity(); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { System.err.print(String.format( "Exception searching FHIR resources: %s\n", response.getStatusLine().toString())); responseEntity.writeTo(System.err); throw new RuntimeException(); } System.out.println("FHIR resource search results: "); responseEntity.writeTo(System.out); }

Target:
public static void fhirResourceSearchPost(String fhirStoreName, String resourceType) throws IOException, URISyntaxException { CloudHealthcare client = createClient(); HttpClient httpClient = HttpClients.createDefault(); String uri = String.format( "%sv1/%s/fhir/%s/_search", client.getRootUrl(), fhirStoreName, resourceType); URIBuilder uriBuilder = new URIBuilder(uri) .setParameter("access_token", getAccessToken()); StringEntity requestEntity = new StringEntity(""); HttpUriRequest request = RequestBuilder .post() .setUri(uriBuilder.build()) .setEntity(requestEntity) .addHeader("Content-Type", "application/fhir+json") .addHeader("Accept-Charset", "utf-8") .addHeader("Accept", "application/fhir+json; charset=utf-8") .build(); HttpResponse response = httpClient.execute(request); HttpEntity responseEntity = response.getEntity(); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { System.err.print(String.format( "Exception searching FHIR resources: %s\n", response.getStatusLine().toString())); responseEntity.writeTo(System.err); throw new RuntimeException(); } System.out.println("FHIR resource search results: "); responseEntity.writeTo(System.out); }
Source:
protected void moveCursor(final int keyCode) { int index; switch (keyCode) { case SWT.HOME: index = 0; while (index < fScaledData.fLastBucket && fScaledData.fData[index].isEmpty()) { index++; } if (index < fScaledData.fLastBucket) { fScaledData.fSelectionBeginBucket = index; } break; case SWT.ARROW_RIGHT: { long prevTime = getTimestamp(fScaledData.fSelectionBeginBucket); index = Math.max(0, fScaledData.fSelectionBeginBucket + 1); while (index < fScaledData.fWidth && (fScaledData.fData[index].isEmpty() || prevTime == getTimestamp(index))) { index++; } if (index >= fScaledData.fLastBucket) { index = fScaledData.fLastBucket; } fScaledData.fSelectionBeginBucket = index; break; } case SWT.END: index = fScaledData.fLastBucket; while (index >= 0 && fScaledData.fData[index].isEmpty()) { index--; } if (index >= 0) { fScaledData.fSelectionBeginBucket = index; } break; case SWT.ARROW_LEFT: { long prevTime = getTimestamp(fScaledData.fSelectionBeginBucket); index = Math.min(fScaledData.fLastBucket - 1, fScaledData.fSelectionBeginBucket - 1); while (index >= 0 && (fScaledData.fData[index].isEmpty() || prevTime == getTimestamp(index))) { index--; } if (index <= 0) { index = 0; } fScaledData.fSelectionBeginBucket = index; break; } default: return; } fScaledData.fSelectionEndBucket = fScaledData.fSelectionBeginBucket; fSelectionBegin = getTimestamp(fScaledData.fSelectionBeginBucket); fSelectionEnd = fSelectionBegin; updateSelectionTime(); }

Target:
protected void moveCursor(final int keyCode) { int index; switch (keyCode) { case SWT.HOME: fScaledData.fSelectionBeginBucket = 0; break; case SWT.END: fScaledData.fSelectionBeginBucket = fScaledData.fWidth - 1; break; case SWT.ARROW_RIGHT: { long prevStartTime = getTimestamp(fScaledData.fSelectionBeginBucket); index = Math.max(0, Math.min(fScaledData.fLastBucket - 1, fScaledData.fSelectionBeginBucket + 1)); while (index < fScaledData.fWidth && (fScaledData.fData[index].isEmpty() || prevStartTime == getTimestamp(index))) { prevStartTime = getTimestamp(index); index++; } if (index >= fScaledData.fWidth) { index = fScaledData.fWidth - 1; } fScaledData.fSelectionBeginBucket = index; break; } case SWT.ARROW_LEFT: { long prevEndTime = getTimestamp(fScaledData.fSelectionBeginBucket + 1); index = Math.max(0, Math.min(fScaledData.fLastBucket - 1, fScaledData.fSelectionBeginBucket - 1)); while (index >= 0 && (fScaledData.fData[index].isEmpty() || prevEndTime == getTimestamp(index + 1))) { prevEndTime = getTimestamp(index + 1); index--; } if (index <= 0) { index = 0; } fScaledData.fSelectionBeginBucket = index; break; } default: return; } fScaledData.fSelectionEndBucket = fScaledData.fSelectionBeginBucket; fSelectionBegin = getTimestamp(fScaledData.fSelectionBeginBucket); fSelectionEnd = fSelectionBegin; updateSelectionTime(); }
Source:
public Object execute(ExecutionEvent event) throws ExecutionException { ISelection selection = HandlerUtil.getCurrentSelection(event); RefreshRepositoryTasksAction na = new RefreshRepositoryTasksAction(); na.selectionChanged((IStructuredSelection) selection); na.run(); return null; }

Target:
public Object execute(ExecutionEvent event) throws ExecutionException { ISelection selection = HandlerUtil.getCurrentSelection(event); RefreshRepositoryTasksAction action = new RefreshRepositoryTasksAction(); action.selectionChanged((IStructuredSelection) selection); action.run(); return null; }
Source:
public String getName(IterationInfo iteration) { if (delegate == null) return fallback.getName(iteration); try { String name = delegate.getName(iteration); if (name != null) return name; return fallback.getName(iteration); } catch (Exception e) { return fallback.getName(iteration); } }

Target:
public String getName(IterationInfo iteration) { if (delegate == null) return getFallbackName(iteration); try { String name = delegate.getName(iteration); if (name != null) return name; return getFallbackName(iteration); } catch (Exception e) { return getFallbackName(iteration); } }
Source:
public JSchProcess(IRemoteProcess process) { fProcess = process; fChannel = ((JSchProcessBuilder) process.getProcessBuilder()).getChannel(); try { if (process.getProcessBuilder().redirectErrorStream()) { PipedOutputStream pipedOutput = new PipedOutputStream(); fProcStdout = new PipedInputStream(pipedOutput); fProcStderr = new NullInputStream(); if (fChannel instanceof ChannelExec) { fStderrReader = new Thread(new ProcReader(((ChannelExec) fChannel).getErrStream(), pipedOutput)); } fStdoutReader = new Thread(new ProcReader(fChannel.getInputStream(), pipedOutput)); fStderrReader.start(); fStdoutReader.start(); } else { fProcStdout = fChannel.getInputStream(); if (fChannel instanceof ChannelExec) { fProcStderr = ((ChannelExec) fChannel).getErrStream(); } } } catch (IOException e) { Activator.log(e); destroy(); } }

Target:
public JSchProcess(IRemoteProcess process) { fProcess = process; fChannel = ((JSchProcessBuilder) process.getProcessBuilder()).getChannel(); try { if (process.getProcessBuilder().redirectErrorStream()) { PipedOutputStream pipedOutput = new PipedOutputStream(); fProcStdout = new PipedInputStream(pipedOutput); fProcStderr = new NullInputStream(); fStderrReader = new Thread(new ProcReader(fChannel.getExtInputStream(), pipedOutput)); fStdoutReader = new Thread(new ProcReader(fChannel.getInputStream(), pipedOutput)); fStderrReader.start(); fStdoutReader.start(); } else { fProcStdout = fChannel.getInputStream(); fProcStderr = fChannel.getExtInputStream(); } } catch (IOException e) { Activator.log(e); destroy(); } }
Source:
public void createClassContext(@Observes(precedence=100) EventContext<ClassEvent> context) { ClassContext classContext = this.classContextInstance.get(); try { classContext.activate(context.getEvent().getTestClass().getJavaClass()); testClassProducer.set(context.getEvent().getTestClass()); context.proceed(); } finally { if (AfterClass.class.isAssignableFrom(context.getEvent().getClass())) { classContext.deactivate(); classContext.clearAll(); classContext.destroy(context.getEvent().getTestClass().getJavaClass()); } } }

Target:
public void createClassContext(@Observes(precedence = 100) EventContext<ClassEvent> context) { ClassContext classContext = this.classContextInstance.get(); try { classContext.activate(context.getEvent().getTestClass().getJavaClass()); testClassProducer.set(context.getEvent().getTestClass()); context.proceed(); } finally { classContext.deactivate(); if (AfterClass.class.isAssignableFrom(context.getEvent().getClass())) { classContext.destroy(context.getEvent().getTestClass().getJavaClass()); } } }
Source:
public void testCustomCallbackIsWrappedByDefaultCallbackBehavior() { MockProducer<String, String> producer = new MockProducer<>(Cluster.empty(), false, null, null, null); KafkaBolt<String, String> bolt = makeBolt(producer); PreparableCallback customCallback = mock(PreparableCallback.class); bolt.withProducerCallback(customCallback); OutputCollector collector = mock(OutputCollector.class); bolt.prepare(new HashMap<>(), mock(TopologyContext.class), collector); String key = "KEY"; String value = "VALUE"; Tuple testTuple = createTestTuple(key, value); bolt.execute(testTuple); assertThat(producer.history().size(), is(1)); ProducerRecord<String, String> arg = producer.history().get(0); LOG.info("GOT ->", arg); LOG.info("{}, {}, {}", arg.topic(), arg.key(), arg.value()); assertThat(arg.topic(), is("MY_TOPIC")); assertThat(arg.key(), is(key)); assertThat(arg.value(), is(value)); producer.completeNext(); verify(collector).ack(testTuple); verify(customCallback).onCompletion(any(), any()); }

Target:
public void testCustomCallbackIsWrappedByDefaultCallbackBehavior() { MockProducer<String, String> producer = new MockProducer<>(Cluster.empty(), false, null, null, null); KafkaBolt<String, String> bolt = makeBolt(producer); PreparableCallback customCallback = mock(PreparableCallback.class); bolt.withProducerCallback(customCallback); OutputCollector collector = mock(OutputCollector.class); TopologyContext context = mock(TopologyContext.class); Map<String, Object> topoConfig = new HashMap<>(); bolt.prepare(topoConfig, context, collector); verify(customCallback).prepare(topoConfig, context); String key = "KEY"; String value = "VALUE"; Tuple testTuple = createTestTuple(key, value); bolt.execute(testTuple); assertThat(producer.history().size(), is(1)); ProducerRecord<String, String> arg = producer.history().get(0); LOG.info("GOT ->", arg); LOG.info("{}, {}, {}", arg.topic(), arg.key(), arg.value()); assertThat(arg.topic(), is("MY_TOPIC")); assertThat(arg.key(), is(key)); assertThat(arg.value(), is(value)); KafkaException ex = new KafkaException(); producer.errorNext(ex); verify(customCallback).onCompletion(any(), eq(ex)); verify(collector).reportError(ex); verify(collector).fail(testTuple); }
Source:
public <F> SerializableConsumer<F> setDataProvider( DataProvider<T, F> dataProvider, F initialFilter) { Objects.requireNonNull(dataProvider, "data provider cannot be null"); filter = initialFilter; doSetDefinedSize(null, null, -1, true); skipSizeCheckUntilReset = false; sizeReset = false; handleDetach(); reset(); getKeyMapper().removeAll(); this.dataProvider = dataProvider; getKeyMapper().setIdentifierGetter(dataProvider::getId); handleAttach(); return filter -> { if (this.dataProvider != dataProvider) { throw new IllegalStateException( "Filter slot is no longer valid after data provider has been changed"); } if (!Objects.equals(this.filter, filter)) { this.filter = filter; reset(); } }; }

Target:
public <F> SerializableConsumer<F> setDataProvider( DataProvider<T, F> dataProvider, F initialFilter) { Objects.requireNonNull(dataProvider, "data provider cannot be null"); filter = initialFilter; clearSizeCallbacksAndState(); definedSize = true; sizeReset = false; handleDetach(); reset(); getKeyMapper().removeAll(); this.dataProvider = dataProvider; getKeyMapper().setIdentifierGetter(dataProvider::getId); handleAttach(); return filter -> { if (this.dataProvider != dataProvider) { throw new IllegalStateException( "Filter slot is no longer valid after data provider has been changed"); } if (!Objects.equals(this.filter, filter)) { this.filter = filter; reset(); } }; }
Source:
public void addTargetGroup(TargetGroup targetGroup) { if (targetGroups == null) { targetGroups = new HashSet<>(); } targetGroups.add(targetGroup); }

Target:
public void addTargetGroup(TargetGroup targetGroup) { targetGroups.add(targetGroup); }
Source:
public <A extends Annotation> A getAnnotation(Class<A> annotationType) { return wrapped.getAnnotation(annotationType); }

Target:
public <A extends Annotation> A getAnnotation(Class<A> annotationType) { for (Annotation annotation : annotations) { if (annotationType.isInstance(annotation)) { return (A) annotation; } } return null; }
Source:
public void setUp() throws Exception { root = Files.createTempDirectory("jgit-security").toFile(); permissions.add(new RuntimePermission("*")); permissions.add(new SecurityPermission("*")); permissions.add(new AuthPermission("*")); permissions.add(new ReflectPermission("*")); permissions.add(new PropertyPermission("*", "read,write")); permissions.add(new LoggingPermission("control", null)); permissions.add(new FilePermission( System.getProperty("java.home") + "/-", "read")); String tempDir = System.getProperty("java.io.tmpdir"); permissions.add(new FilePermission(tempDir, "read,write,delete")); permissions .add(new FilePermission(tempDir + "/-", "read,write,delete")); String classPath = System.getProperty("java.class.path"); if (classPath != null) { for (String path : classPath.split(File.pathSeparator)) { permissions.add(new FilePermission(path, "read")); } } String jgitSourcesRoot = new File(System.getProperty("user.dir")) .getParent(); permissions.add(new FilePermission(jgitSourcesRoot + "/-", "read")); permissions.add(new FilePermission(root.getPath() + "/-", "read,write,delete,execute")); String userHome = System.getProperty("user.home"); permissions.add(new FilePermission(userHome, "read")); permissions.add(new FilePermission(userHome + "/-", "read,write")); permissions.add(new FilePermission("/etc/gitconfig", "read")); originalSecurityManager = System.getSecurityManager(); System.setSecurityManager(new SecurityManager() { @Override public void checkPermission(Permission requested) { for (Permission permission : permissions) { if (permission.implies(requested)) { return; } } super.checkPermission(requested); } }); }

Target:
public void setUp() throws Exception { SystemReader.setInstance(new MockSystemReader()); root = Files.createTempDirectory("jgit-security").toFile(); permissions.add(new RuntimePermission("*")); permissions.add(new SecurityPermission("*")); permissions.add(new AuthPermission("*")); permissions.add(new ReflectPermission("*")); permissions.add(new PropertyPermission("*", "read,write")); permissions.add(new LoggingPermission("control", null)); permissions.add(new FilePermission( System.getProperty("java.home") + "/-", "read")); String tempDir = System.getProperty("java.io.tmpdir"); permissions.add(new FilePermission(tempDir, "read,write,delete")); permissions .add(new FilePermission(tempDir + "/-", "read,write,delete")); String classPath = System.getProperty("java.class.path"); if (classPath != null) { for (String path : classPath.split(File.pathSeparator)) { permissions.add(new FilePermission(path, "read")); } } String jgitSourcesRoot = new File(System.getProperty("user.dir")) .getParent(); permissions.add(new FilePermission(jgitSourcesRoot + "/-", "read")); permissions.add(new FilePermission(root.getPath() + "/-", "read,write,delete,execute")); originalSecurityManager = System.getSecurityManager(); System.setSecurityManager(new SecurityManager() { @Override public void checkPermission(Permission requested) { for (Permission permission : permissions) { if (permission.implies(requested)) { return; } } super.checkPermission(requested); } }); }
Source:
protected void channelRead0(ChannelHandlerContext ctx, Message msg) throws Exception { seenMessages.incrementAndGet(); byte[] payload = msg.asBytes(); if (encryptionConfig != null) { try { payload = encrypt(payload); } catch (Exception e) { log.error("Fail to encrypt message: ", e.getMessage()); } } String kafkaTopic = defaultTopic; byte[] partitionKey = null; for (String tag : msg.getTags()) { if (tag.startsWith("kt:")) { kafkaTopic = tag.substring(3); } else if (tag.startsWith("pk:")) { partitionKey = Base64.getUrlDecoder().decode( tag.substring(3)); } } sendOrReportFailure(kafkaTopic, partitionKey, payload); if (propagate) { msg.retain(); ctx.fireChannelRead(msg); } }

Target:
protected void channelRead0(ChannelHandlerContext ctx, Message msg) throws Exception { seenMessages.incrementAndGet(); byte[] payload = msg.asBytes(); if (encryptionConfig != null) { try { payload = encrypt(payload); } catch (Exception e) { log.error("Fail to encrypt message: ", e.getMessage()); } } String kafkaTopic = defaultTopic; String partitionKey = null; for (String tag : msg.getTags()) { if (tag.startsWith("kt:")) { kafkaTopic = tag.substring(3); } else if (tag.startsWith("pk:")) { partitionKey = tag.substring(3); } } sendOrReportFailure(kafkaTopic, partitionKey, payload); if (propagate) { msg.retain(); ctx.fireChannelRead(msg); } }
Source:
public void a_pancake_can_be_fried_out_of_an_egg_milk_and_flour() { given() .ingredients().comma() .consisting_of() .asterisk() .an() .egg() .asterisk() .some() .milk() .asterisk() .the() .ingredient( "flour" ); when() .the_cook_mangles_everthing_to_a_dough(). and() .the_cook_fries_the_dough_in_a_pan(); then() .the_resulting_meal_is_a_pan_cake(); }

Target:
public void a_pancake_can_be_fried_out_of_an_egg_milk_and_flour() { given() .some() .open_bracket().fresh().close_bracket() .ingredients().comma() .consisting_of().colon() .an() .egg() .some() .milk() .the() .ingredient( "flour" ); when() .the_cook_mangles_everthing_to_a_dough(). and() .the_cook_fries_the_dough_in_a_pan(); then() .the_resulting_meal_is_a_pan_cake(); }
Source:
public Condition unvoidCondition(Condition condition) throws APIException { condition.setVoided(false); condition.setVoidedBy(null); condition.setDateVoided(null); condition.setVoidReason(null); Context.getConditionService().saveCondition(condition); return condition; }

Target:
public Condition unvoidCondition(Condition condition) { return Context.getConditionService().saveCondition(condition); }
Source:
public static boolean isSessionValid(HttpServletRequest req) throws NamingException { String sessionId = (String) req.getSession(true).getAttribute(SessionConstants.SSO_TOKEN_KEY); boolean isValid = false; if (StringUtils.isNotEmpty(sessionId)) { try { SSOQueryServiceUtils.getFromSsoQueryService(req, String.format("command=sso-token-validate&sso_token=%s", sessionId)); isValid = true; } catch (Exception e) { log.error("Session not valid session id = " + sessionId, e.getMessage()); } } return isValid; }

Target:
public static boolean isSessionValid(HttpServletRequest req) throws NamingException { String sessionId = (String) req.getSession(true).getAttribute(SessionConstants.SSO_TOKEN_KEY); boolean isValid = false; if (StringUtils.isNotEmpty(sessionId)) { try { SSOQueryServiceUtils.getFromSsoQueryService("command=sso-token-validate&sso_token=%s", sessionId); isValid = true; } catch (Exception e) { log.error("Session not valid session id = " + sessionId, e.getMessage()); } } return isValid; }
Source:
public EObject getEObject(String uriFragment) { Option<String> optionalRewrittenFragment = VSMMigrationService.getInstance().getNewFragment(uriFragment); if (optionalRewrittenFragment.some()) { return getEObject(optionalRewrittenFragment.get()); } else { if (useURIFragmentAsId) { return getEObjectUsingURIFragmentAsId(uriFragment); } else { return super.getEObject(uriFragment); } } }

Target:
public EObject getEObject(String uriFragment) { Option<String> optionalRewrittenFragment = VSMMigrationService.getInstance().getNewFragment(uriFragment); if (optionalRewrittenFragment.some()) { return getEObject(optionalRewrittenFragment.get()); } else if (useURIFragmentAsId) { return getEObjectUsingURIFragmentAsId(uriFragment); } else { return super.getEObject(uriFragment); } }
Source:
public SimpleSearcher(String indexDir) throws IOException { Path indexPath = Paths.get(indexDir); if (!Files.exists(indexPath) || !Files.isDirectory(indexPath) || !Files.isReadable(indexPath)) { throw new IllegalArgumentException(indexDir + " does not exist or is not a directory."); } this.reader = DirectoryReader.open(FSDirectory.open(indexPath)); this.similarity = new LMDirichletSimilarity(1000.0f); this.analyzer = new EnglishAnalyzer(); setNormalReranker(); }

Target:
public SimpleSearcher(String indexDir) throws IOException { Path indexPath = Paths.get(indexDir); if (!Files.exists(indexPath) || !Files.isDirectory(indexPath) || !Files.isReadable(indexPath)) { throw new IllegalArgumentException(indexDir + " does not exist or is not a directory."); } this.reader = DirectoryReader.open(FSDirectory.open(indexPath)); this.similarity = new LMDirichletSimilarity(1000.0f); this.analyzer = new EnglishAnalyzer(); this.searchtweets = false; this.isRerank = false; setDefaultReranker(); }
Source:
public void requestBannerAd(Context context, MediationBannerListener listener, Bundle serverParameters, AdSize adSize, MediationAdRequest adRequest, Bundle mediationExtras) { mBannerListener = listener; String gameId = serverParameters.getString(KEY_GAME_ID); mBannerPlacementId = serverParameters.getString(KEY_PLACEMENT_ID); if (!isValidIds(gameId, mPlacementId)) { if (mBannerListener != null) { mBannerListener.onAdFailedToLoad(UnityAdapter.this, AdRequest.ERROR_CODE_INVALID_REQUEST); } return; } if (!isValidContext(context)) { return; } if (!UnitySingleton.initializeUnityAds(mUnityAdapterDelegate, (Activity) context, gameId)) { if (mBannerListener != null) { mBannerListener.onAdFailedToLoad(UnityAdapter.this, AdRequest.ERROR_CODE_INVALID_REQUEST); } return; } mActivityWeakReference = new WeakReference<>((Activity) context); UnitySingleton.loadBannerAd(mBannerDelegate); }

Target:
public void requestBannerAd(Context context, MediationBannerListener listener, Bundle serverParameters, AdSize adSize, MediationAdRequest adRequest, Bundle mediationExtras) { mBannerListener = listener; String gameId = serverParameters.getString(KEY_GAME_ID); mBannerPlacementId = serverParameters.getString(KEY_PLACEMENT_ID); if (!isValidIds(gameId, mBannerPlacementId)) { if (mBannerListener != null) { mBannerListener.onAdFailedToLoad(UnityAdapter.this, AdRequest.ERROR_CODE_INVALID_REQUEST); } return; } if (!isValidContext(context)) { return; } if (!UnitySingleton.initializeUnityAds(mUnityAdapterDelegate, (Activity) context, gameId)) { if (mBannerListener != null) { mBannerListener.onAdFailedToLoad(UnityAdapter.this, AdRequest.ERROR_CODE_INVALID_REQUEST); } return; } mActivityWeakReference = new WeakReference<>((Activity) context); UnitySingleton.loadBannerAd(mBannerDelegate); }
Source:
public Stream<? extends DomainEventData<?>> findSnapshots(MongoCollection<Document> snapshotCollection, String aggregateIdentifier) { FindIterable<Document> cursor = snapshotCollection.find(eq(eventConfiguration.aggregateIdentifierProperty(), aggregateIdentifier)) .sort(new BasicDBObject(eventConfiguration.sequenceNumberProperty(), ORDER_ASC)).limit(1); return stream(cursor.spliterator(), false).map(this::extractSnapshot); }

Target:
public Stream<? extends DomainEventData<?>> findSnapshots(MongoCollection<Document> snapshotCollection, String aggregateIdentifier) { FindIterable<Document> cursor = snapshotCollection.find(eq(eventConfiguration.aggregateIdentifierProperty(), aggregateIdentifier)) .sort(orderBy(descending(eventConfiguration.sequenceNumberProperty()))); return stream(cursor.spliterator(), false).map(this::extractSnapshot); }