auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void setUp() throws Exception { Constant.getInstance(); I18N i18n = Mockito.mock(I18N.class, withSettings().lenient()); given(i18n.getString(anyString())).willReturn(""); given(i18n.getString(anyString(), any())).willReturn(""); given(i18n.getLocal()).willReturn(Locale.getDefault()); Constant.messages = i18n; type = new FormBasedAuthenticationMethodType(); method = Mockito.mock(AuthenticationMethod.class, Mockito.CALLS_REAL_METHODS); method.setAuthCheckingStrategy(AuthCheckingStrategy.POLL_URL); method.setPollFrequencyUnits(AuthPollFrequencyUnits.REQUESTS); method.setPollFrequency(5); method.setLoggedInIndicatorPattern(LOGGED_IN_INDICATOR); type = new FormBasedAuthenticationMethodType(); Mockito.when(method.getType()).thenReturn(type); mockedSessionManagementMethod = Mockito.mock(SessionManagementMethod.class); doNothing() .when(mockedSessionManagementMethod) .processMessageToMatchSession((HttpMessage) any(), (WebSession) any()); mockedContext = Mockito.mock(Context.class); when(mockedContext.getSessionManagementMethod()).thenReturn(mockedSessionManagementMethod); this.startServer(); }

Target:
public void setUp() throws Exception { WithConfigsTest.setUpConstant(); type = new FormBasedAuthenticationMethodType(); method = type.createAuthenticationMethod(1); method.setAuthCheckingStrategy(AuthCheckingStrategy.POLL_URL); method.setPollFrequencyUnits(AuthPollFrequencyUnits.REQUESTS); method.setPollFrequency(5); method.setLoggedInIndicatorPattern(LOGGED_IN_INDICATOR); mockedSessionManagementMethod = Mockito.mock(SessionManagementMethod.class); doNothing() .when(mockedSessionManagementMethod) .processMessageToMatchSession((HttpMessage) any(), (WebSession) any()); mockedContext = Mockito.mock(Context.class); when(mockedContext.getSessionManagementMethod()).thenReturn(mockedSessionManagementMethod); this.startServer(); }
Source:
private <T> T uncachedValue(Class<?> cls) throws BinaryObjectException { assert cls != null; GridBinaryMarshaller.USE_CACHE.set(Boolean.FALSE); if (ord >= 0) { Object[] vals = cls.getEnumConstants(); if (ord < vals.length) return (T)vals[ord]; else throw new BinaryObjectException("Failed to get enum value for ordinal (do you have correct class " + "version?) [cls=" + cls.getName() + ", ordinal=" + ord + ", totalValues=" + vals.length + ']'); } else return null; }

Target:
private <T> T uncachedValue(Class<?> cls) throws BinaryObjectException { assert cls != null; assert !GridBinaryMarshaller.USE_CACHE.get(); if (ord >= 0) { Object[] vals = cls.getEnumConstants(); if (ord < vals.length) return (T)vals[ord]; else throw new BinaryObjectException("Failed to get enum value for ordinal (do you have correct class " + "version?) [cls=" + cls.getName() + ", ordinal=" + ord + ", totalValues=" + vals.length + ']'); } else return null; }
Source:
@Test public void unableToConnectWrongPort() { configureSSHSlaveLauncher(sshd.ipBound(22), 1234).pwdCredentials("test", "test"); slave.save(); elasticSleep(3000); verifyLog("Connection refused"); }

Target:
@Test public void unableToConnectWrongPort() { configureSSHSlaveLauncher(sshd.ipBound(22), 1234).pwdCredentials("test", "test"); slave.save(); waitForLogMessage("Connection refused"); }
Source:
protected boolean canDoAction() { boolean retValue = false; String event; if (getVds() == null) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_HOST_NOT_EXIST); return false; } if (getParameters().getAction() == FenceActionType.Start) { event = AuditLogType.USER_VDS_STOP.name(); } else { event = AuditLogType.USER_VDS_START.name(); } if (getVds().getpm_enabled() && isPowerManagementLegal()) { Date waitTo = Backend.getInstance() .getStartedAt() .addSeconds((Integer) Config.getValue(ConfigValues.DisableFenceAtStartupInSec)); Date now = new Date(); if (waitTo.before(now) || waitTo.equals(now)) { int secondsLeftToNextPmOp = (isInternalExecution() || (getParameters().getParentCommand() == VdcActionType.RestartVds)) ? 0 : DbFacade.getInstance() .getAuditLogDao() .getTimeToWaitForNextPmOp(getVds().getName(), event); if (secondsLeftToNextPmOp <= 0) { if (createFenceExecutor().isProxyHostAvailable()) { retValue = true; } else { addCanDoActionMessage(VdcBllMessages.VDS_NO_VDS_PROXY_FOUND); } } else { addCanDoActionMessage(VdcBllMessages.VDS_FENCE_DISABLED_AT_QUIET_TIME); addCanDoActionMessage(String.format("$seconds %1$s", secondsLeftToNextPmOp)); } } else { addCanDoActionMessage(VdcBllMessages.VDS_FENCE_DISABLED_AT_SYSTEM_STARTUP_INTERVAL); } } if (!retValue) { handleError(); } else { addCanDoActionMessage(VdcBllMessages.VDS_FENCE_DISABLED); handleError(); } getReturnValue().setSucceeded(retValue); return retValue; }

