auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public ReviewInput toReviewInput(@NotNull Review review) { ReviewInput reviewInput = new ReviewInput(); reviewInput.message = Joiner.on(". ").join(review.getMessages()); reviewInput.labels = new HashMap<>(review.getScores()); reviewInput.comments = new HashMap<>(); for (ReviewFile file : review.getFiles()) { List<ReviewInput.CommentInput> comments = new ArrayList<>(); for (Comment comment : file.getComments()) { if(commentFilter.filter(file.getReviewFilename(), comment.getLine())){ log.debug("Filter comment in file line {}", file.getReviewFilename(), comment.getLine()); continue; } ReviewInput.CommentInput commentInput = new ReviewInput.CommentInput(); commentInput.line = comment.getLine(); commentInput.message = comment.getMessage(); comments.add(commentInput); } reviewInput.comments.put(file.getReviewFilename(), comments); } return reviewInput; }

Target:
public ReviewInput toReviewInput(@NotNull Review review) { ReviewInput reviewInput = new ReviewInput(); reviewInput.message = Joiner.on(". ").join(review.getMessages()); reviewInput.labels = new HashMap<>(review.getScores()); reviewInput.comments = new HashMap<>(); for (ReviewFile file : review.getFiles()) { List<ReviewInput.CommentInput> comments = new ArrayList<>(); for (Comment comment : file.getComments()) { if (commentFilter.filter(file.getReviewFilename(), comment.getLine())) { log.debug("Comment excluded in file line {}", file.getReviewFilename(), comment.getLine()); continue; } ReviewInput.CommentInput commentInput = new ReviewInput.CommentInput(); commentInput.line = comment.getLine(); commentInput.message = comment.getMessage(); comments.add(commentInput); } reviewInput.comments.put(file.getReviewFilename(), comments); } return reviewInput; }
Source:
LocalDateTime extractExpiryDate(Map<String, String> args, ZoneId effectiveTimeZone) { LocalDateTime expiry = null; if (args.containsKey("Expires".toLowerCase())) { val ts = args.get("Expires".toLowerCase()); val explicit = Instant.ofEpochMilli(Long.parseLong(ts) * 1000); expiry = LocalDateTime.ofInstant(explicit, effectiveTimeZone); } else if (args.containsKey("X-Amz-Expires".toLowerCase()) && (args.containsKey("X-Amz-Date".toLowerCase()))) { String ts = ""; try { ts = args.get("X-Amz-Date".toLowerCase()); val formatter = DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmssX"); val reqDate = ZonedDateTime.parse(ts, formatter); log.trace("Request DateTime (Zoned): %s%n", reqDate); val expSeconds = Integer.parseInt(args.get("X-Amz-Expires".toLowerCase())); expiry = reqDate.withZoneSameInstant(effectiveTimeZone).toLocalDateTime().plusSeconds(expSeconds); System.out.printf("Expiry DateTime (Local): %s%n", expiry); } catch (DateTimeParseException pe) { log.error("%s is not parsable!%n", ts); throw pe; } } else { log.error("Could not identify expected date parameters in request: {}", flattenMap(args)); throw new IllegalArgumentException( String.format("Could not parse presigned URL - missing expected expiry date parameters")); } return expiry; }

Target:
LocalDateTime extractExpiryDate(Map<String, String> args, ZoneId effectiveTimeZone) { LocalDateTime expiry = null; if (args.containsKey(HttpHeaders.EXPIRES.toLowerCase())) { val ts = args.get(HttpHeaders.EXPIRES.toLowerCase()); val explicit = Instant.ofEpochMilli(Long.parseLong(ts) * 1000); expiry = LocalDateTime.ofInstant(explicit, effectiveTimeZone); } else if (args.containsKey(SignerConstants.X_AMZ_EXPIRES.toLowerCase()) && (args.containsKey(SignerConstants.X_AMZ_DATE.toLowerCase()))) { String ts = ""; try { ts = args.get(SignerConstants.X_AMZ_DATE.toLowerCase()); val reqDate = ZonedDateTime.parse(ts, formatter); log.trace("Request DateTime (Zoned): %s%n", reqDate); val expSeconds = Integer.parseInt(args.get(SignerConstants.X_AMZ_EXPIRES.toLowerCase())); expiry = reqDate.withZoneSameInstant(effectiveTimeZone).toLocalDateTime().plusSeconds(expSeconds); System.out.printf("Expiry DateTime (Local): %s%n", expiry); } catch (DateTimeParseException pe) { log.error("%s is not parsable!%n", ts); throw pe; } } else { log.error("Could not identify expected date parameters in request: {}", flattenMap(args)); throw new IllegalArgumentException( String.format("Could not parse presigned URL - missing expected expiry date parameters")); } return expiry; }
Source:
public void getEvents(EventConsumer c, BinlogPosition endPosition) throws Exception { int max_tries = 10; while ( true ) { MaxwellAbstractRowsEvent e = getEvent(); if (e == null) { if (max_tries > 0) { max_tries--; continue; } else { System.out.println("maxwell didn't reach the position requested."); return; } } c.consume(e); if ( eventBinlogPosition(e).newerThan(endPosition) ) return; } }

Target:
public void getEvents(EventConsumer c, BinlogPosition endPosition) throws Exception { int max_tries = 10; while ( true ) { MaxwellAbstractRowsEvent e = getEvent(); if (e == null) { if (max_tries > 0) { max_tries--; continue; } else { LOGGER.error("maxwell didn't reach the position requested."); return; } } c.consume(e); if ( eventBinlogPosition(e).newerThan(endPosition) ) return; } }
Source:
private boolean validatePassword(String password, String repeatedPassword) { if (password == null || password.trim().equals("")) { log(""); log(" * Error *\nThe password should not be empty"); return false; } if (repeatedPassword == null || repeatedPassword.trim().equals("")) { log(""); log(" * Error *\nThe repeated password should not be empty"); return false; } if (!password.equals(repeatedPassword)) { log(""); log(" * Error *\nThe passwords you introduced do not match each other. Please write them again."); return false; } if (!password.matches(".*\\d+.*")) { log(""); log(" * Error *\nThe passwords should include numbers."); return false; } if (password.length() < 8) { log(""); log(" * Error *\nThe lengh of the password should be at least of 8 characters."); return false; } return true; }

Target:
private boolean validatePassword(String password, String repeatedPassword) { if (password == null || password.trim().equals("")) { log(""); log(" * Error *\nThe password should not be empty"); return false; } if (repeatedPassword == null || repeatedPassword.trim().equals("")) { log(""); log(" * Error *\nThe repeated password should not be empty"); return false; } if (!password.equals(repeatedPassword)) { log(""); log(" * Error *\nThe passwords you introduced do not match each other. Please write them again."); return false; } if (!password.matches(".*\\d+.*")) { log(""); log(" * Error *\nThe passwords should include numbers."); return false; } if (password.length() < 8) { log(""); log(" * Error *\nThe length of the password should be at least of 8 characters."); return false; } return true; }
Source:
private HashMap<String, Geofence> getGeofencesFromCursor(Cursor cursor, int limit) { HashMap<String, Geofence> result = new HashMap<>(limit); Geofence geofence; int i = 0; while (cursor.moveToNext()) { i++; if (i <= HIGH) { String fence = cursor.getString(0); geofence = buildGeofence(fence); if (geofence != null) { result.put(fence, geofence); } } else { Logger.log.geofenceError("Over " + HIGH + " found in cursor", null); break; } } return result; }

Target:
private HashMap<String, Geofence> getGeofencesFromCursor(Cursor cursor, int limit) { HashMap<String, Geofence> result = new HashMap<>(limit); Geofence geofence; int i = 0; while (cursor.moveToNext()) { i++; if (i <= HIGH) { String fence = cursor.getString(cursor.getColumnIndex(DBHelper.TG_FENCE)); geofence = buildGeofence(fence); if (geofence != null) { result.put(fence, geofence); } } else { Logger.log.geofenceError("Over " + HIGH + " found in cursor", null); break; } } return result; }
Source:
public CoreMessage putCharProperty(String key, char value) { messageChanged(); getOrCreateProperties().putCharProperty(key(key), value); return this; }

Target:
public CoreMessage putCharProperty(String key, char value) { return putCharProperty(key(key), value); }
Source:
private StreamApplicationDescriptorImpl getTestJoinStreamGraph(TestJoinFunction joinFn) throws IOException { Map<String, String> mapConfig = new HashMap<>(); mapConfig.put("job.name", "jobName"); mapConfig.put("job.id", "jobId"); StreamTestUtils.addStreamConfigs(mapConfig, "inStream", "insystem", "instream"); StreamTestUtils.addStreamConfigs(mapConfig, "inStream2", "insystem", "instream2"); Config config = new MapConfig(mapConfig); return new StreamApplicationDescriptorImpl(appDesc -> { IntegerSerde integerSerde = new IntegerSerde(); KVSerde<Integer, Integer> kvSerde = KVSerde.of(integerSerde, integerSerde); GenericSystemDescriptor sd = new GenericSystemDescriptor("insystem", "mockFactoryClassName"); GenericInputDescriptor<KV<Integer, Integer>> inputDescriptor1 = sd.getInputDescriptor("inStream", kvSerde); GenericInputDescriptor<KV<Integer, Integer>> inputDescriptor2 = sd.getInputDescriptor("inStream2", kvSerde); MessageStream<KV<Integer, Integer>> inStream = appDesc.getInputStream(inputDescriptor1); MessageStream<KV<Integer, Integer>> inStream2 = appDesc.getInputStream(inputDescriptor2); inStream .join(inStream2, joinFn, integerSerde, kvSerde, kvSerde, JOIN_TTL, "j1") .sink((message, messageCollector, taskCoordinator) -> { SystemStream outputSystemStream = new SystemStream("outputSystem", "outputStream"); messageCollector.send(new OutgoingMessageEnvelope(outputSystemStream, message)); return message; }); }, config); }

Target:
private StreamApplicationDescriptorImpl getTestJoinStreamGraph(TestJoinFunction joinFn) throws IOException { Map<String, String> mapConfig = new HashMap<>(); mapConfig.put("job.name", "jobName"); mapConfig.put("job.id", "jobId"); StreamTestUtils.addStreamConfigs(mapConfig, "inStream", "insystem", "instream"); StreamTestUtils.addStreamConfigs(mapConfig, "inStream2", "insystem", "instream2"); Config config = new MapConfig(mapConfig); return new StreamApplicationDescriptorImpl(appDesc -> { IntegerSerde integerSerde = new IntegerSerde(); KVSerde<Integer, Integer> kvSerde = KVSerde.of(integerSerde, integerSerde); GenericSystemDescriptor sd = new GenericSystemDescriptor("insystem", "mockFactoryClassName"); GenericInputDescriptor<KV<Integer, Integer>> inputDescriptor1 = sd.getInputDescriptor("inStream", kvSerde); GenericInputDescriptor<KV<Integer, Integer>> inputDescriptor2 = sd.getInputDescriptor("inStream2", kvSerde); MessageStream<KV<Integer, Integer>> inStream = appDesc.getInputStream(inputDescriptor1); MessageStream<KV<Integer, Integer>> inStream2 = appDesc.getInputStream(inputDescriptor2); inStream .join(inStream2, joinFn, integerSerde, kvSerde, kvSerde, JOIN_TTL, "j1") .sink((message, messageCollector, taskCoordinator) -> { SystemStream outputSystemStream = new SystemStream("outputSystem", "outputStream"); messageCollector.send(new OutgoingMessageEnvelope(outputSystemStream, message)); }); }, config); }
Source:
public static String toFriendlyMessage(@Code int code) { switch (code) { case UNKNOWN_ERROR: return "Unknown error"; case NO_NETWORK: return "No internet connection"; case PLAY_SERVICES_UPDATE_CANCELLED: return "Play Services update cancelled"; case DEVELOPER_ERROR: return "Developer error"; case PROVIDER_ERROR: return "Provider error"; case ANONYMOUS_UPGRADE_MERGE_CONFLICT: return "Merge conflict"; default: throw new IllegalArgumentException("Unknown code: " + code); } }

Target:
public static String toFriendlyMessage(@Code int code) { switch (code) { case UNKNOWN_ERROR: return "Unknown error"; case NO_NETWORK: return "No internet connection"; case PLAY_SERVICES_UPDATE_CANCELLED: return "Play Services update cancelled"; case DEVELOPER_ERROR: return "Developer error"; case PROVIDER_ERROR: return "Provider error"; case ANONYMOUS_UPGRADE_MERGE_CONFLICT: return "User account merge conflict"; case EMAIL_MISMATCH_ERROR: return "You are are attempting to sign in a different email than previously " + "provided"; default: throw new IllegalArgumentException("Unknown code: " + code); } }
Source:
public void analyzerOverride_queryOnlyAnalyzer() { StubMappingSearchScope scope = indexManager.createSearchScope(); String absoluteFieldPath = indexMapping.whitespaceLowercaseAnalyzedField.relativeFieldName; IndexSearchQuery<DocumentReference> query = scope.query() .asReference() .predicate( f -> f.match().onField( absoluteFieldPath ).matching( "worldofwordcraft" ) .analyzer( OverrideAnalysisDefinitions.ANALYZER_NGRAM.name ) ) .toQuery(); assertThat( query ) .hasDocRefHitsAnyOrder( INDEX_NAME, DOCUMENT_1, DOCUMENT_2, DOCUMENT_3 ); }

Target:
public void analyzerOverride_queryOnlyAnalyzer() { StubMappingSearchScope scope = indexManager.createSearchScope(); String absoluteFieldPath = indexMapping.whitespaceLowercaseAnalyzedField.relativeFieldName; IndexSearchQuery<DocumentReference> query = scope.query() .asReference() .predicate( f -> f.match().onField( absoluteFieldPath ).matching( "worldofwordcraft" ) ) .toQuery(); assertThat( query ).hasNoHits(); query = scope.query() .asReference() .predicate( f -> f.match().onField( absoluteFieldPath ).matching( "worldofwordcraft" ) .analyzer( OverrideAnalysisDefinitions.ANALYZER_NGRAM.name ) ) .toQuery(); assertThat( query ) .hasDocRefHitsAnyOrder( INDEX_NAME, DOCUMENT_1, DOCUMENT_2, DOCUMENT_3 ); }
Source:
public Optional<WorldProperties> getDefaultWorld() { final Optional<WorldServer> optWorldServer = DimensionManager.getWorldByDimensionId(0); if (optWorldServer.isPresent()) { return Optional.of(((World) optWorldServer.get()).getProperties()); } return Optional.empty(); }

Target:
public Optional<WorldProperties> getDefaultWorld() { return DimensionManager.getWorldByDimensionId(0).map(worldServer -> ((World) worldServer).getProperties()); }
Source:
public void append(byte[] nameBuf, int namePos, int nameLen, FileMode mode, AnyObjectId id, boolean allowEmptyName) { if (nameLen == 0 && !allowEmptyName) throw new IllegalArgumentException("Can't append a tree entry with zero-length name"); if (fmtBuf(nameBuf, namePos, nameLen, mode)) { id.copyRawTo(buf, ptr); ptr += OBJECT_ID_LENGTH; } else { try { fmtOverflowBuffer(nameBuf, namePos, nameLen, mode); id.copyRawTo(overflowBuffer); } catch (IOException badBuffer) { throw new RuntimeException(badBuffer); } } }

Target:
public void append(byte[] nameBuf, int namePos, int nameLen, FileMode mode, AnyObjectId id, boolean allowEmptyName) { if (nameLen == 0 && !allowEmptyName) { throw new IllegalArgumentException( JGitText.get().invalidTreeZeroLengthName); } if (fmtBuf(nameBuf, namePos, nameLen, mode)) { id.copyRawTo(buf, ptr); ptr += OBJECT_ID_LENGTH; } else { try { fmtOverflowBuffer(nameBuf, namePos, nameLen, mode); id.copyRawTo(overflowBuffer); } catch (IOException badBuffer) { throw new RuntimeException(badBuffer); } } }
Source:
public void testInsertAnnotated() throws Exception { SqlSession sqlSession = sqlSessionFactory.openSession(); try { InsertMapper mapper = sqlSession.getMapper(InsertMapper.class); Name name = new Name(); name.setFirstName("Fred"); name.setLastName("Flintstone"); int rows = mapper.insertNameAnnotated(name); assertNotNull(name.getId()); assertEquals(1, rows); } finally { sqlSession.close(); } }

Target:
public void testInsertAnnotated() throws Exception { try (SqlSession sqlSession = sqlSessionFactory.openSession()) { InsertMapper mapper = sqlSession.getMapper(InsertMapper.class); Name name = new Name(); name.setFirstName("Fred"); name.setLastName("Flintstone"); int rows = mapper.insertNameAnnotated(name); assertNotNull(name.getId()); assertEquals(1, rows); } }
Source:
public void visitMethodDeclaration(MethodDeclarationTree tree) { if (!isNested) { add(tree.name()); excludeLastReturn(tree.body().statements()); isNested = true; super.visitMethodDeclaration(tree); isNested = false; } }

Target:
public void visitMethodDeclaration(MethodDeclarationTree tree) { if (mustAnalyse()) { add(tree.name()); excludeLastReturn(tree.body().statements()); isInsideFunction = true; super.visitMethodDeclaration(tree); isInsideFunction = false; } }
Source:
public void executeCallback() { if(!highlighter_.getCallbackProcessed(index_)) { highlighter_.setCallbackProcessed(index_, true); highlighter_.getServer().executeRCode(callback_, new ServerRequestCallback<String>(){ @Override public void onResponseReceived(String results) { highlighter_.clearEvents(); } @Override public void onError(ServerError error) { Debug.logError(error); } }); } }

Target:
public void executeCallback() { if(!highlighter_.getCallbackProcessed(index_)) { highlighter_.setCallbackProcessed(index_, true); highlighter_.getServer().executeRCode(callback_, new ServerRequestCallback<String>(){ @Override public void onResponseReceived(String results) { highlighter_.clearEvents(); } @Override public void onError(ServerError error) { highlighter_.clearEvents(); Debug.logError(error); } }); } }
Source:
public void visitNode(Tree tree) { if (!hasSemantic()) { return; } MethodTree methodTree = (MethodTree) tree; Symbol.MethodSymbol methodSymbol = methodTree.symbol(); if (!methodSymbol.isPublic() || BooleanUtils.isNotFalse(((MethodTreeImpl) methodTree).isOverriding()) || isOverloaded(methodSymbol)) { return; } List<Symbol> parameters = methodTree.parameters().stream() .map(VariableTree::symbol) .collect(Collectors.toList()); for (Symbol param : parameters) { if (param.type().isClass() && !param.type().symbol().isEnum() && !param.type().is("java.lang.String")) { handleParameter(param); } } }

Target:
public void visitNode(Tree tree) { if (!hasSemantic()) { return; } MethodTree methodTree = (MethodTree) tree; Symbol.MethodSymbol methodSymbol = methodTree.symbol(); if (!methodSymbol.isPublic() || BooleanUtils.isNotFalse(((MethodTreeImpl) methodTree).isOverriding()) || isOverloaded(methodSymbol)) { return; } methodTree.parameters().stream() .map(VariableTree::symbol) .filter(p -> p.type().isClass() && !p.type().symbol().isEnum() && !p.type().is("java.lang.String")) .forEach(this::handleParameter); }
Source:
private String loadJsonFromAsset(String filename) { String json; try { InputStream is = getAssets().open(filename); int size = is.available(); byte[] buffer = new byte[size]; is.read(buffer); is.close(); json = new String(buffer, "UTF-8"); } catch (IOException ex) { ex.printStackTrace(); return null; } return json; }

Target:
private String loadJsonFromAsset(String filename) { try { InputStream is = getAssets().open(filename); int size = is.available(); byte[] buffer = new byte[size]; is.read(buffer); is.close(); return new String(buffer, "UTF-8"); } catch (IOException ex) { ex.printStackTrace(); return null; } }
Source:
private AllocateResponse sendContainerAskToRM(List<ContainerRequest> containerRequests, List<ContainerRequest> removedContainerRequests, List<ContainerId> releasedContainers) throws YarnException, IOException { if (removedContainerRequests.size() > 0) { LOG.debug("Removing container request: {}", removedContainerRequests); for (ContainerRequest cr : removedContainerRequests) { amRmClient.removeContainerRequest(cr); } } if (containerRequests.size() > 0) { LOG.debug("Asking RM for containers: {}", containerRequests); for (ContainerRequest cr : containerRequests) { amRmClient.addContainerRequest(cr); } } for (ContainerId containerId : releasedContainers) { LOG.info("Released container, id={}", containerId.getId()); amRmClient.releaseAssignedContainer(containerId); } for (String containerIdStr : dnmgr.containerStopRequests.values()) { AllocatedContainer allocatedContainer = this.allocatedContainers.get(containerIdStr); if (allocatedContainer != null && !allocatedContainer.stopRequested) { nmClient.stopContainerAsync(allocatedContainer.container.getId(), allocatedContainer.container.getNodeId()); LOG.info("Requested stop container {}", containerIdStr); allocatedContainer.stopRequested = true; pendingContainersToKill.put(containerIdStr, System.currentTimeMillis()); } dnmgr.containerStopRequests.remove(containerIdStr); } for (Map.Entry<String, Long> pendingToKill : pendingContainersToKill.entrySet()) { if (System.currentTimeMillis() - pendingToKill.getValue() >= REMOVE_CONTAINER_TIMEOUT) { LOG.info("Timeout happened for NodeManager kill container request, recovering the container without waiting", pendingToKill.getKey()); recoverContainer(pendingToKill.getKey()); } } return amRmClient.allocate(0); }

Target:
private AllocateResponse sendContainerAskToRM(List<ContainerRequest> containerRequests, List<ContainerRequest> removedContainerRequests, List<ContainerId> releasedContainers) throws YarnException, IOException { if (removedContainerRequests.size() > 0) { LOG.debug("Removing container request: {}", removedContainerRequests); for (ContainerRequest cr : removedContainerRequests) { amRmClient.removeContainerRequest(cr); } } if (containerRequests.size() > 0) { LOG.debug("Asking RM for containers: {}", containerRequests); for (ContainerRequest cr : containerRequests) { amRmClient.addContainerRequest(cr); } } for (ContainerId containerId : releasedContainers) { LOG.info("Released container, id={}", containerId.getId()); amRmClient.releaseAssignedContainer(containerId); } for (String containerIdStr : dnmgr.containerStopRequests.values()) { AllocatedContainer allocatedContainer = this.allocatedContainers.get(containerIdStr); if (allocatedContainer != null) { allocatedContainer.stop(nmClient); } dnmgr.containerStopRequests.remove(containerIdStr); } for (Map.Entry<String, AllocatedContainer> entry : allocatedContainers.entrySet()) { if (entry.getValue().checkStopRequestedTimeout()) { LOG.info("Timeout happened for NodeManager kill container request, recovering the container without waiting", entry.getKey()); recoverHelper(entry.getKey()); } } return amRmClient.allocate(0); }
Source:
protected boolean canDoAction() { if (!super.canDoAction()) { return false; } if (getParameters().getClusterId() == null) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_CLUSTER_IS_NOT_VALID); return false; } if (getParameters().getConfigParams() == null || getParameters().getConfigParams().size() == 0) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_GLUSTER_VOLUME_SNAPSHOT_CONFIG_PARAMS_IS_EMPTY); return false; } for (GlusterVolumeSnapshotConfig param : getParameters().getConfigParams()) { if (param.getParamValue() == null || param.getParamValue().equals("")) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_GLUSTER_VOLUME_SNAPSHOT_CONFIG_PARAM_VALUE_IS_EMPTY); return false; } } return true; }