Target:
protected boolean canDoAction() { boolean retValue = false; String event; if (getVds() == null) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_HOST_NOT_EXIST); return false; } if (getParameters().getAction() == FenceActionType.Start) { event = AuditLogType.USER_VDS_STOP.name(); } else { event = AuditLogType.USER_VDS_START.name(); } if (getVds().getpm_enabled() && isPowerManagementLegal()) { Date waitTo = Backend.getInstance() .getStartedAt() .addSeconds((Integer) Config.getValue(ConfigValues.DisableFenceAtStartupInSec)); Date now = new Date(); if (waitTo.before(now) || waitTo.equals(now)) { int secondsLeftToNextPmOp = (isInternalExecution() || (getParameters().getParentCommand() == VdcActionType.RestartVds)) ? 0 : DbFacade.getInstance() .getAuditLogDao() .getTimeToWaitForNextPmOp(getVds().getName(), event); if (secondsLeftToNextPmOp <= 0) { if (createProxyHostLocator().isProxyHostAvailable()) { retValue = true; } else { addCanDoActionMessage(VdcBllMessages.VDS_NO_VDS_PROXY_FOUND); } } else { addCanDoActionMessage(VdcBllMessages.VDS_FENCE_DISABLED_AT_QUIET_TIME); addCanDoActionMessage(String.format("$seconds %1$s", secondsLeftToNextPmOp)); } } else { addCanDoActionMessage(VdcBllMessages.VDS_FENCE_DISABLED_AT_SYSTEM_STARTUP_INTERVAL); } } if (!retValue) { handleError(); } else { addCanDoActionMessage(VdcBllMessages.VDS_FENCE_DISABLED); handleError(); } getReturnValue().setSucceeded(retValue); return retValue; }
Source:
private static void saveIssue(SensorContext context, Flake8ReportReader.Issue issue, Set<String> unresolvedInputFiles) { InputFile inputFile = context.fileSystem().inputFile(context.fileSystem().predicates().hasPath(issue.filePath)); if (inputFile == null) { unresolvedInputFiles.add(issue.filePath); return; } NewExternalIssue newExternalIssue = context.newExternalIssue(); newExternalIssue .type(RuleType.CODE_SMELL) .severity(Severity.MAJOR) .remediationEffortMinutes(DEFAULT_CONSTANT_DEBT_MINUTES); NewIssueLocation primaryLocation = newExternalIssue.newLocation() .message(issue.message) .on(inputFile); primaryLocation.at(inputFile.selectLine(issue.lineNumber)); newExternalIssue.at(primaryLocation); newExternalIssue.engineId(LINTER_KEY).ruleId(issue.ruleKey); newExternalIssue.save(); }

Target:
private static void saveIssue(SensorContext context, Flake8ReportReader.Issue issue, Set<String> unresolvedInputFiles) { InputFile inputFile = context.fileSystem().inputFile(context.fileSystem().predicates().hasPath(issue.filePath)); if (inputFile == null) { unresolvedInputFiles.add(issue.filePath); return; } NewExternalIssue newExternalIssue = context.newExternalIssue(); newExternalIssue .type(RuleType.CODE_SMELL) .severity(Severity.MAJOR) .remediationEffortMinutes(DEFAULT_CONSTANT_DEBT_MINUTES); NewIssueLocation primaryLocation = newExternalIssue.newLocation() .message(issue.message) .on(inputFile); if (issue.columnNumber != null && issue.columnNumber < inputFile.selectLine(issue.lineNumber).end().lineOffset() + 1) { inputFile.selectLine(issue.lineNumber).end().lineOffset(); primaryLocation.at(inputFile.newRange(issue.lineNumber, issue.columnNumber - 1, issue.lineNumber, issue.columnNumber)); } else { primaryLocation.at(inputFile.selectLine(issue.lineNumber)); } newExternalIssue.at(primaryLocation); newExternalIssue.engineId(LINTER_KEY).ruleId(issue.ruleKey); newExternalIssue.save(); }
Source:
public void testWithParallelism() throws Exception { tEnv().executeSql("create table print_t (" + "f0 int," + "f1 double" + ") with (" + "'connector' = 'print'," + "'print-identifier' = 'test_print'," + "'sink.parallelism' = '2'," + "'standard-error'='false')"); DataType type = tEnv().from("print_t").getSchema().toRowDataType(); Row row = Row.of(1, 1.1); tEnv().fromValues(type, Arrays.asList(row)).executeInsert("print_t").await(); String expectedLine1 = "test_print:1> +I(" + "1," + "1.1" + ")"; String expectedLine2 = "test_print:2> +I(" + "1," + "1.1" + ")"; Assert.assertTrue(arrayOutputStream.toString().equals(expectedLine1 + "\n") || arrayOutputStream.toString().equals(expectedLine2 + "\n")); }

Target:
public void testWithParallelism() throws Exception { tEnv().executeSql("create table print_t (" + "f0 int," + "f1 double" + ") with (" + "'connector' = 'print'," + "'print-identifier' = 'test_print'," + "'sink.parallelism' = '2'," + "'standard-error'='false')"); DataType type = tEnv().from("print_t").getSchema().toRowDataType(); Row row = Row.of(1, 1.1); tEnv().fromValues(type, Collections.singleton(row)).executeInsert("print_t").await(); String expectedLine1 = "test_print:1> +I(" + "1," + "1.1" + ")"; String expectedLine2 = "test_print:2> +I(" + "1," + "1.1" + ")"; Assert.assertTrue(arrayOutputStream.toString().equals(expectedLine1 + "\n") || arrayOutputStream.toString().equals(expectedLine2 + "\n")); }
Source:
public List<ConnectionSlot> acquireConnectionSlots(final String client, final String eventType, final List<String> partitions) throws NoConnectionSlotsException, ServiceUnavailableException { final List<Optional<ConnectionSlot>> slots = new ArrayList<>(); try { for (final String partition : partitions) { Optional<ConnectionSlot> connectionSlot = Optional.empty(); try { connectionSlot = executeWithRetry( () -> acquireConnectionSlot(client, eventType, partition), new RetryForSpecifiedCountStrategy<Optional<ConnectionSlot>>(5) .withExceptionsThatForceRetry(ConnectionSlotOccupiedException.class) .withWaitBetweenEachTry(0L, 100L)); } catch (ConnectionSlotOccupiedException e) { LOG.info(format("Failed to capture consuming connection slot after 5 tries for client '{0}', " + "event-type '{1}', partition {2}", client, eventType, partition)); } slots.add(connectionSlot); } if (slots.stream().allMatch(Optional::isPresent)) { return slots.stream() .map(Optional::get) .collect(Collectors.toList()); } else { final String failedPartitions = partitions.stream() .filter(p -> !slots.stream().anyMatch(s -> s.isPresent() && s.get().getPartition().equals(p))) .collect(Collectors.joining(", ")); final String msg = format(ERROR_MSG, eventType, failedPartitions, maxConnections); throw new NoConnectionSlotsException(msg); } } catch (final Exception e) { slots.stream() .filter(Optional::isPresent) .map(Optional::get) .forEach(this::releaseConnectionSlot); if (e instanceof NoConnectionSlotsException) { throw e; } else { throw new ServiceUnavailableException("Error communicating with zookeeper", e); } } }

Target:
public List<ConnectionSlot> acquireConnectionSlots(final String client, final String eventType, final List<String> partitions) throws NoConnectionSlotsException, ServiceUnavailableException { final List<String> partitionsWithNoFreeSlots = getPartitionsWithNoFreeSlots(client, eventType, partitions); if (partitionsWithNoFreeSlots.size() == 0) { final List<ConnectionSlot> slots = new ArrayList<>(); final String lockZkPath = format("{0}/{1}|{2}", LOCKS_ZK_PATH, client, eventType); try { return runLocked(() -> { final List<String> occupiedPartitions = getPartitionsWithNoFreeSlots(client, eventType, partitions); if (occupiedPartitions.size() > 0) { throw generateNoConnectionSlotsException(eventType, partitionsWithNoFreeSlots); } for (final String partition : partitions) { final ConnectionSlot connectionSlot = acquireConnectionSlot(client, eventType, partition); slots.add(connectionSlot); } return slots; }, zkLockFactory.createLock(lockZkPath)); } catch (final NoConnectionSlotsException e) { throw e; } catch (final Exception e) { slots.forEach(this::releaseConnectionSlot); throw new ServiceUnavailableException("Error communicating with zookeeper", e); } } else { throw generateNoConnectionSlotsException(eventType, partitionsWithNoFreeSlots); } }
Source:
public void testRetainAll() throws Exception { intSet.add(1); intSet.add(4); intSet.add(7); assertEquals(3, intSet.size()); IntSet intSet2 = new SmallIntSet(); intSet2.add(4); intSet2.add(5); intSet2.add(7); intSet.retainAll(intSet2); assertEquals(2, intSet.size()); assertTrue(intSet.contains(4)); assertTrue(intSet.contains(7)); }

Target:
public void testRetainAll() throws Exception { intSet.add(1); intSet.add(4); intSet.add(7); assertEquals(3, intSet.size()); IntSet intSet2 = new SmallIntSet(); intSet2.add(4); intSet2.add(5); intSet2.add(7); intSet.retainAll(intSet2); assertEquals(CollectionFactory.makeSet(4, 7), intSet); }
Source:
private Builder() { try { this.configDirectory = Files.createTempDirectory("ccm"); } catch (IOException e) { throw new RuntimeException(e); } withCassandraConfiguration("auto_snapshot", "false"); if (this.configDirectory != null) { this.configDirectory.toFile().deleteOnExit(); } }

Target:
private Builder() { try { this.configDirectory = Files.createTempDirectory("ccm"); this.configDirectory.toFile().deleteOnExit(); } catch (IOException e) { throw new RuntimeException(e); } withCassandraConfiguration("auto_snapshot", "false"); }
Source:
public void process(final K key, final Change<V1> change) { if (key == null) { LOG.warn( "Skipping record due to null key. change=[{}] topic=[{}] partition=[{}] offset=[{}]", change, context().topic(), context().partition(), context().offset() ); metrics.skippedRecordsSensor().record(); return; } final R newValue; final long resultTimestamp; R oldValue = null; final ValueAndTimestamp<V2> valueAndTimestampLeft = valueGetter.get(key); final V2 valueLeft = getValueOrNull(valueAndTimestampLeft); if (valueLeft == null) { return; } if (change.newValue != null) { resultTimestamp = Math.max(context().timestamp(), valueAndTimestampLeft.timestamp()); } else { resultTimestamp = valueAndTimestampLeft.timestamp(); } newValue = joiner.apply(change.newValue, valueLeft); if (sendOldValues) { oldValue = joiner.apply(change.oldValue, valueLeft); } context().forward(key, new Change<>(newValue, oldValue), To.all().withTimestamp(resultTimestamp)); }

Target:
public void process(final K key, final Change<V1> change) { if (key == null) { LOG.warn( "Skipping record due to null key. change=[{}] topic=[{}] partition=[{}] offset=[{}]", change, context().topic(), context().partition(), context().offset() ); metrics.skippedRecordsSensor().record(); return; } final R newValue; final long resultTimestamp; R oldValue = null; final ValueAndTimestamp<V2> valueAndTimestampLeft = valueGetter.get(key); final V2 valueLeft = getValueOrNull(valueAndTimestampLeft); if (valueLeft == null) { return; } resultTimestamp = Math.max(context().timestamp(), valueAndTimestampLeft.timestamp()); newValue = joiner.apply(change.newValue, valueLeft); if (sendOldValues) { oldValue = joiner.apply(change.oldValue, valueLeft); } context().forward(key, new Change<>(newValue, oldValue), To.all().withTimestamp(resultTimestamp)); }
Source:
private void loadNodeMap() { this.nodeMap = new HashMap<>(); for (Node n : this.getAllNodes()) { this.nodeMap.put(n.getNodeName(), n); } LOGGER.info("We currently have nodes assigned to this Jenkins instance, which we will check", this.nodeMap.size()); }

Target:
private Map<String, Node> loadNodeMap() { Map<String, Node> nodeMap = new HashMap<>(); for (Node n : getAllNodes()) { nodeMap.put(n.getNodeName(), n); } LOGGER.info("We currently have nodes assigned to this Jenkins instance, which we will check", nodeMap.size()); return nodeMap; }
Source:
public List<TaskDetails> getJobTasksById(@PathParam("cluster") String cluster, @PathParam("jobId") String jobId) throws IOException { LOG.info("Fetching tasks info for jobId=" + jobId); serializationContext.set(new SerializationContext( SerializationContext.DetailLevel.EVERYTHING)); JobDetails jobDetails = getJobHistoryService().getJobByJobID(cluster, jobId, true); return jobDetails.getTasks(); }

Target:
public List<TaskDetails> getJobTasksById(@PathParam("cluster") String cluster, @PathParam("jobId") String jobId) throws IOException { LOG.info("Fetching tasks info for jobId=" + jobId); Stopwatch timer = new Stopwatch().start(); serializationContext.set(new SerializationContext( SerializationContext.DetailLevel.EVERYTHING)); JobDetails jobDetails = getJobHistoryService().getJobByJobID(cluster, jobId, true); timer.stop(); List<TaskDetails> tasks = jobDetails.getTasks(); if(tasks != null && !tasks.isEmpty()) { LOG.info("For endpoint /tasks/" + cluster + "/" + jobId + ", fetched " + tasks.size() + " tasks, spent time " + timer); } else { LOG.info("For endpoint /tasks/" + cluster + "/" + jobId + ", found no tasks, spent time " + timer); } return tasks; }
Source:
private double[] createDoubleArrayFromINDArray(@Nonnull final INDArray x) { final double[] xDoubleArray = new double[fftSize]; for (int i = 0; i < dimension; i++) { xDoubleArray[i] = x.getDouble(i); } return xDoubleArray; }

Target:
private double[] createDoubleArrayFromINDArray(@Nonnull final INDArray x) { return zeroPad(new IndexRange(0, getDimension()).mapToDouble(x::getDouble)); }
Source:
public synchronized ServerTemplate update(ServerTemplate serverTemplate) { delete(serverTemplate.getId()); store(serverTemplate); return serverTemplate; }