Target:
protected boolean canDoAction() { if (!super.canDoAction()) { return false; } if (getParameters().getClusterId() == null) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_CLUSTER_IS_NOT_VALID); return false; } if (getParameters().getConfigParams() == null || getParameters().getConfigParams().isEmpty()) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_GLUSTER_VOLUME_SNAPSHOT_CONFIG_PARAMS_IS_EMPTY); return false; } for (GlusterVolumeSnapshotConfig param : getParameters().getConfigParams()) { if (param.getParamValue() == null || param.getParamValue().equals("")) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_GLUSTER_VOLUME_SNAPSHOT_CONFIG_PARAM_VALUE_IS_EMPTY); return false; } } return true; }
Source:
public void selectFromList(String locator, String... items) { String itemList = items.length != 0 ? String.format("option(s) [ %s ]", Python.join(" | ", items)) : "all options"; logging.info(String.format("Selecting %s from list '%s'.", itemList, locator)); Select select = getSelectList(locator); if (items.length == 0) { for (int i = 0; i < select.getOptions().size(); i++) { select.selectByIndex(i); } return; } boolean lastItemFound = false; List<String> nonExistingItems = new ArrayList<>(); for (String item : items) { lastItemFound = true; try { select.selectByValue(item); } catch (NoSuchElementException e1) { try { select.selectByVisibleText(item); } catch (NoSuchElementException e2) { nonExistingItems.add(item); lastItemFound = false; } } } if (nonExistingItems.size() != 0) { if (select.isMultiple()) { throw new SeleniumLibraryNonFatalException(String.format("Options '%s' not in list '%s'.", Python.join(", ", nonExistingItems), locator)); } logging.warn(String.format("Option%s '%s' not found within list '%s'.", nonExistingItems.size() == 0 ? "" : "s", Python.join(", ", nonExistingItems), locator)); if (!lastItemFound) { throw new SeleniumLibraryNonFatalException(String.format("Option '%s' not in list '%s'.", nonExistingItems.get(nonExistingItems.size() - 1), locator)); } } }

Target:
public void selectFromList(String locator, String... items) { String itemList = items.length != 0 ? String.format("option(s) [ %s ]", Python.join(" | ", items)) : "all options"; logging.info(String.format("Selecting %s from list '%s'.", itemList, locator)); Select select = getSelectList(locator); if (items.length == 0) { for (int i = 0; i < select.getOptions().size(); i++) { select.selectByIndex(i); } return; } boolean lastItemFound = false; List<String> nonExistingItems = new ArrayList<>(); for (String item : items) { lastItemFound = true; try { select.selectByValue(item); } catch (NoSuchElementException e1) { try { select.selectByVisibleText(item); } catch (NoSuchElementException e2) { nonExistingItems.add(item); lastItemFound = false; continue; } } } if (nonExistingItems.size() != 0) { if (select.isMultiple()) { throw new SeleniumLibraryNonFatalException(String.format("Options '%s' not in list '%s'.", Python.join(", ", nonExistingItems), locator)); } logging.warn(String.format("Option%s '%s' not found within list '%s'.", nonExistingItems.size() == 0 ? "" : "s", Python.join(", ", nonExistingItems), locator)); if (!lastItemFound) { throw new SeleniumLibraryNonFatalException(String.format("Option '%s' not in list '%s'.", nonExistingItems.get(nonExistingItems.size() - 1), locator)); } } }
Source:
public void testAddMenusWithExperimentalPerspective() { when(authzManager.authorize(any(MenuItem.class), any())).thenReturn(true); List<MenuItem> items = new ArrayList<>(); items.add(MenuFactory.newSimpleItem(NAME).perspective(PERSPECTIVE_ID).endMenu().build().getItems().get(0)); items.add(MenuFactory.newSimpleItem(NAME).perspective(SECOND_PERSPECTIVE_ID).endMenu().build().getItems().get(0)); items.add(MenuFactory.newSimpleItem(NAME).perspective(THIRD_PERSPECTIVE_ID).endMenu().build().getItems().get(0)); final Menus menus = MenuFactory.newSimpleItem(NAME).withItems(items).endMenu().build(); when(experimentalActivitiesAuthorizationManager.authorizeActivityId(anyString())) .thenAnswer((Answer<Boolean>) invocationOnMock -> !SECOND_PERSPECTIVE_ID.equals(invocationOnMock.getArguments()[0])); presenter.addMenus(menus); verify(experimentalActivitiesAuthorizationManager, times(3)).authorizeActivityId(anyString()); verify(view, times(2)).setMenuItemVisible(anyString(), eq(true)); verify(view, times(1)).setMenuItemVisible(anyString(), eq(false)); }