Target:
public ServerTemplate update(ServerTemplate serverTemplate) { synchronized (store) { delete(serverTemplate.getId()); store(serverTemplate); } return serverTemplate; }
Source:
SendThread(ClientCnxnSocket clientCnxnSocket) { super(makeThreadName("-SendThread()")); try { changeZkState(States.CONNECTING); } catch (IOException e) { throw new RuntimeException("Connection setup failed when migrate state to CONNECTING"); } this.clientCnxnSocket = clientCnxnSocket; setDaemon(true); }

Target:
SendThread(ClientCnxnSocket clientCnxnSocket) throws IOException { super(makeThreadName("-SendThread()")); changeZkState(States.CONNECTING); this.clientCnxnSocket = clientCnxnSocket; setDaemon(true); }
Source:
public void testJWTAuthShouldFailWithoutToken() { String defaultExpectedErrorMessage = messages.getMessage(UNAUTHORIZED_MESSAGE_CODE, Locale.ENGLISH); String expectedErrorMessage = messages.getMessage(UNAUTHORIZED_MESSAGE_CODE, defaultExpectedErrorMessage); String utf8ExpectedErrorMessage = new String(expectedErrorMessage.getBytes(ISO_8859_1), UTF_8); String url = getContextBaseUrl() + "/users"; given().header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE) .when() .get(url) .then() .statusCode(HttpStatus.UNAUTHORIZED.value()) .body("error", equalTo(utf8ExpectedErrorMessage)); }

Target:
public void testJWTAuthShouldFailWithoutToken() { String defaultErrorMessage = messages.getMessage(UNAUTHORIZED_MESSAGE_CODE, Locale.ENGLISH); String errorMessage = messages.getMessage(UNAUTHORIZED_MESSAGE_CODE, defaultErrorMessage); String decodedErrorMessage = new String(errorMessage.getBytes(ISO_8859_1), Charset.defaultCharset()); String url = getContextBaseUrl() + "/users"; given().header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE) .when() .get(url) .then() .statusCode(HttpStatus.UNAUTHORIZED.value()) .body("error", equalTo(decodedErrorMessage)); }
Source:
protected void fireEvent(CoreSession session, String eventId, Collection<DocumentRef> refs) { EventService eventService = Framework.getService(EventService.class); DocumentModelList docs = session.getDocuments(refs.toArray(new DocumentRef[refs.size()])); docs.forEach(d -> { DocumentEventContext ctx = new DocumentEventContext(session, session.getPrincipal(), d); ctx.setCategory(DocumentEventCategories.EVENT_DOCUMENT_CATEGORY); ctx.setProperty(CoreEventConstants.REPOSITORY_NAME, session.getRepositoryName()); ctx.setProperty(CoreEventConstants.SESSION_ID, session.getSessionId()); Event event = ctx.newEvent(eventId); event.setInline(false); event.setImmediate(false); eventService.fireEvent(event); }); }

Target:
protected void fireEvent(CoreSession session, String eventId, Collection<DocumentRef> refs) { EventService eventService = Framework.getService(EventService.class); DocumentModelList docs = session.getDocuments(refs.toArray(new DocumentRef[0])); docs.forEach(d -> { DocumentEventContext ctx = new DocumentEventContext(session, session.getPrincipal(), d); ctx.setCategory(DocumentEventCategories.EVENT_DOCUMENT_CATEGORY); ctx.setProperty(CoreEventConstants.REPOSITORY_NAME, session.getRepositoryName()); ctx.setProperty(CoreEventConstants.SESSION_ID, session.getSessionId()); Event event = ctx.newEvent(eventId); event.setInline(false); event.setImmediate(false); eventService.fireEvent(event); }); }
Source:
public boolean areEqual(MapObject o1, MapObject o2) { if (o1 == null ^ o2 == null) { return false; } else if (o1 == o2) { return true; } else { return o1.id.equals(o2.id); } }

Target:
public boolean areEqual(MapObject o1, MapObject o2) { if (o1 == null) { return o2 == null; } else { return o1.id.equals(o2.id); } }
Source:
public void testSegmentMetadataHolderNumRows() { Map<DataSegment, SegmentMetadataHolder> segmentsMetadata = schema.getSegmentMetadata(); Set<DataSegment> segments = segmentsMetadata.keySet(); Assert.assertEquals(segments.size(), 3); DataSegment existingSegment = segments.stream().findFirst().orElse(null); Assert.assertFalse(existingSegment == null); SegmentMetadataHolder existingHolder = segmentsMetadata.get(existingSegment); SegmentMetadataHolder updatedHolder = SegmentMetadataHolder.from(existingHolder).withNumRows(5).build(); schema.setSegmentMetadataHolder(existingSegment, updatedHolder); ImmutableDruidServer server = null; for (ImmutableDruidServer druidServer : druidServers) { for (DataSegment segment : druidServer.getSegments()) { if (segment == existingSegment) { server = druidServer; } } } Assert.assertFalse(server == null); final DruidServerMetadata druidServerMetadata = server.getMetadata(); schema.addSegment(druidServerMetadata, existingSegment); segmentsMetadata = schema.getSegmentMetadata(); existingSegment = segments.stream().findFirst().orElse(null); final SegmentMetadataHolder currentHolder = segmentsMetadata.get(existingSegment); Assert.assertEquals(updatedHolder.getNumRows(), currentHolder.getNumRows()); }

Target:
public void testSegmentMetadataHolderNumRows() { Map<DataSegment, SegmentMetadataHolder> segmentsMetadata = schema.getSegmentMetadata(); final Set<DataSegment> segments = segmentsMetadata.keySet(); Assert.assertEquals(3, segments.size()); final DataSegment existingSegment = segments.stream() .filter(segment -> segment.getDataSource().equals("foo2")) .findFirst() .orElse(null); Assert.assertNotNull(existingSegment); final SegmentMetadataHolder existingHolder = segmentsMetadata.get(existingSegment); SegmentMetadataHolder updatedHolder = SegmentMetadataHolder.from(existingHolder).withNumRows(5).build(); schema.setSegmentMetadataHolder(existingSegment, updatedHolder); final Pair<ImmutableDruidServer, DataSegment> pair = druidServers.stream() .flatMap(druidServer -> druidServer.getSegments() .stream() .filter(segment -> segment .equals( existingSegment)) .map(segment -> Pair .of( druidServer, segment ))) .findAny() .orElse(null); Assert.assertNotNull(pair); final ImmutableDruidServer server = pair.lhs; Assert.assertNotNull(server); final DruidServerMetadata druidServerMetadata = server.getMetadata(); schema.addSegment(druidServerMetadata, existingSegment); segmentsMetadata = schema.getSegmentMetadata(); final DataSegment currentSegment = segments.stream() .filter(segment -> segment.getDataSource().equals("foo2")) .findFirst() .orElse(null); final SegmentMetadataHolder currentHolder = segmentsMetadata.get(currentSegment); Assert.assertEquals(updatedHolder.getSegmentId(), currentHolder.getSegmentId()); Assert.assertEquals(updatedHolder.getNumRows(), currentHolder.getNumRows()); Assert.assertEquals(updatedHolder.getNumReplicas(), currentHolder.getNumReplicas()); Assert.assertEquals(updatedHolder.isAvailable(), currentHolder.isAvailable()); Assert.assertEquals(updatedHolder.isPublished(), currentHolder.isPublished()); }
Source:
public void handleResponse(AbstractResponse response) { TxnOffsetCommitResponse txnOffsetCommitResponse = (TxnOffsetCommitResponse) response; boolean coordinatorReloaded = false; Map<TopicPartition, Errors> errors = txnOffsetCommitResponse.errors(); log.debug("Received TxnOffsetCommit response for consumer group {}: {}", builder.data.groupId(), errors); for (Map.Entry<TopicPartition, Errors> entry : errors.entrySet()) { TopicPartition topicPartition = entry.getKey(); Errors error = entry.getValue(); if (error == Errors.NONE) { pendingTxnOffsetCommits.remove(topicPartition); } else if (error == Errors.COORDINATOR_NOT_AVAILABLE || error == Errors.NOT_COORDINATOR || error == Errors.REQUEST_TIMED_OUT) { if (!coordinatorReloaded) { coordinatorReloaded = true; lookupCoordinator(FindCoordinatorRequest.CoordinatorType.GROUP, builder.data.groupId()); } } else if (error == Errors.UNKNOWN_TOPIC_OR_PARTITION || error == Errors.COORDINATOR_LOAD_IN_PROGRESS || error == Errors.UNKNOWN_MEMBER_ID) { continue; } else if (error == Errors.GROUP_AUTHORIZATION_FAILED) { abortableError(GroupAuthorizationException.forGroupId(builder.data.groupId())); break; } else if (isFatalException(error)) { fatalError(error.exception()); break; } else { fatalError(new KafkaException("Unexpected error in TxnOffsetCommitResponse: " + error.message())); break; } } if (result.isCompleted()) { pendingTxnOffsetCommits.clear(); } else if (pendingTxnOffsetCommits.isEmpty()) { result.done(); } else { reenqueue(); } }

Target:
public void handleResponse(AbstractResponse response) { TxnOffsetCommitResponse txnOffsetCommitResponse = (TxnOffsetCommitResponse) response; boolean coordinatorReloaded = false; Map<TopicPartition, Errors> errors = txnOffsetCommitResponse.errors(); log.debug("Received TxnOffsetCommit response for consumer group {}: {}", builder.data.groupId(), errors); for (Map.Entry<TopicPartition, Errors> entry : errors.entrySet()) { TopicPartition topicPartition = entry.getKey(); Errors error = entry.getValue(); if (error == Errors.NONE) { pendingTxnOffsetCommits.remove(topicPartition); } else if (error == Errors.COORDINATOR_NOT_AVAILABLE || error == Errors.NOT_COORDINATOR || error == Errors.REQUEST_TIMED_OUT) { if (!coordinatorReloaded) { coordinatorReloaded = true; lookupCoordinator(FindCoordinatorRequest.CoordinatorType.GROUP, builder.data.groupId()); } } else if (error == Errors.UNKNOWN_TOPIC_OR_PARTITION || error == Errors.COORDINATOR_LOAD_IN_PROGRESS) { continue; } else if (error == Errors.GROUP_AUTHORIZATION_FAILED) { abortableError(GroupAuthorizationException.forGroupId(builder.data.groupId())); break; } else if (error == Errors.TRANSACTIONAL_ID_AUTHORIZATION_FAILED || error == Errors.INVALID_PRODUCER_EPOCH || error == Errors.UNSUPPORTED_FOR_MESSAGE_FORMAT) { fatalError(error.exception()); break; } else { fatalError(new KafkaException("Unexpected error in TxnOffsetCommitResponse: " + error.message())); break; } } if (result.isCompleted()) { pendingTxnOffsetCommits.clear(); } else if (pendingTxnOffsetCommits.isEmpty()) { result.done(); } else { reenqueue(); } }
Source:
protected Module wrapPluginSink( final Key<? extends PluginSink> input, final Key<PluginSink> output ) { return new PrivateModule() { @Override protected void configure() { Key<PluginSink> sinkKey = (Key<PluginSink>) input; if (flushInterval.isPresent() || BatchedPluginSink.class.isAssignableFrom( sinkKey.getTypeLiteral().getRawType())) { final Key<PluginSink> nextKey = Key.get(PluginSink.class, Names.named("flushing")); install(new OutputDelegatingModule<>(sinkKey, nextKey, new FlushingPluginSink(flushInterval.get()))); sinkKey = nextKey; } if (filter.isPresent()) { final Key<PluginSink> next = Key.get(PluginSink.class, Names.named("filtered")); install(new OutputDelegatingModule<>(sinkKey, next, new FilteringPluginSink(filter.get()))); sinkKey = next; } bind(output).to(sinkKey); expose(output); } }; }

Target:
protected Module wrapPluginSink( final Key<? extends PluginSink> input, final Key<PluginSink> output ) { return new PrivateModule() { @Override protected void configure() { Key<PluginSink> sinkKey = (Key<PluginSink>) input; if (flushInterval != null && flushInterval.isPresent() && BatchedPluginSink.class.isAssignableFrom( sinkKey.getTypeLiteral().getRawType())) { final Key<PluginSink> flushingKey = Key.get(PluginSink.class, Names.named("flushing")); install(new OutputDelegatingModule<>(sinkKey, flushingKey, new FlushingPluginSink(flushInterval.get()))); sinkKey = flushingKey; } if (filter != null && filter.isPresent()) { final Key<PluginSink> filteringKey = Key.get(PluginSink.class, Names.named("filtered")); install(new OutputDelegatingModule<>(sinkKey, filteringKey, new FilteringPluginSink(filter.get()))); sinkKey = filteringKey; } bind(output).to(sinkKey); expose(output); } }; }
Source:
private List<Variant> regionWsHelper(String testRegion, HttpStatus status) { String url = "/v2/regions/" + testRegion + "?species=mmusculus&assembly=grcm38"; ResponseEntity<String> response = restTemplate.getForEntity(url, String.class); assertEquals(status, response.getStatusCode()); Configuration configuration = Configuration.defaultConfiguration() .jsonProvider(new JacksonJsonProvider()) .mappingProvider(new JacksonMappingProvider(objectMapper)) .addOptions(Option.SUPPRESS_EXCEPTIONS); List<Variant> variantList = JsonPath.using(configuration).parse(response.getBody()) .read("$['_embedded']['variantList']", new TypeRef<List<Variant>>() { }); return variantList; }