Target:
public void testAddMenusWithExperimentalPerspective() { when(authzManager.authorize(any(MenuItem.class), any())).thenReturn(true); List<MenuItem> items = new ArrayList<>(); items.add(MenuFactory.newSimpleItem(NAME).perspective(PERSPECTIVE_ID).endMenu().build().getItems().get(0)); items.add(MenuFactory.newSimpleItem(NAME).perspective(SECOND_PERSPECTIVE_ID).endMenu().build().getItems().get(0)); items.add(MenuFactory.newSimpleItem(NAME).perspective(THIRD_PERSPECTIVE_ID).endMenu().build().getItems().get(0)); final Menus menus = MenuFactory.newSimpleItem(NAME).withItems(items).endMenu().build(); when(experimentalActivitiesAuthorizationManager.authorizeActivityId(anyString())) .thenAnswer((Answer<Boolean>) invocationOnMock -> !SECOND_PERSPECTIVE_ID.equals(invocationOnMock.getArguments()[0])); presenter.addMenus(menus); verify(experimentalActivitiesAuthorizationManager, times(3)).authorizeActivityId(anyString()); verify(view, times(2)).setMenuItemVisible(anyString(), eq(true)); verify(view).setMenuItemVisible(anyString(), eq(false)); }
Source:
public Subscription subscribe() { return storIOSQLite .observeChangesInTable(UserTableMeta.TABLE) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Observer<Changes>() { @Override public void onError(Throwable e) { fail("Error occurred: " + e); } @Override public void onNext(Changes changes) { onNextObtained(changes); } @Override public void onCompleted() { } }); }

Target:
public Subscription subscribe() { return storIOSQLite .observeChangesInTable(UserTableMeta.TABLE) .subscribeOn(Schedulers.io()) .subscribe(new Action1<Changes>() { @Override public void call(Changes changes) { onNextObtained(changes); } }); }
Source:
private RexNode simplifyMinus(RexCall e) { int zeroIndex = findLiteralIndex(e.operands, 0L); if (zeroIndex == 1) { RexNode leftOperand = e.getOperands().get(0); return leftOperand.getType().equals(e.getType()) ? leftOperand : rexBuilder.makeCast(e.getType(), leftOperand); } return simplifyGenericNode(e); }

Target:
private RexNode simplifyMinus(RexCall e) { final int zeroIndex = findLiteralIndex(e.operands, BigDecimal.ZERO); if (zeroIndex == 1) { RexNode leftOperand = e.getOperands().get(0); return leftOperand.getType().equals(e.getType()) ? leftOperand : rexBuilder.makeCast(e.getType(), leftOperand); } return simplifyGenericNode(e); }
Source:
public HttpCallRequestBuilder request(final URI url, final RequestMethod method) { try { Assert.requireNonNull(url, "url"); Assert.requireNonNull(method, "method"); final HttpClientConnection clientConnection = new HttpClientConnection(httpURLConnectionFactory, url, method); return new HttpCallRequestBuilderImpl(clientConnection, gson, requestHandlers, responseHandlers, configuration); } catch (IOException e) { throw new DolphinRuntimeException("HTTP error", e); } }

Target:
public HttpCallRequestBuilder request(final URI url, final RequestMethod method) { try { Assert.requireNonNull(url, "url"); Assert.requireNonNull(method, "method"); final HttpClientConnection clientConnection = new HttpClientConnection(httpURLConnectionFactory, url, method); return new HttpCallRequestBuilderImpl(clientConnection, gson, requestHandlers, responseHandlers, configuration); } catch (final IOException e) { throw new DolphinRuntimeException("HTTP error", e); } }
Source:
public static SafeLoggableData fromTableMetadata(Map<TableReference, byte[]> tableRefToMetadata) { ImmutableSafeLoggableData.Builder builder = ImmutableSafeLoggableData.builder(); tableRefToMetadata.forEach( (ref, metadataBytes) -> { try { TableMetadata tableMetadata = TableMetadata.BYTES_HYDRATOR.hydrateFromBytes(metadataBytes); addLoggableNamesToBuilder(builder, ref, tableMetadata); } catch (Exception e) { log.warn("Exception thrown hydrating table metadata for table {}. {}", UnsafeArg.of("tableName", ref), UnsafeArg.of("exception", e)); } }); return builder.build(); }