Target:
private List<Variant> regionWsHelper(String testRegion, HttpStatus status) { String url = "/v2/regions/" + testRegion + "/variants?species=mmusculus&assembly=grcm38"; ResponseEntity<String> response = restTemplate.getForEntity(url, String.class); assertEquals(status, response.getStatusCode()); Configuration configuration = Configuration.defaultConfiguration() .jsonProvider(new JacksonJsonProvider()) .mappingProvider(new JacksonMappingProvider(objectMapper)) .addOptions(Option.SUPPRESS_EXCEPTIONS); List<Variant> variantList = JsonPath.using(configuration).parse(response.getBody()) .read("$['_embedded']['variantList']", new TypeRef<List<Variant>>() { }); return variantList; }
Source:
protected void releaseMonitorLock(EngineLock monitoringLock, String commandName) { final VDS vds = getVds(); getLockManager().releaseLock(monitoringLock); log.infoFormat(commandName + " finished. Lock released. Monitoring can run now for host {0} from data-center {1}", vds.getName(), vds.getStoragePoolName()); }

Target:
protected void releaseMonitorLock(EngineLock monitoringLock, String commandName) { getLockManager().releaseLock(monitoringLock); final VDS vds = getVds(); log.infoFormat(commandName + " finished. Lock released. Monitoring can run now for host {0} from data-center {1}", vds.getName(), vds.getStoragePoolName()); }
Source:
public void run() { long startTime; long lastTime; try { while (isOpen.get()) { startTime = time.milliseconds(); lastTime = startTime; List<RequestInfo> requestInfoList = pollForRequests(); routerMetrics.operationControllerPollforRequestTimeMs.update(time.milliseconds() - lastTime); lastTime = time.milliseconds(); List<ResponseInfo> responseInfoList = networkClient.sendAndPoll(requestInfoList); routerMetrics.numOfRequestInfosPerPoll.update(requestInfoList.size()); routerMetrics.operationControllerSendAndPollTimeMs.update(time.milliseconds() - lastTime); lastTime = time.milliseconds(); onResponse(responseInfoList); routerMetrics.operationControllerProcessResponseTimeMs.update(time.milliseconds() - lastTime); routerMetrics.operationControllerOnePollCycleTimeMs.update(time.milliseconds() - startTime); } } catch (Throwable e) { logger.error("Aborting, as requestResponseHandlerThread received an unexpected error: ", e); } finally { networkClient.close(); shutDownLatch.countDown(); shutDownOperationControllers(); } }

Target:
public void run() { try { while (isOpen.get()) { List<RequestInfo> requestInfoList = pollForRequests(); List<ResponseInfo> responseInfoList = networkClient.sendAndPoll(requestInfoList); onResponse(responseInfoList); } } catch (Throwable e) { logger.error("Aborting, as requestResponseHandlerThread received an unexpected error: ", e); } finally { networkClient.close(); shutDownLatch.countDown(); shutDownOperationControllers(); } }
Source:
public boolean isUserOnChat() { try { wait.forElementVisible(chatInlineAlert); return chatInlineAlert.isDisplayed(); } catch (Exception e) { return false; } }

Target:
public boolean isUserOnChat() { try { wait.forElementVisible(chatInlineAlert); return true; } catch (Exception e) { return false; } }
Source:
public String getNiogitRepoPath(org.uberfire.java.nio.file.Path path) { try { final File directory = path.toFile(); return directory.toURI().toString(); } catch (ClassCastException cce) { throw new IllegalArgumentException("Cannot get .niogit directory for non-jgit path.", cce); } }

Target:
public String getNiogitRepoPath(org.uberfire.java.nio.file.Path path) { try { Path p = path.getFileSystem().getPath(path.toString()); final File directory = p.toFile(); return directory.toURI().toString(); } catch (ClassCastException cce) { throw new IllegalArgumentException("Cannot get .niogit directory for non-jgit path.", cce); } }
Source:
public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Appointment)) return false; Appointment that = (Appointment) o; if (durationTime != that.durationTime) return false; if (startTime != that.startTime) return false; if (!applicantId.equals(that.applicantId)) return false; if (!userIdList.equals(that.userIdList)) return false; return true; }

Target:
public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Appointment)) return false; Appointment that = (Appointment) o; if (actualStartTime != that.actualStartTime) return false; if (durationTime != that.durationTime) return false; if (startTime != that.startTime) return false; if (applicantId != null ? !applicantId.equals(that.applicantId) : that.applicantId != null) return false; if (appointmentId != null ? !appointmentId.equals(that.appointmentId) : that.appointmentId != null) return false; if (groupId != null ? !groupId.equals(that.groupId) : that.groupId != null) return false; if (userIdList != null ? !userIdList.equals(that.userIdList) : that.userIdList != null) return false; return true; }
Source:
public void testCacheLoaderWriterOverriding() { MutableConfiguration<Long, Product> conf = new MutableConfiguration<Long, Product>(); conf.setTypes(Long.class, Product.class); javax.cache.Cache<Long, Product> c1 = cm.createCache("productCache", conf); ProductCacheLoaderWriter.written.clear(); c1.put(1L, new Product(1L)); assertThat(ProductCacheLoaderWriter.written.isEmpty(), is(true)); cm.destroyCache("productCache"); conf.setReadThrough(true); c1 = cm.createCache("productCache", conf); c1.put(1L, new Product(1L)); assertThat(ProductCacheLoaderWriter.written.isEmpty(), is(false)); cm.destroyCache("productCache"); ProductCacheLoaderWriter.written.clear(); conf.setReadThrough(false); conf.setWriteThrough(true); c1 = cm.createCache("productCache", conf); c1.put(1L, new Product(1L)); assertThat(ProductCacheLoaderWriter.written.isEmpty(), is(false)); ProductCacheLoaderWriter.written.clear(); cm.destroyCache("productCache"); }