Target:
public static SafeLoggableData fromTableMetadata(Map<TableReference, byte[]> tableRefToMetadata) { ImmutableSafeLoggableData.Builder builder = ImmutableSafeLoggableData.builder(); tableRefToMetadata.forEach( (ref, metadataBytes) -> { try { TableMetadata tableMetadata = TableMetadata.BYTES_HYDRATOR.hydrateFromBytes(metadataBytes); addLoggableNamesToBuilder(builder, ref, tableMetadata); } catch (Exception e) { log.warn("Exception thrown hydrating table metadata for table {}.", UnsafeArg.of("tableName", ref), e); } }); return builder.build(); }
Source:
static Participant getLeader(CuratorFramework client, Collection<String> participantNodes) throws Exception { Participant result = null; if ( participantNodes.size() > 0 ) { Iterator<String> iter = participantNodes.iterator(); while ( iter.hasNext() ) { try { result = participantForPath(client, iter.next(), true); } catch( KeeperException.NoNodeException e ) { } if ( result != null ) { break; } } } if( result == null ) { result = new Participant(); } return result; }

Target:
static Participant getLeader(CuratorFramework client, Collection<String> participantNodes) throws Exception { Participant result = null; if ( participantNodes.size() > 0 ) { Iterator<String> iter = participantNodes.iterator(); while ( iter.hasNext() ) { result = participantForPath(client, iter.next(), true); if ( result != null ) { break; } } } if( result == null ) { result = new Participant(); } return result; }
Source:
public boolean onOptionsItemSelected(final MenuItem item) { if (item.getItemId() == android.R.id.home) { if (mIsFeed) { Intent feedListIntent = ReaderActivityLauncher.getReaderFeedPreviewIntent(this, mBlogId); if (NavUtils.shouldUpRecreateTask(this, feedListIntent) || isTaskRoot()) { TaskStackBuilder.create(this) .addNextIntentWithParentStack(feedListIntent) .startActivities(); return true; } } onBackPressed(); return true; } return super.onOptionsItemSelected(item); }

Target:
public boolean onOptionsItemSelected(final MenuItem item) { if (item.getItemId() == android.R.id.home) { onBackPressed(); return true; } return super.onOptionsItemSelected(item); }
Source:
public void testWriteWithOldSchema() throws IOException { fsWriter = newWriter(testDirectory, SCHEMA); init(fsWriter); FileStatus[] stats = fs.listStatus(testDirectory, PathFilters.notHidden()); Assert.assertEquals("Should contain no visible files", 0, stats.length); stats = fs.listStatus(testDirectory); Assert.assertEquals("Should contain a hidden file", 1, stats.length); List<Record> written = Lists.newArrayList(); for (long i = 0; i < 10000; i += 1) { Record record = record(i, "test-" + i); fsWriter.write(record); written.add(record); } stats = fs.listStatus(testDirectory, PathFilters.notHidden()); Assert.assertEquals("Should contain no visible files", 0, stats.length); stats = fs.listStatus(testDirectory); Assert.assertEquals("Should contain a hidden file", 1, stats.length); fsWriter.close(); stats = fs.listStatus(testDirectory, PathFilters.notHidden()); Assert.assertEquals("Should contain a visible data file", 1, stats.length); DatasetReader<Record> reader = newReader(stats[0].getPath(), TEST_SCHEMA); Assert.assertEquals("Should match written records", written, Lists.newArrayList((Iterator) init(reader))); }

Target:
public void testWriteWithOldSchema() throws IOException { Schema writerSchema = SchemaBuilder.record("Message").fields() .requiredLong("id") .requiredString("message") .endRecord(); fsWriter = newWriter(testDirectory, TEST_SCHEMA, writerSchema); init(fsWriter); for (long i = 0; i < 1000; i += 1) { GenericRecordBuilder recordBuilder = new GenericRecordBuilder(TEST_SCHEMA) .set("id", i).set("message","test-"+ i); fsWriter.write(recordBuilder.build()); } fsWriter.close(); final FileStatus[] stats = fs.listStatus(testDirectory, PathFilters.notHidden()); Assert.assertEquals("Should match with writer schema", writerSchema, FileSystemUtil.schema("record", fs, stats[0].getPath())); }
Source:
public boolean conforms() { long max_dist = in().dimension(0) * in().dimension(0) + in().dimension(1) * in().dimension(1) + in().dimension(2) * in().dimension(2); System.out.println(max_dist); return ((in().numDimensions() == 3) && (max_dist <= Integer.MAX_VALUE)); }

Target:
public boolean conforms() { if (in().numDimensions() == 3) { long max_dist = in().dimension(0) * in().dimension(0) + in().dimension(1) * in().dimension(1) + in().dimension(2) * in().dimension(2); return ((in().numDimensions() == 3) && (max_dist <= Integer.MAX_VALUE)); } return false; }
Source:
public void removeSyncNotificationLatch(Cache<K, V> cache, K key, V value, CountDownLatch latch) { EventSource<K, V> eventSourceKey = new EventSource<K, V>(cache, key, value); Queue<CountDownLatch> latches = latchesByEventSource.get(eventSourceKey); if (latches == null) { return; } latches.remove(latch); if (latches.isEmpty()) { latchesByEventSource.remove(eventSourceKey, EMPTY_QUEUE); } }

Target:
public void removeSyncNotificationLatch(Cache<K, V> cache, K key, V value, CountDownLatch latch) { EventSource<K, V> eventSourceKey = new EventSource<K, V>(cache, key, value); Queue<CountDownLatch> latches = latchesByEventSource.get(eventSourceKey); if (latches == null) { return; } latchesByEventSource.compute(eventSourceKey, (kvEventSource, countDownLatches) -> { countDownLatches.remove(latch); return countDownLatches.isEmpty() ? null : countDownLatches; }); }
Source:
protected FileDescriptor connectToKernel() throws ErrnoException, SocketException { FileDescriptor fd = Os.socket(AF_NETLINK, SOCK_DGRAM | SOCK_CLOEXEC, NETLINK_INET_DIAG); Os.connect(fd, SocketUtils.makeNetlinkSocketAddress(0 , 0 )); return fd; }

Target:
protected FileDescriptor connectToKernel() throws ErrnoException, SocketException { final FileDescriptor fd = Os.socket(AF_NETLINK, SOCK_DGRAM | SOCK_CLOEXEC, NETLINK_INET_DIAG); Os.connect(fd, SocketUtils.makeNetlinkSocketAddress(0 , 0 )); return fd; }
Source:
public static String getDensityString(DisplayMetrics displayMetrics) { switch (displayMetrics.densityDpi) { case DisplayMetrics.DENSITY_LOW: return "ldpi"; case DisplayMetrics.DENSITY_MEDIUM: return "mdpi"; case DisplayMetrics.DENSITY_TV: return "tvdpi"; case DisplayMetrics.DENSITY_HIGH: return "hdpi"; case DisplayMetrics.DENSITY_280: return "xhdpi"; case DisplayMetrics.DENSITY_XHIGH: return "xhdpi"; case DisplayMetrics.DENSITY_360: return "xxhdpi"; case DisplayMetrics.DENSITY_400: return "xxhdpi"; case DisplayMetrics.DENSITY_420: return "xxhdpi"; case DisplayMetrics.DENSITY_XXHIGH: return "xxhdpi"; case DisplayMetrics.DENSITY_560: return "xxxhdpi"; case DisplayMetrics.DENSITY_XXXHIGH: return "xxxhdpi"; case DisplayMetrics.DENSITY_TV: return "tvdpi"; default: return "unknown"; } }

Target:
public static String getDensityString(DisplayMetrics displayMetrics) { switch (displayMetrics.densityDpi) { case DisplayMetrics.DENSITY_LOW: return "ldpi"; case DisplayMetrics.DENSITY_MEDIUM: return "mdpi"; case DisplayMetrics.DENSITY_TV: return "tvdpi"; case DisplayMetrics.DENSITY_HIGH: return "hdpi"; case DisplayMetrics.DENSITY_280: case DisplayMetrics.DENSITY_XHIGH: return "xhdpi"; case DisplayMetrics.DENSITY_360: case DisplayMetrics.DENSITY_400: case DisplayMetrics.DENSITY_420: case DisplayMetrics.DENSITY_XXHIGH: return "xxhdpi"; case DisplayMetrics.DENSITY_560: case DisplayMetrics.DENSITY_XXXHIGH: return "xxxhdpi"; default: return "unknown"; } }
Source:
public Completable asRxCompletable() { throwExceptionIfRxJavaIsNotAvailable("asRxCompetable()"); return Completable .create(OnSubscribeExecuteAsBlockingCompletable.newInstance(this)) .subscribeOn(Schedulers.io()); }

Target:
public Completable asRxCompletable() { throwExceptionIfRxJavaIsNotAvailable("asRxCompletable()"); return Completable .create(OnSubscribeExecuteAsBlockingCompletable.newInstance(this)) .subscribeOn(Schedulers.io()); }
Source:
BulkSlotProviderImpl( final SlotSelectionStrategy slotSelectionStrategy, final SlotPool slotPool, final PhysicalSlotRequestBulkChecker slotRequestBulkChecker) { this.slotSelectionStrategy = checkNotNull(slotSelectionStrategy); this.slotPool = checkNotNull(slotPool); this.slotRequestBulkChecker = slotRequestBulkChecker; }

Target:
public BulkSlotProviderImpl( final SlotSelectionStrategy slotSelectionStrategy, final SlotPool slotPool, final PhysicalSlotRequestBulkChecker slotRequestBulkChecker) { this.slotSelectionStrategy = checkNotNull(slotSelectionStrategy); this.slotPool = checkNotNull(slotPool); this.slotRequestBulkChecker = checkNotNull(slotRequestBulkChecker); }
Source:
public String openSession(SessionContext session) throws SqlExecutionException { return null; }

Target:
public String openSession(SessionContext session) throws SqlExecutionException { return session.getSessionId(); }
Source:
public void anAlarmNotificationIsReceivedFromAnUnknownDevice(final Map<String, String> settings) throws Throwable { try { final String deviceIdentification = getString(settings, PlatformKeys.KEY_DEVICE_IDENTIFICATION, PlatformDefaults.DEFAULT_DEVICE_IDENTIFICATION); SimulatePushedAlarmsHooks.simulateAlarm(deviceIdentification, new byte[] { 0x2C, 0x00, 0x00, 0x01, 0x02 }, this.serviceEndpoint.getAlarmNotificationsHost(), this.serviceEndpoint.getAlarmNotificationsPort()); SimulatePushedAlarmsHooks.simulateAlarm(deviceIdentification, new byte[] { 0x2C, 0x04, 0x20, 0x00, 0x00 }, this.serviceEndpoint.getAlarmNotificationsHost(), this.serviceEndpoint.getAlarmNotificationsPort()); } catch (final Exception e) { LOGGER.error("Error occured simulateAlarm: ", e); } }

Target:
public void anAlarmNotificationIsReceivedFromAnUnknownDevice(final Map<String, String> settings) throws Throwable { try { final String deviceIdentification = getString(settings, PlatformKeys.KEY_DEVICE_IDENTIFICATION, PlatformDefaults.DEFAULT_DEVICE_IDENTIFICATION); SimulatePushedAlarmsHooks.simulateAlarm(deviceIdentification, new byte[] { 0x2C, 0x00, 0x00, 0x01, 0x02 }, this.serviceEndpoint.getAlarmNotificationsHost(), this.serviceEndpoint.getAlarmNotificationsPort()); SimulatePushedAlarmsHooks.simulateAlarm(deviceIdentification, new byte[] { 0x2C, 0x04, 0x20, 0x00, 0x00 }, this.serviceEndpoint.getAlarmNotificationsHost(), this.serviceEndpoint.getAlarmNotificationsPort()); } catch (final Exception e) { LOGGER.error("Error occured simulating an alarm", e); } }
Source:
private boolean isValidRecord(boolean isBinary, boolean isPositive, ColumnConfig columnConfig) { if(isBinary) { return columnConfig != null && (columnConfig.isCategorical() || modelConfig.getBinningAlgorithm().equals(ModelStatsConf.BinningAlgorithm.DynamicBinning) || modelConfig.getBinningMethod().equals(BinningMethod.EqualTotal) || modelConfig.getBinningMethod().equals(BinningMethod.EqualInterval) || (modelConfig.getBinningMethod().equals(BinningMethod.EqualPositive) && isPositive) || (modelConfig.getBinningMethod().equals(BinningMethod.EqualNegtive) && !isPositive) || modelConfig.getBinningMethod().equals(BinningMethod.WeightTotal) || modelConfig.getBinningMethod().equals(BinningMethod.WeightInterval) || (modelConfig.getBinningMethod().equals(BinningMethod.WeightPositive) && isPositive) || (modelConfig.getBinningMethod().equals(BinningMethod.WeightNegative) && !isPositive)); } else { return columnConfig != null && ( columnConfig.isCategorical() || modelConfig.getBinningMethod().equals(BinningMethod.EqualTotal) || modelConfig.getBinningMethod().equals(BinningMethod.EqualInterval) || modelConfig.getBinningMethod().equals(BinningMethod.WeightTotal) || modelConfig.getBinningMethod().equals(BinningMethod.WeightInterval)); } }