Target:
public void testCacheLoaderWriterOverriding() { javax.cache.Cache<Long, Product> c1 = cm.createCache("productCache", createProductCacheConf()); ProductCacheLoaderWriter.written.clear(); c1.put(1L, new Product(1L)); assertThat(ProductCacheLoaderWriter.written.isEmpty(), is(true)); cm.destroyCache("productCache"); MutableConfiguration conf = createProductCacheConf(); conf.setReadThrough(true); c1 = cm.createCache("productCache", conf); c1.put(1L, new Product(1L)); assertThat(ProductCacheLoaderWriter.written.isEmpty(), is(false)); cm.destroyCache("productCache"); conf = createProductCacheConf(); ProductCacheLoaderWriter.written.clear(); conf.setReadThrough(false); conf.setWriteThrough(true); c1 = cm.createCache("productCache", conf); c1.put(1L, new Product(1L)); assertThat(ProductCacheLoaderWriter.written.isEmpty(), is(false)); ProductCacheLoaderWriter.written.clear(); cm.destroyCache("productCache"); try { conf = createProductCacheConf(); conf.setReadThrough(true); cm.createCache("p1", conf); fail("Cache creation should have failed for illegal cache loader/writer configuration"); } catch (MultiCacheException e) { assertThat(e.getThrowables().get(0).getMessage(), is(equalTo("Unable to construct (read/write)through cache without either a templated loader/writer or configured loader/writer"))); } }
Source:
protected void onActivityResult(int requestCode, int resultCode, Intent intent) { if (requestCode == RC_SIGN_IN) { mSignInClicked = false; mResolvingConnectionFailure = false; if (resultCode == RESULT_OK) { mGoogleApiClient.connect(); } else { BaseGameUtils.showActivityResultError(this, requestCode, resultCode, R.string.signin_failure, R.string.signin_other_error); } } }

Target:
protected void onActivityResult(int requestCode, int resultCode, Intent intent) { super.onActivityResult(requestCode, resultCode, intent); if (requestCode == RC_SIGN_IN) { mSignInClicked = false; mResolvingConnectionFailure = false; if (resultCode == RESULT_OK) { mGoogleApiClient.connect(); } else { BaseGameUtils.showActivityResultError(this, requestCode, resultCode, R.string.signin_failure, R.string.signin_other_error); } } }
Source:
Optional<DecisionNavigatorItem> findItem(final Node<View, Edge> node) { return getItems() .stream() .filter(item -> item.getUUID().equals(node.getUUID())) .findFirst(); }

Target:
Optional<DecisionNavigatorItem> findItem(final Node<View, Edge> node) { return getItems() .stream() .filter(item -> Objects.equals(item.getUUID(), node.getUUID())) .findFirst(); }
Source:
public void validTest() throws Exception { String mimetype = "text/plain"; String checksumPrefix = "urn:sha1:"; String checksum = "61673dacf6c6eea104e77b151584ed7215388ea3"; File file = new File(binaryBase + "/61/67/3d/" + checksum); file.getParentFile().mkdirs(); file.createNewFile(); Model model = ModelFactory.createDefaultModel(); Resource resc = model.createResource(RESC_ID); resc.addProperty(RDF.type, Fcrepo4Repository.Binary); resc.addProperty(Ebucore.hasMimeType, mimetype); resc.addProperty(Premis.hasMessageDigest, checksumPrefix + checksum); setMessageBody(model); processor.process(exchange); verify(message).setHeader(CdrBinaryChecksum, checksum); verify(message).setHeader(CdrBinaryMimeType, mimetype); verify(message).setHeader(CdrBinaryPath, file.getAbsolutePath()); verify(message).setHeader(CdrBinarySubPath, idToPath(RESC_ID, HASHED_PATH_DEPTH, HASHED_PATH_SIZE)); }

Target:
public void validTest() throws Exception { String mimetype = "text/plain"; String checksumPrefix = "urn:sha1:"; String checksum = "61673dacf6c6eea104e77b151584ed7215388ea3"; File file = new File(binaryBase + "/61/67/3d/" + checksum); file.getParentFile().mkdirs(); file.createNewFile(); Model model = ModelFactory.createDefaultModel(); Resource resc = model.createResource(RESC_ID); resc.addProperty(RDF.type, Fcrepo4Repository.Binary); resc.addProperty(Ebucore.hasMimeType, mimetype); resc.addProperty(Premis.hasMessageDigest, checksumPrefix + checksum); setMessageBody(model); processor.process(exchange); verify(message).setHeader(CdrBinaryChecksum, checksum); verify(message).setHeader(CdrBinaryMimeType, mimetype); verify(message).setHeader(CdrBinaryPath, file.getAbsolutePath()); }
Source:
public void closesExplicitlyAllParts() throws IOException { final String body = "RqMultipartTest.closesExplicitlyAllParts"; final RqMultipart request = new RqMultipart.Fake( new RqFake(), new RqGreedy( new RqWithHeaders( new RqFake("", "", body), RqMultipartTest.contentLengthHeader( (long) body.getBytes().length ), RqMultipartTest.contentDispositionHeader( "form-data; name=\"foo\"" ) ) ), new RqGreedy( new RqWithHeaders( new RqFake("", "", body), RqMultipartTest.contentLengthHeader(0L), RqMultipartTest.contentDispositionHeader( "form-data; name=\"bar\"; filename=\"a.bin\"" ) ) ) ); final RqMultipart.Base multi = new RqMultipart.Base(request); multi.body().close(); MatcherAssert.assertThat( multi.part("foo").iterator().next(), Matchers.notNullValue() ); multi.part("foo").iterator().next().body().close(); MatcherAssert.assertThat( multi.part("bar").iterator().next(), Matchers.notNullValue() ); multi.part("bar").iterator().next().body().close(); }

Target:
public void closesExplicitlyAllParts() throws Exception { final String body = "RqMultipartTest.closesExplicitlyAllParts"; final RqMultipart request = new RqMultipart.Fake( new RqFake(), new RqGreedy( new RqWithHeaders( new RqFake("", "", body), RqMultipartTest.contentLengthHeader( (long) body.getBytes().length ), RqMultipartTest.contentDispositionHeader( "form-data; name=\"foo\"" ) ) ), new RqGreedy( new RqWithHeaders( new RqFake("", "", body), RqMultipartTest.contentLengthHeader(0L), RqMultipartTest.contentDispositionHeader( "form-data; name=\"bar\"; filename=\"a.bin\"" ) ) ) ); final RqMultipart.Base multi = new RqMultipart.Base(request); multi.body().close(); MatcherAssert.assertThat( multi.part("foo").iterator().next(), Matchers.notNullValue() ); multi.part("foo").iterator().next().body().close(); MatcherAssert.assertThat( multi.part("bar").iterator().next(), Matchers.notNullValue() ); multi.part("bar").iterator().next().body().close(); }
Source:
public Object get(DataFetchingEnvironment env) { Object source = env.getSource(); if (source == null) return null; try { if (isBooleanProperty(env.getFieldType())) { try { return getProperty(source, "is"); } catch (NoSuchMethodException e) { return getProperty(source, "get"); } } else { return getProperty(source, "get"); } } catch (NoSuchMethodException e) { return null; } }

Target:
public Object get(DataFetchingEnvironment env) { Object source = env.getSource(); if (source == null) return null; try { return getProperty(source); } catch (NoSuchMethodException e) { return null; } }
Source:
public void testDeployChildOnParentUndeploy() throws Exception { class ParentVerticle extends AbstractVerticle { @Override public void stop(Promise<Void> stopPromise) { vertx.deployVerticle(ChildVerticle.class.getName()) .<Void>mapEmpty() .setHandler(stopPromise); } } CountDownLatch latch = new CountDownLatch(1); vertx.deployVerticle(new ParentVerticle(), ar1 -> { assertTrue(ar1.succeeded()); vertx.undeploy(ar1.result(), ar2 -> { assertFalse(ar2.succeeded()); latch.countDown(); }); }); awaitLatch(latch); }

Target:
public void testDeployChildOnParentUndeploy() { class ParentVerticle extends AbstractVerticle { @Override public void stop(Promise<Void> stopPromise) { vertx.deployVerticle(ChildVerticle.class.getName()) .<Void>mapEmpty() .setHandler(stopPromise); } } vertx.deployVerticle(new ParentVerticle(), onSuccess(id -> vertx.undeploy(id, onFailure(u -> testComplete())))); await(); }
Source:
public SAMLocusAndReference next() { final LocusInfo locus = locusIterator.next(); final ReferenceSequence referenceSequence = referenceSequenceFileWalker.get(locus.getSequenceIndex(), locus.getSequenceName(), locus.getSequenceLength()); final int position = locus.getPosition(); final byte referenceBase = 0 == position ? (byte)'N' : referenceSequence.getBases()[locus.getPosition() - 1]; return new SAMLocusAndReference(locus, referenceBase); }

Target:
public SAMLocusAndReference next() { final LocusInfo locus = locusIterator.next(); final ReferenceSequence referenceSequence = referenceSequenceFileWalker.get(locus.getSequenceIndex(), locus.getSequenceName(), locus.getSequenceLength()); if (locus.getPosition() == 0) { return new SAMLocusAndReference(locus, BASE_BEFORE_REFERENCE_START); } else { return new SAMLocusAndReference(locus, referenceSequence.getBases()[locus.getPosition() - 1]); } }
Source:
private Observer<List<Location>> getLocationList() { return new Observer<List<Location>>() { @Override public void onCompleted() { showLocationDialog(locationList); } @Override public void onError(Throwable e) { e.printStackTrace(); } @Override public void onNext(List<Location> locations) { for (Location locationItem : locations) { locationList.add(locationItem.getName()); } } }; }

Target:
private Observer<List<Location>> getLocationList() { return new Observer<List<Location>>() { @Override public void onCompleted() { showLocationDialog(locationList); } @Override public void onError(Throwable e) { mOpenMRSLogger.e(e.getMessage()); } @Override public void onNext(List<Location> locations) { for (Location locationItem : locations) { locationList.add(locationItem.getName()); } } }; }
Source:
private List<VmTemplate> getTemplatesForUpdate(List<Guid> templatesIds) { if (templatesIds.isEmpty()) { return Collections.emptyList(); } List<Guid> idsToProcess = getIdsToProcess(templatesIds); List<VmTemplate> toReturn = new ArrayList<VmTemplate>(); List<VmTemplate> templates = getVmTemplateDao().getVmTemplatesByIds(idsToProcess); for (VmTemplate template : templates) { if (VmTemplateStatus.Locked != template.getstatus()) { VmTemplateHandler.UpdateDisksFromDb(template); long currentDbGeneration = getVmAndTemplatesGenerationsDAO().getDbGeneration(template.getId()); if (template.getDb_generation() == currentDbGeneration) { boolean verifyDisksNotLocked = verifyDisksNotLocked(template.getDiskList()); if (verifyDisksNotLocked) { toReturn.add(template); } } } } return toReturn; }

Target:
private List<VmTemplate> getTemplatesForUpdate(List<Guid> templatesIds) { if (templatesIds.isEmpty()) { return Collections.emptyList(); } List<Guid> idsToProcess = getIdsToProcess(templatesIds); List<VmTemplate> toReturn = new LinkedList<VmTemplate>(); List<VmTemplate> templates = getVmTemplateDao().getVmTemplatesByIds(idsToProcess); for (VmTemplate template : templates) { if (VmTemplateStatus.Locked != template.getstatus()) { VmTemplateHandler.UpdateDisksFromDb(template); boolean verifyDisksNotLocked = verifyDisksNotLocked(template.getDiskList()); if (verifyDisksNotLocked) { Long currentDbGeneration = getVmAndTemplatesGenerationsDAO().getDbGeneration(template.getId()); if (template.getDb_generation() == currentDbGeneration) { toReturn.add(template); } } } } return toReturn; }
Source:
public void testGetRangeOfTimestampsOmitsTimestampsLessThanMax() { keyValueService.put(TEST_TABLE, ImmutableMap.of( Cell.create(row0, column0), value0_t0), TEST_TIMESTAMP); keyValueService.put(TEST_TABLE, ImmutableMap.of( Cell.create(row0, column0), value0_t1), TEST_TIMESTAMP + 10); RangeRequest range = RangeRequest.all().withBatchHint(1); List<RowResult<Set<Long>>> results = ImmutableList.copyOf( keyValueService.getRangeOfTimestamps(TEST_TABLE, range, TEST_TIMESTAMP + 1)); assertEquals(1, results.size()); assertArrayEquals(row0, results.get(0).getRowName()); assertEquals(TEST_TIMESTAMP, (long)results.get(0).getOnlyColumnValue().iterator().next()); }

Target:
public void testGetRangeOfTimestampsOmitsTimestampsLessThanMax() { keyValueService.put(TEST_TABLE, ImmutableMap.of( Cell.create(row0, column0), value0_t0), TEST_TIMESTAMP); keyValueService.put(TEST_TABLE, ImmutableMap.of( Cell.create(row0, column0), value0_t1), TEST_TIMESTAMP + 10); RangeRequest range = RangeRequest.all().withBatchHint(2); List<RowResult<Set<Long>>> results = ImmutableList.copyOf( keyValueService.getRangeOfTimestamps(TEST_TABLE, range, TEST_TIMESTAMP + 1)); assertEquals(1, results.size()); assertArrayEquals(row0, results.get(0).getRowName()); assertEquals(TEST_TIMESTAMP, (long) results.get(0).getOnlyColumnValue().iterator().next()); }