Target:
private boolean isValidRecord(boolean isBinary, boolean isPositive, ColumnConfig columnConfig) { if(isBinary) { return columnConfig != null && (columnConfig.isCategorical() || isValidBinningMethodForBinary(isPositive)); } else { return columnConfig != null && (columnConfig.isCategorical() || isValidBinningMethod()); } }
Source:
public int hashCode() { final int prime = 31; int result = 1; result = (prime * result) + ((context == null) ? 0 : context.hashCode()); result = (prime * result) + ((fields == null) ? 0 : fields.hashCode()); result = (prime * result) + ((id == null) ? 0 : id.hashCode()); result = (prime * result) + ((name == null) ? 0 : name.hashCode()); result = (prime * result) + ((stream == null) ? 0 : stream.hashCode()); return result; }

Target:
public int hashCode() { final int prime = 31; int result = 1; result = (prime * result) + ((context == null) ? 0 : context.hashCode()); result = (prime * result) + ((fields == null) ? 0 : fields.hashCode()); result = (prime * result) + ((id == null) ? 0 : id.hashCode()); result = (prime * result) + ((name == null) ? 0 : name.hashCode()); result = (prime * result) + ((stream == null) ? 0 : stream.hashCode()); result = (prime * result) + ((customAttributes == null) ? 0 : customAttributes.hashCode()); return result; }
Source:
public static void setupTracingConfig() { List<String> descriptors = new ArrayList<>(); addDescriptor(descriptors, BigtableTableAdminGrpc.getServiceDescriptor()); addDescriptor(descriptors, BigtableGrpc.getServiceDescriptor()); boolean usingBigtableHBase = false; try { Class.forName("com.google.cloud.bigtable.hbase.BigtableTable"); usingBigtableHBase = true; } catch (ClassNotFoundException e) { } if (usingBigtableHBase) { descriptors.addAll(Arrays.asList( "BigtableTable.getTableDescriptor", "BigtableTable.exists", "BigtableTable.existsAll", "BigtableTable.batch", "BigtableTable.batchCallback", "BigtableTable.get", "BigtableTable.put", "BigtableTable.checkAndPut", "BigtableTable.delete", "BigtableTable.checkAndDelete", "BigtableTable.checkAndMutate", "BigtableTable.mutateRow", "BigtableTable.append", "BigtableTable.increment", "BigtableTable.incrementColumnValue" )); } Tracing.getExportComponent().getSampledSpanStore().registerSpanNamesForCollection(descriptors); Tracing.getTraceConfig().updateActiveTraceParams( TraceParams.DEFAULT.toBuilder().setSampler(Samplers.probabilitySampler(0.1)).build()); }

Target:
public static void setupTracingConfig() { List<String> descriptors = new ArrayList<>(); addDescriptor(descriptors, BigtableTableAdminGrpc.getServiceDescriptor()); addDescriptor(descriptors, BigtableGrpc.getServiceDescriptor()); Tracing.getExportComponent().getSampledSpanStore().registerSpanNamesForCollection(descriptors); }
Source:
public void getState_throwOnClosedSession() { SyncUser user = UserFactory.createUniqueUser(Constants.AUTH_URL); SyncConfiguration syncConfiguration = configFactory .createSyncConfigurationBuilder(user, Constants.SYNC_SERVER_URL) .waitForInitialRemoteData() .build(); Realm realm = Realm.getInstance(syncConfiguration); SyncSession session = SyncManager.getSession(syncConfiguration); realm.close(); user.logout(); thrown.expect(IllegalStateException.class); thrown.expectMessage("Could not find session, Realm was probably closed"); session.getState(); }

Target:
public void getState_throwOnClosedSession() { SyncUser user = UserFactory.createUniqueUser(Constants.AUTH_URL); SyncConfiguration syncConfiguration = configFactory .createSyncConfigurationBuilder(user, Constants.SYNC_SERVER_URL) .build(); Realm realm = Realm.getInstance(syncConfiguration); SyncSession session = SyncManager.getSession(syncConfiguration); realm.close(); user.logout(); thrown.expect(IllegalStateException.class); thrown.expectMessage("Could not find session, Realm was probably closed"); session.getState(); }
Source:
public List<Vo> getVosWhereUserIsAdmin(PerunSession sess, User user) throws InternalErrorException { try { return jdbc.query("select " + VosManagerImpl.voMappingSelectQuery + " from authz join vos on authz.vo_id=vos.id " + " left outer join groups_members on groups_members.group_id=authz.authorized_group_id " + " left outer join members on members.id=groups_members.member_id " + " where (authz.user_id=? or members.user_id=?) and authz.role_id=(select id from roles where name='voadmin')", VosManagerImpl.VO_MAPPER, user.getId(), user.getId()); } catch (EmptyResultDataAccessException e) { return new ArrayList<Vo>(); } catch (RuntimeException e) { throw new InternalErrorException(e); } }

Target:
public List<Vo> getVosWhereUserIsAdmin(PerunSession sess, User user) throws InternalErrorException { try { return jdbc.query("select " + VosManagerImpl.voMappingSelectQuery + " from authz join vos on authz.vo_id=vos.id " + " left outer join groups_members on groups_members.group_id=authz.authorized_group_id " + " left outer join members on members.id=groups_members.member_id " + " where (authz.user_id=? or members.user_id=?) and authz.role_id=(select id from roles where name=?)", VosManagerImpl.VO_MAPPER, user.getId(), user.getId(), Role.VOADMIN.getRoleName()); } catch (EmptyResultDataAccessException e) { return new ArrayList<Vo>(); } catch (RuntimeException e) { throw new InternalErrorException(e); } }