auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void updateTopic(TopicName topicName, PatchData patch, String modifiedBy) { groupService.checkGroupExists(topicName.getGroupName()); Topic retrieved = getTopicDetails(topicName); Topic modified = Patch.apply(retrieved, patch); topicValidator.ensureUpdatedTopicIsValid(modified, retrieved); if (!retrieved.equals(modified)) { Instant beforeMigrationInstant = clock.instant(); if (retrieved.getRetentionTime() != modified.getRetentionTime()) { multiDCAwareService.manageTopic(brokerTopicManagement -> brokerTopicManagement.updateTopic(modified) ); } topicRepository.updateTopic(modified); if (!retrieved.wasMigratedFromJsonType() && modified.wasMigratedFromJsonType()) { logger.info("Waiting until all subscriptions have consumers assigned during topic content type migration...", topicName.qualifiedName()); topicContentTypeMigrationService.waitUntilAllSubscriptionsHasConsumersAssigned(modified, Duration.ofSeconds(topicProperties.getCheckTopicSubscriptionsAssignmentCompletedTimeoutSeconds())); logger.info("Notifying subscriptions' consumers about changes in topic content type...", topicName.qualifiedName()); topicContentTypeMigrationService.notifySubscriptions(modified, beforeMigrationInstant); } auditor.objectUpdated(modifiedBy, retrieved, modified); topicOwnerCache.onUpdatedTopic(retrieved, modified); } }

Target:
public void updateTopic(TopicName topicName, PatchData patch, String modifiedBy) { groupService.checkGroupExists(topicName.getGroupName()); Topic retrieved = getTopicDetails(topicName); Topic modified = Patch.apply(retrieved, patch); topicValidator.ensureUpdatedTopicIsValid(modified, retrieved); if (!retrieved.equals(modified)) { Instant beforeMigrationInstant = clock.instant(); if (retrieved.getRetentionTime() != modified.getRetentionTime()) { multiDCAwareService.manageTopic(brokerTopicManagement -> brokerTopicManagement.updateTopic(modified) ); } topicRepository.updateTopic(modified); if (!retrieved.wasMigratedFromJsonType() && modified.wasMigratedFromJsonType()) { logger.info("Waiting until all subscriptions have consumers assigned during topic content type migration...", topicName.qualifiedName()); topicContentTypeMigrationService.waitUntilAllSubscriptionsHasConsumersAssigned(modified, Duration.ofSeconds(topicProperties.getSubscriptionsAssignmentsCompletedTimeoutSeconds())); logger.info("Notifying subscriptions' consumers about changes in topic content type...", topicName.qualifiedName()); topicContentTypeMigrationService.notifySubscriptions(modified, beforeMigrationInstant); } auditor.objectUpdated(modifiedBy, retrieved, modified); topicOwnerCache.onUpdatedTopic(retrieved, modified); } }
Source:
private static List<IProject> getSelectedProjects(ISelection selection) { List<IProject> projectSelection = new ArrayList<>(); if (selection instanceof IStructuredSelection) { for (Object element : ((StructuredSelection) selection).toList()) { if (element instanceof AutomationSystem) { projectSelection.add(((AutomationSystem) element).getProject()); } } } return projectSelection; }

Target:
private static List<IProject> getSelectedProjects(ISelection selection) { List<IProject> projectSelection = new ArrayList<>(); if (selection instanceof IStructuredSelection) { for (Object element : ((StructuredSelection) selection).toList()) { if (element instanceof AutomationSystem) { projectSelection.add(((AutomationSystem) element).getProject()); } else if (element instanceof IProject) { projectSelection.add((IProject) element); } } } return projectSelection; }
Source:
public Firehose connect(StringInputRowParser stringInputRowParser) throws IOException { Preconditions.checkNotNull(azureStorage, "null azureStorage"); final LinkedList<AzureBlob> objectQueue = Lists.newLinkedList(blobs); return new FileIteratingFirehose( new Iterator<LineIterator>() { @Override public boolean hasNext() { return !objectQueue.isEmpty(); } @Override public LineIterator next() { final AzureBlob nextURI = objectQueue.poll(); final String container = nextURI.getContainer(); final String path = nextURI.getPath().startsWith("/") ? nextURI.getPath().substring(1) : nextURI.getPath(); try { final InputStream innerInputStream = new AzureByteSource(azureStorage, container, path).openStream(); final InputStream outerInputStream = path.endsWith(".gz") ? CompressionUtils.gzipInputStream(innerInputStream) : innerInputStream; return IOUtils.lineIterator( new BufferedReader( new InputStreamReader(outerInputStream, Charsets.UTF_8) ) ); } catch (Exception e) { log.error(e, "Exception reading from container[%s] blob[%s]", container, path ); throw Throwables.propagate(e); } } @Override public void remove() { throw new UnsupportedOperationException(); } }, stringInputRowParser ); }

Target:
public Firehose connect(StringInputRowParser stringInputRowParser) throws IOException { Preconditions.checkNotNull(azureStorage, "null azureStorage"); final LinkedList<AzureBlob> objectQueue = Lists.newLinkedList(blobs); return new FileIteratingFirehose( new Iterator<LineIterator>() { @Override public boolean hasNext() { return !objectQueue.isEmpty(); } @Override public LineIterator next() { final AzureBlob nextURI = objectQueue.poll(); final String container = nextURI.getContainer(); final String path = nextURI.getPath().startsWith("/") ? nextURI.getPath().substring(1) : nextURI.getPath(); try { final InputStream innerInputStream = new AzureByteSource(azureStorage, container, path).openStream(); final InputStream outerInputStream = path.endsWith(".gz") ? CompressionUtils.gzipInputStream(innerInputStream) : innerInputStream; return IOUtils.lineIterator( new BufferedReader( new InputStreamReader(outerInputStream, Charsets.UTF_8) ) ); } catch (Exception e) { log.error(e, "Exception opening container[%s] blob[%s]", container, path ); throw Throwables.propagate(e); } } @Override public void remove() { throw new UnsupportedOperationException(); } }, stringInputRowParser ); }
Source:
public void whenStreamWrongPartitionsThenUnprocessableEntity() throws IOException { final String et = createEventType().getName(); final Subscription s = createSubscriptionForEventType(et); final String body = "{\"partitions\":[" + "{\"event_type\":\"" + et + "\",\"partition\":\"0\"}," + "{\"event_type\":\"dummy-et-123\",\"partition\":\"0\"}," + "{\"event_type\":\"dummy-et-123\",\"partition\":\"1\"}]}"; given().body(body) .contentType(JSON) .when() .post("/subscriptions/{sid}/events", s.getId()) .then() .statusCode(HttpStatus.SC_UNPROCESSABLE_ENTITY) .body(JSON_HELPER.matchesObject(Problem.valueOf( MoreStatus.UNPROCESSABLE_ENTITY, "Wrong partitions specified - some partitions don't belong to subscription: " + "EventTypePartition{eventType='dummy-et-123', partition='0'}, " + "EventTypePartition{eventType='dummy-et-123', partition='1'}"))); }

Target:
public void whenStreamWrongPartitionsThenUnprocessableEntity() throws IOException { final String et = createEventType().getName(); final Subscription s = createSubscriptionForEventType(et); final String body = "{\"partitions\":[" + "{\"event_type\":\"" + et + "\",\"partition\":\"0\"}," + "{\"event_type\":\"" + et + "\",\"partition\":\"1\"}," + "{\"event_type\":\"dummy-et-123\",\"partition\":\"0\"}]}"; given().body(body) .contentType(JSON) .when() .post("/subscriptions/{sid}/events", s.getId()) .then() .statusCode(HttpStatus.SC_UNPROCESSABLE_ENTITY) .body(JSON_HELPER.matchesObject(Problem.valueOf( MoreStatus.UNPROCESSABLE_ENTITY, "Wrong partitions specified - some partitions don't belong to subscription: " + "EventTypePartition{eventType='" + et + "', partition='1'}, " + "EventTypePartition{eventType='dummy-et-123', partition='0'}"))); }
Source:
private boolean isAwake(final long startMillis, final long endMillis){ if(endMillis - startMillis > MINIMUM_AWAKE_LENGTH_MILLIS){ return true; } double maxVote = 0; for(int i = 0; i < this.votes.size(); i++){ final Pair<Long, Double> vote = this.votes.get(i); if(vote.fst >= startMillis && vote.fst <= endMillis && vote.snd > maxVote){ maxVote = vote.snd; } } if(maxVote >= 3){ return true; } return false; }

Target:
private boolean isAwake(final long startMillis, final long endMillis){ if(endMillis - startMillis > MINIMUM_AWAKE_LENGTH_MILLIS){ return true; } double maxVote = 0; for(int i = 0; i < this.votes.size(); i++){ final Pair<Long, Double> vote = this.votes.get(i); if(vote.fst >= startMillis && vote.fst <= endMillis && vote.snd > maxVote){ maxVote = vote.snd; } } if(maxVote >= MIN_VOTE_FOR_AWAKE){ return true; } return false; }
Source:
public AuthenticationContext(final String authority, final boolean validateAuthority, final ExecutorService service) throws MalformedURLException { if (StringHelper.isBlank(authority)) { throw new IllegalArgumentException("authority is null or empty"); } if (service == null) { throw new IllegalArgumentException("service is null"); } this.service = service; this.validateAuthority = validateAuthority; this.authority = this.canonicalizeUri(authority); this.proxy = Proxy.NO_PROXY; authenticationAuthority = new AuthenticationAuthority(new URL( this.getAuthority()), this.shouldValidateAuthority()); }

Target:
public AuthenticationContext(final String authority, final boolean validateAuthority, final ExecutorService service) throws MalformedURLException { if (StringHelper.isBlank(authority)) { throw new IllegalArgumentException("authority is null or empty"); } if (service == null) { throw new IllegalArgumentException("service is null"); } this.service = service; this.validateAuthority = validateAuthority; this.authority = this.canonicalizeUri(authority); authenticationAuthority = new AuthenticationAuthority(new URL( this.getAuthority()), this.shouldValidateAuthority()); }
Source:
public HttpLogOptions setApplicationId(final String applicationId) { if (applicationId != null && (applicationId.length() > MAX_APPLICATION_ID_LENGTH || applicationId.contains(" "))) { if (applicationId.contains(" ")) { throw logger .logExceptionAsError(new IllegalArgumentException("'applicationId' must not contain a space.")); } else { throw logger .logExceptionAsError(new IllegalArgumentException("'applicationId' length cannot be greater than " + MAX_APPLICATION_ID_LENGTH)); } } else { this.applicationId = applicationId; } return this; }

Target:
public HttpLogOptions setApplicationId(final String applicationId) { if (!CoreUtils.isNullOrEmpty(applicationId)) { if (applicationId.length() > MAX_APPLICATION_ID_LENGTH) { throw logger .logExceptionAsError(new IllegalArgumentException("'applicationId' length cannot be greater than " + MAX_APPLICATION_ID_LENGTH)); } else if (applicationId.contains(" ")) { throw logger .logExceptionAsError(new IllegalArgumentException("'applicationId' must not contain a space.")); } else { this.applicationId = applicationId; } } return this; }
Source:
public void setUp() throws Exception { super.setUp(); diskWithSnapshots = createDiskImage(); snapshotsList = createSnapshotsForDiskImage(diskWithSnapshots.getId()); diskWithoutSnapshots = createDiskImage(); ovfImage = createDiskImage(); ovfImage.setContentType(DiskContentType.OVF_STORE); cinderDisk = createCinderDisk(); lunDisk = createLunDisk(); setUpDaoMocks(); }

Target:
public void setUp() throws Exception { super.setUp(); diskWithSnapshots = createDiskImage(null); snapshotsList = createSnapshotsForDiskImage(diskWithSnapshots.getId()); diskWithoutSnapshots = createDiskImage(null); ovfImage = createDiskImage(null); ovfImage.setContentType(DiskContentType.OVF_STORE); cinderDisk = createCinderDisk(); lunDisk = createLunDisk(); setUpImagesHandlerMocks(); }
Source:
public void copyTo(final TemplateOptions to) { super.copyTo(to); if (to instanceof AzureComputeTemplateOptions) { final AzureComputeTemplateOptions eTo = AzureComputeTemplateOptions.class.cast(to); if (virtualNetworkName.isPresent()) { eTo.virtualNetworkName(virtualNetworkName.get()); } if (addressSpaceAddressPrefix.isPresent()) { eTo.addressSpaceAddressPrefix(addressSpaceAddressPrefix.get()); } if (subnetName.isPresent()) { eTo.subnetName(subnetName.get()); } if (networkSecurityGroupName.isPresent()) { eTo.subnetName(networkSecurityGroupName.get()); } if (subnetAddressPrefix.isPresent()) { eTo.subnetAddressPrefix(subnetAddressPrefix.get()); } if (storageAccountName.isPresent()) { eTo.storageAccountName(storageAccountName.get()); } if (storageAccountType.isPresent()) { eTo.storageAccountType(storageAccountType.get()); } final LoginCredentials credentials = new LoginCredentials.Builder(). user(loginUser). password(loginPassword == null || !loginPassword.isPresent() ? null : loginPassword.get()). privateKey(loginPrivateKey == null || !loginPrivateKey.isPresent() ? null : loginPrivateKey.get()). authenticateSudo(authenticateSudo == null ? false : authenticateSudo). build(); eTo.overrideLoginCredentials(credentials); } }

Target:
public void copyTo(final TemplateOptions to) { super.copyTo(to); if (to instanceof AzureComputeTemplateOptions) { final AzureComputeTemplateOptions eTo = AzureComputeTemplateOptions.class.cast(to); if (virtualNetworkName.isPresent()) { eTo.virtualNetworkName(virtualNetworkName.get()); } if (addressSpaceAddressPrefix.isPresent()) { eTo.addressSpaceAddressPrefix(addressSpaceAddressPrefix.get()); } if (subnetName.isPresent()) { eTo.subnetName(subnetName.get()); } if (networkSecurityGroupName.isPresent()) { eTo.subnetName(networkSecurityGroupName.get()); } if (subnetAddressPrefix.isPresent()) { eTo.subnetAddressPrefix(subnetAddressPrefix.get()); } if (storageAccountName.isPresent()) { eTo.storageAccountName(storageAccountName.get()); } if (storageAccountType.isPresent()) { eTo.storageAccountType(storageAccountType.get()); } } }
Source:
public void requestResetPassword() { mockHealthCodeAndAccountRetrieval(); participantService.requestResetPassword(STUDY, ID); verify(accountDao).requestResetPassword(accountIdCaptor.capture()); AccountId accountId = accountIdCaptor.getValue(); assertEquals(STUDY.getIdentifier(), accountId.getStudyId()); assertEquals(ID, accountId.getId()); }

Target:
public void requestResetPassword() { mockHealthCodeAndAccountRetrieval(); participantService.requestResetPassword(STUDY, ID); verify(accountDao).requestResetPassword(eq(STUDY), eq(ACCOUNT_ID)); }
Source:
public static boolean checkIfPinEntry(){ if ((System.currentTimeMillis() - timestamp) > 10000 && (System.currentTimeMillis() - lastStart) > 10000){ SharedPreferences appPrefs = PreferenceManager.getDefaultSharedPreferences(MainApp.getAppContext()); if (appPrefs.getBoolean("set_pincode", false)) { lastStart = System.currentTimeMillis(); return true; } } return false; }

Target:
public static boolean checkIfPinEntry(){ if ((System.currentTimeMillis() - timestamp) > PINCODE_TIMEOUT && (System.currentTimeMillis() - lastStart) > PINCODE_TIMEOUT){ SharedPreferences appPrefs = PreferenceManager.getDefaultSharedPreferences(MainApp.getAppContext()); if (appPrefs.getBoolean("set_pincode", false)) { lastStart = System.currentTimeMillis(); return true; } } return false; }
Source:
public static void init() { if (initialized) { return; } initialized = true; DebugOptions.DEV_ROOT_PATH = "engine/src/main/resources/"; final LwjglApplication application = new LwjglApplication(new SolApplication(new ModuleManager())); try { Thread.sleep(10000L); } catch (InterruptedException e) { e.printStackTrace(); } game = ((SolApplication) application.getApplicationListener()).getGame(); }

Target:
public static void init() { if (initialized) { return; } initialized = true; DebugOptions.DEV_ROOT_PATH = "engine/src/main/resources/"; ModuleManager moduleManager = new ModuleManager(); GL20 mockGL = new MockGL(); Gdx.gl = mockGL; Gdx.gl20 = mockGL; final HeadlessApplication application = new HeadlessApplication(new SolApplication(moduleManager, 100), new HeadlessApplicationConfiguration()); game = ((SolApplication) application.getApplicationListener()).getGame(); }
Source:
public void commit() { if ( !isActive( true ) ) { throw new IllegalStateException( "Transaction not successfully started" ); } if ( LOG.isDebugEnabled() ) { LOG.debug( "committing" ); } try { internalGetTransactionDriverControl().commit(); } catch (RuntimeException e) { throw exceptionConverter.convertCommitException( e ); } }

Target:
public void commit() { if ( !isActive( true ) ) { throw new IllegalStateException( "Transaction not successfully started" ); } LOG.debug( "committing" ); try { internalGetTransactionDriverControl().commit(); } catch (RuntimeException e) { throw exceptionConverter.convertCommitException( e ); } }
Source:
public void verify() { synchronized (controller) { processing.forEach(Expectation::verify); if (!expectations.isEmpty()) { throw controller.setFailure( new AssertionError( "expecting " + (expectations.size() + processing.size()) + " executions for '" + controller + "' but only " + processing.size() + " occurred; the following were not executed: \r\n\t" + expectations .stream() .map(Expectation::toString) .collect(Collectors.joining(ActionRegistry.CR_AND_INDENT)) + "\r\n")); } } }

Target:
public void verify() { synchronized (controller) { processing.forEach(Expectation::verify); if (!expectations.isEmpty()) { throw controller.setFailure( new AssertionError( String.format( "expecting %d executions for `%s` but only %d occurred; the following were not executed: %n\t%s%n", (expectations.size() + processing.size()), controller, processing.size(), expectations .stream() .map(Expectation::toString) .collect(Collectors.joining(ActionRegistry.NL_AND_INDENT))))); } } }
Source:
static AppInstallationToken generateAppInstallationToken(String appId, String appPrivateKey, String apiUrl, String owner) { try (Timeout timeout = Timeout.limit(30, TimeUnit.SECONDS)) { String jwtToken = createJWT(appId, appPrivateKey); GitHub gitHubApp = Connector .createGitHubBuilder(apiUrl) .withJwtToken(jwtToken) .build(); GHApp app = gitHubApp.getApp(); List<GHAppInstallation> appInstallations = app.listInstallations().asList(); if (appInstallations.isEmpty()) { throw new IllegalArgumentException(String.format(ERROR_NOT_INSTALLED, appId)); } GHAppInstallation appInstallation; if (appInstallations.size() == 1) { appInstallation = appInstallations.get(0); } else { appInstallation = appInstallations.stream() .filter(installation -> installation.getAccount().getLogin().equals(owner)) .findAny() .orElseThrow(() -> new IllegalArgumentException(String.format( ERROR_NOT_INSTALLED, appId))); } GHAppInstallationToken appInstallationToken = appInstallation .createToken(appInstallation.getPermissions()) .create(); long expiration = getExpirationSeconds(appInstallationToken); LOGGER.log(Level.FINEST, "Token raw expiration epoch seconds: {0,number,#}", expiration); AppInstallationToken token = new AppInstallationToken(appInstallationToken.getToken(), expiration); LOGGER.log(Level.FINE, "Generated App Installation Token for app ID {0}", appId); return token; } catch (Exception e) { LOGGER.log(Level.WARNING, "Failed to retrieve GitHub App installation token for app ID " + appId, e); throw new IllegalArgumentException(String.format(ERROR_AUTHENTICATING_GITHUB_APP, appId), e); } }

Target:
static AppInstallationToken generateAppInstallationToken(String appId, String appPrivateKey, String apiUrl, String owner) { try (Timeout timeout = Timeout.limit(30, TimeUnit.SECONDS)) { String jwtToken = createJWT(appId, appPrivateKey); GitHub gitHubApp = Connector .createGitHubBuilder(apiUrl) .withJwtToken(jwtToken) .build(); GHApp app; try { app = gitHubApp.getApp(); } catch (IOException e) { throw new IllegalArgumentException(String.format(ERROR_AUTHENTICATING_GITHUB_APP, appId), e); } List<GHAppInstallation> appInstallations = app.listInstallations().asList(); if (appInstallations.isEmpty()) { throw new IllegalArgumentException(String.format(ERROR_NOT_INSTALLED, appId)); } GHAppInstallation appInstallation; if (appInstallations.size() == 1) { appInstallation = appInstallations.get(0); } else { appInstallation = appInstallations.stream() .filter(installation -> installation.getAccount().getLogin().equals(owner)) .findAny() .orElseThrow(() -> new IllegalArgumentException(String.format(ERROR_NOT_INSTALLED, appId))); } GHAppInstallationToken appInstallationToken = appInstallation .createToken(appInstallation.getPermissions()) .create(); long expiration = getExpirationSeconds(appInstallationToken); AppInstallationToken token = new AppInstallationToken(appInstallationToken.getToken(), expiration); LOGGER.log(Level.FINER, "Generated App Installation Token for app ID {0}", appId); return token; } catch (Exception e) { throw new IllegalArgumentException("Failed to generate GitHub App installation token for app ID " + appId , e); } }
Source:
public void setVisible(boolean visible) { if (visible != isVisible()) { if (!visible) { beforeHide(); } super.setVisible(visible); IContributionManager parent = getParent(); if (parent instanceof SubToolBarManager) { SubToolBarManager subManager = (SubToolBarManager) parent; IContributionItem item = subManager.getParent() .find(getId()); if (item != null) { item.setVisible(visible); } } bars.updateActionBars(); if (visible && toolbar != null) { openCloseToggle.setChecked(true); graph.getControl().setFocus(); toolbar.setFocus(); } else if (!visible && !graph.getControl().isDisposed()) { graph.getControl().setFocus(); } } }

Target:
public void setVisible(boolean visible) { if (visible != isVisible()) { if (!visible) { beforeHide(); } super.setVisible(visible); workAroundBug551067(visible); bars.updateActionBars(); if (visible && toolbar != null) { openCloseToggle.setChecked(true); graph.getControl().setFocus(); toolbar.setFocus(); } else if (!visible && !graph.getControl().isDisposed()) { graph.getControl().setFocus(); } } }
Source:
public PositionalJob(String thingUID) { checkNotNull(thingUID, "Thing UID cannot be null"); this.thingUID = thingUID; }

Target:
public PositionalJob(String thingUID) { checkArgument(thingUID != null, "Thing UID cannot be null"); this.thingUID = thingUID; }
Source:
public long writeTo(WritableByteChannel channel) throws IOException { long totalWritten = 0; if (bufferToSend == null) { bufferToSend = ByteBuffer.allocate(sizeExcludingData()); writeHeader(); bufferToSend.put(blobId.toBytes()); BlobPropertiesSerDe.putBlobPropertiesToBuffer(bufferToSend, properties); bufferToSend.putInt(usermetadata.capacity()); bufferToSend.put(usermetadata); bufferToSend.putLong(dataSize); bufferToSend.putShort((short) dataType.ordinal()); bufferToSend.flip(); } while (sentBytes < sizeInBytes()) { if (bufferToSend.remaining() > 0) { int toWrite = bufferToSend.remaining(); int written = channel.write(bufferToSend); totalWritten += written; sentBytes += written; if (toWrite != written || sentBytes == sizeInBytes()) { break; } } logger.trace("sent Bytes from Put Request {}", sentBytes); bufferToSend.clear(); int dataRead = data.read(bufferToSend.array(), 0, (int) Math.min(bufferToSend.capacity(), (sizeInBytes() - sentBytes))); bufferToSend.limit(dataRead); } return totalWritten; }

Target:
public long writeTo(WritableByteChannel channel) throws IOException { long totalWritten = 0; if (bufferToSend == null) { bufferToSend = ByteBuffer.allocate(sizeExcludingBlobSize()); writeHeader(); bufferToSend.put(blobId.toBytes()); BlobPropertiesSerDe.putBlobPropertiesToBuffer(bufferToSend, properties); bufferToSend.putInt(usermetadata.capacity()); bufferToSend.put(usermetadata); bufferToSend.putShort((short) blobType.ordinal()); bufferToSend.putLong(blobSize); bufferToSend.flip(); } while (sentBytes < sizeInBytes()) { if (bufferToSend.remaining() > 0) { int toWrite = bufferToSend.remaining(); int written = channel.write(bufferToSend); totalWritten += written; sentBytes += written; if (toWrite != written || sentBytes == sizeInBytes()) { break; } } logger.trace("sent Bytes from Put Request {}", sentBytes); bufferToSend.clear(); int streamReadCount = blobStream .read(bufferToSend.array(), 0, (int) Math.min(bufferToSend.capacity(), (sizeInBytes() - sentBytes))); bufferToSend.limit(streamReadCount); } return totalWritten; }
Source:
public static Collection<Supplier<Object[]>> buildGrids() { return ImmutableSet.of( () -> { try { return createRemotes(); } catch (URISyntaxException | SSLException | CertificateException e) { throw new RuntimeException(e); } }, () -> { try { return createInMemory(); } catch (Exception e) { throw new RuntimeException(e); } }); }

Target:
public static Collection<Supplier<Object[]>> buildGrids() { return ImmutableSet.of( () -> { try { return createRemotes(); } catch (CertificateException | SSLException | URISyntaxException e) { throw new RuntimeException(e); } }, () -> { try { return createInMemory(); } catch (Exception e) { throw new RuntimeException(e); } }); }
Source:
public Response createLayer(@Context HttpServletRequest req, InputStream postBody) { Response response = null; String newId = IdGenerator.generate(); List<Service> added = null; try { byte[] inmemory = IOUtils.toByteArray(postBody); ByteArrayInputStream bais = new ByteArrayInputStream(inmemory); String metadataId = MetadataUtil.doCSWInsertFromString(MetadataUtil.extractMetadataFromShp(bais)); bais.reset(); added = GeoserverUtil.addLayer(bais, newId); added.add(MetadataUtil.makeCSWServiceForUrl(MetadataUtil.getMetadataByIdUrl(metadataId))); } catch (IOException | ParserConfigurationException | SAXException e) { log.error("Problem creating services from input", e); } if (added != null && !added.isEmpty()) { Layer layer = new Layer(); layer.setId(newId); layer.setServices(added); try (LayerManager manager = new LayerManager()) { manager.save(layer); } response = Response.created(layerURI(layer)).build(); } else { response = Response.serverError().entity("Unable to create layer").build(); } return response; }

Target:
public Response createLayer(@Context HttpServletRequest req, InputStream postBody) { Response response = null; String newId = IdGenerator.generate(); List<Service> added = null; try { byte[] inmemory = IOUtils.toByteArray(postBody); try (ByteArrayInputStream bais = new ByteArrayInputStream(inmemory)) { String metadataId = MetadataUtil.doCSWInsertFromString(MetadataUtil.extractMetadataFromShp(bais)); bais.reset(); added = GeoserverUtil.addLayer(bais, newId); added.add(MetadataUtil.makeCSWServiceForUrl(MetadataUtil.getMetadataByIdUrl(metadataId))); } finally { inmemory = null; } } catch (IOException | ParserConfigurationException | SAXException e) { log.error("Problem creating services from input", e); } if (added != null && !added.isEmpty()) { Layer layer = new Layer(); layer.setId(newId); layer.setServices(added); try (LayerManager manager = new LayerManager()) { manager.save(layer); } response = Response.created(layerURI(layer)).build(); } else { response = Response.serverError().entity("Unable to create layer").build(); } return response; }
Source:
public void testGroupingSets() { assertions.assertQuery( "SELECT x, array_agg(y ORDER BY y), count(*) FROM (" + "VALUES " + " (1, 3), " + " (1, 1), " + " (2, 3), " + " (2, 4)) t(x, y) " + "GROUP BY GROUPING SETS ((), (x))", "VALUES " + " (1, ARRAY[1, 3], BIGINT '2'), " + " (2, ARRAY[3, 4], BIGINT '2'), " + " (NULL, ARRAY[1, 3, 3, 4], BIGINT '4')"); }

Target:
public void testGroupingSets() { assertions.assertQuery( "SELECT x, array_agg(y ORDER BY y), array_agg(y ORDER BY y) FILTER (WHERE y > 1), count(*) FROM (" + "VALUES " + " (1, 3), " + " (1, 1), " + " (2, 3), " + " (2, 4)) t(x, y) " + "GROUP BY GROUPING SETS ((), (x))", "VALUES " + " (1, ARRAY[1, 3], ARRAY[3], BIGINT '2'), " + " (2, ARRAY[3, 4], ARRAY[3, 4], BIGINT '2'), " + " (NULL, ARRAY[1, 3, 3, 4], ARRAY[3, 3, 4], BIGINT '4')"); assertions.assertQuery( "SELECT x, array_agg(DISTINCT y ORDER BY y), count(*) FROM (" + "VALUES " + " (1, 3), " + " (1, 1), " + " (1, 3), " + " (2, 3), " + " (2, 4)) t(x, y) " + "GROUP BY GROUPING SETS ((), (x))", "VALUES " + " (1, ARRAY[1, 3], BIGINT '3'), " + " (2, ARRAY[3, 4], BIGINT '2'), " + " (NULL, ARRAY[1, 3, 4], BIGINT '5')"); }
Source:
public static boolean validateIsNotEmpty(TaskDataProvider provider) { return !checkEmpty(new HashSet<>(), TASK_DATA_PROVIDER, "objects", provider.getObjects()); }

Target:
public static boolean validateIsNotEmpty(TaskDataProvider provider) { return !provider.getObjects().isEmpty(); }
Source:
private void flushErrors() { if(cachePath == null) return; safeAsync(new Runnable() { @Override public void run() { Notification notif = null; File exceptionDir = new File(cachePath); if(exceptionDir.exists() && exceptionDir.isDirectory()) { for(File errorFile : exceptionDir.listFiles()) { try { if(notif == null) notif = createNotification(); notif.setError(errorFile); notif.deliver(); logger.debug("Deleting sent error file " + errorFile.getName()); errorFile.delete(); } catch (IOException e) { logger.warn("Problem reading unsent error from disk", e); } } } } }); }

Target:
private void flushErrors() { if(cachePath == null) return; safeAsync(new Runnable() { @Override public void run() { File exceptionDir = new File(cachePath); if(exceptionDir.exists() && exceptionDir.isDirectory()) { Notification notif = null; for(File errorFile : exceptionDir.listFiles()) { try { if(notif == null) notif = createNotification(); notif.setError(errorFile); notif.deliver(); logger.debug("Deleting sent error file " + errorFile.getName()); errorFile.delete(); } catch (NetworkException e) { logger.warn("Could not send error(s) to Bugsnag, will try again later", e); } catch (Exception e) { logger.warn("Problem sending unsent error from disk", e); errorFile.delete(); } } } } }); }
Source:
private Moshi(Builder builder) { Set<JsonAdapter.Factory> factories = new LinkedHashSet<>(); factories.addAll(builder.factories); factories.add(StandardJsonAdapters.FACTORY); factories.add(CollectionJsonAdapter.FACTORY); factories.add(MapJsonAdapter.FACTORY); factories.add(ArrayJsonAdapter.FACTORY); factories.add(ClassJsonAdapter.FACTORY); this.factories = Collections.unmodifiableList(new ArrayList<>(factories)); }

Target:
private Moshi(Builder builder) { List<JsonAdapter.Factory> factories = new ArrayList<>(); factories.addAll(builder.factories); factories.addAll(BUILT_IN_FACTORIES); this.factories = Collections.unmodifiableList(factories); }
Source:
public void shouldConcatenateOneNonEmptyAndOneEmptyLists() { final List<Integer> list = Collections.unmodifiableList( IntStream.range(0, 4) .boxed() .collect(Collectors.toList()) ); final List<Integer> actual = ListOps.concat(EMPTY_LIST, list); final List<Integer> expected = IntStream.range(0, 4) .boxed() .collect(Collectors.toList()); assertNotNull(actual); assertFalse(actual.isEmpty()); assertEquals(expected, actual); }

Target:
public void shouldConcatenateOneNonEmptyAndOneEmptyLists() { final List<Integer> list = Collections.unmodifiableList( Arrays.asList(0, 1, 2, 3, 4) ); final List<Integer> actual = ListOps.concat(EMPTY_LIST, list); final List<Integer> expected = Arrays.asList(0, 1, 2, 3, 4); assertNotNull(actual); assertFalse(actual.isEmpty()); assertEquals(expected, actual); }
Source:
public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized != -1) { return isInitialized == 1; } if (!hasContinent()) { memoizedIsInitialized = 0; return false; } if (!hasCity()) { memoizedIsInitialized = 0; return false; } memoizedIsInitialized = 1; return true; }

Target:
public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized != -1) return isInitialized == 1; if (!hasContinent()) { memoizedIsInitialized = 0; return false; } if (!hasCity()) { memoizedIsInitialized = 0; return false; } memoizedIsInitialized = 1; return true; }
Source:
public ScheduleDefinition getSchedule(final TenantIdentifier tenant, final JobIdentifier jobIdentifier) { final TenantContext context = _tenantContextFactory.getContext(tenant); final String jobName = jobIdentifier.getName(); final JobContext jobContext = context.getJob(jobIdentifier); if (jobContext == null) { throw new IllegalArgumentException("No such job: " + jobName); } Map<String, String> jobMetadataProperties = null; if(jobContext.getJobFile().getType() == Type.ANALYSIS_JOB){ final AnalysisJobMetadata analysisJobMetadata = getJobMetadataFromJobFile(context, jobContext); jobMetadataProperties = analysisJobMetadata.getProperties(); } final String groupName = jobContext.getGroupName(); final RepositoryFolder jobsFolder = context.getJobFolder(); final RepositoryFile scheduleFile = jobsFolder.getFile(jobName + EXTENSION_SCHEDULE_XML); final JaxbScheduleReader reader = new JaxbScheduleReader(); final ScheduleDefinition schedule; if (scheduleFile == null) { schedule = new ScheduleDefinition(tenant, jobIdentifier, groupName); } else { schedule = scheduleFile.readFile(new Func<InputStream, ScheduleDefinition>() { @Override public ScheduleDefinition eval(InputStream inputStream) { return reader.read(inputStream, jobIdentifier, tenant, groupName); } }); } schedule.setJobMetadataProperties(jobMetadataProperties); return schedule; }

Target:
public ScheduleDefinition getSchedule(final TenantIdentifier tenant, final JobIdentifier jobIdentifier) { final TenantContext context = _tenantContextFactory.getContext(tenant); final String jobName = jobIdentifier.getName(); final JobContext jobContext = context.getJob(jobIdentifier); if (jobContext == null) { throw new IllegalArgumentException("No such job: " + jobName); } final Map<String, String> jobMetadataProperties = jobContext.getMetadataProperties(); final String groupName = jobContext.getGroupName(); final RepositoryFolder jobsFolder = context.getJobFolder(); final RepositoryFile scheduleFile = jobsFolder.getFile(jobName + EXTENSION_SCHEDULE_XML); final JaxbScheduleReader reader = new JaxbScheduleReader(); final ScheduleDefinition schedule; if (scheduleFile == null) { schedule = new ScheduleDefinition(tenant, jobIdentifier, groupName); } else { schedule = scheduleFile.readFile(new Func<InputStream, ScheduleDefinition>() { @Override public ScheduleDefinition eval(InputStream inputStream) { return reader.read(inputStream, jobIdentifier, tenant, groupName); } }); } schedule.setJobMetadataProperties(jobMetadataProperties); return schedule; }
Source:
protected void stop() { if (shutdownThread != null) { Runtime.getRuntime().removeShutdownHook(shutdownThread); shutdownThread = null; } try { if (process != null) { try { client.getControllerClient().executeAsync(Operations.createOperation("shutdown"), null); } catch (AssertionError | RuntimeException e) { } if (process != null) { if (process.waitFor(stopTimeout, TimeUnit.SECONDS)) { process = null; } else { process.destroy(); } } } } catch (Exception e) { try { if (process != null) { process.destroy(); process.waitFor(); } } catch (Exception ignore) { } throw new RuntimeException("Could not stop container", e); } finally { safeCloseClient(); } }

Target:
protected void stop() { if (shutdownThread != null) { Runtime.getRuntime().removeShutdownHook(shutdownThread); shutdownThread = null; } try { if (process != null) { try { client.getControllerClient().executeAsync(Operations.createOperation("shutdown"), null); } catch (AssertionError | RuntimeException e) { } if (!process.waitFor(stopTimeout, TimeUnit.SECONDS)) { process.destroy(); process.waitFor(); } process = null; } } catch (Exception e) { try { if (process != null) { process.destroy(); process.waitFor(); } } catch (Exception ignore) { } throw new RuntimeException("Could not stop container", e); } finally { safeCloseClient(); } }
Source:
public static void switchFocus (Stage stage, Focusable widget) { if (focusedWidget == widget) return; if (focusedWidget != null) focusedWidget.focusLost(); if (stage != null) stage.setKeyboardFocus(null); focusedWidget = widget; focusedWidget.focusGained(); }

Target:
public static void switchFocus (Stage stage, Focusable widget) { if (focusedWidget == widget) return; if (focusedWidget != null) focusedWidget.focusLost(); focusedWidget = null; if (stage != null) stage.setKeyboardFocus(null); focusedWidget = widget; focusedWidget.focusGained(); }
Source:
public void execute(String[] args, Console console) { int numberOfArguments = args.length; if (numberOfArguments < 1) { return; } String subCommand = args[0]; switch (subCommand) { case SUBCMD_LIST: listFirmwares(console, args); break; case SUBCMD_STATUS: listFirmwareStatus(console, args); break; case SUBCMD_UPDATE: updateFirmware(console, args); break; default: console.println( String.format("Unkown firmware sub command '%s'. Only the sub commands %s are supported.", subCommand, ALL_SUBCMDS)); break; } }

Target:
public void execute(String[] args, Console console) { int numberOfArguments = args.length; if (numberOfArguments < 1) { console.println("No firmare subcommand given."); printUsage(console); return; } String subCommand = args[0]; switch (subCommand) { case SUBCMD_LIST: listFirmwares(console, args); break; case SUBCMD_STATUS: listFirmwareStatus(console, args); break; case SUBCMD_UPDATE: updateFirmware(console, args); break; default: console.println(String.format("Unkown firmware sub command '%s'.", subCommand)); printUsage(console); break; } }
Source:
public static <T> T execute(ClientContext context, ClientExecReturn<T,MasterClientService.Client> exec) throws AccumuloException, AccumuloSecurityException, ThriftTableOperationException { MasterClientService.Client client = null; while (true) { try { client = getConnectionWithRetry(context); return exec.execute(client); } catch (TTransportException tte) { log.debug("MasterClient request failed, retrying ... ", tte); sleepUninterruptibly(100, TimeUnit.MILLISECONDS); } catch (ThriftSecurityException e) { throw new AccumuloSecurityException(e.user, e.code, e); } catch (AccumuloException | ThriftTableOperationException e) { throw e; } catch (ThriftNotActiveServiceException e) { log.debug("Contacted a Master which is no longer active, retrying"); sleepUninterruptibly(100, TimeUnit.MILLISECONDS); } catch (Exception e) { throw new AccumuloException(e); } finally { if (client != null) close(client); } } }

Target:
public static <T> T execute(ClientContext context, ClientExecReturn<T,MasterClientService.Client> exec) throws AccumuloException, AccumuloSecurityException, TableNotFoundException { MasterClientService.Client client = null; while (true) { try { client = getConnectionWithRetry(context); return exec.execute(client); } catch (TTransportException tte) { log.debug("MasterClient request failed, retrying ... ", tte); sleepUninterruptibly(100, TimeUnit.MILLISECONDS); } catch (ThriftSecurityException e) { throw new AccumuloSecurityException(e.user, e.code, e); } catch (AccumuloException e) { throw e; } catch (ThriftTableOperationException e) { switch (e.getType()) { case NAMESPACE_NOTFOUND: throw new TableNotFoundException(e.getTableName(), new NamespaceNotFoundException(e)); case NOTFOUND: throw new TableNotFoundException(e); default: throw new AccumuloException(e); } } catch (ThriftNotActiveServiceException e) { log.debug("Contacted a Master which is no longer active, retrying"); sleepUninterruptibly(100, TimeUnit.MILLISECONDS); } catch (Exception e) { throw new AccumuloException(e); } finally { if (client != null) close(client); } } }
Source:
protected String getLogParameters() { HttpUrl.Builder httpUrlBuilder = new HttpUrl.Builder(); StringBuilder sb = new StringBuilder(); httpUrlBuilder.addPathSegment("log"); httpUrlBuilder.addQueryParameter("pretty", String.valueOf(withPrettyOutput)); sb.append("log?pretty=").append(withPrettyOutput); if (containerId != null && !containerId.isEmpty()) { sb.append("&container=").append(containerId); httpUrlBuilder.addQueryParameter("container", containerId); } if (withTerminatedStatus) { sb.append("&previous=true"); httpUrlBuilder.addQueryParameter("previous", String.valueOf(Boolean.TRUE)); } if (sinceSeconds != null) { sb.append("&sinceSeconds=").append(sinceSeconds); httpUrlBuilder.addQueryParameter("sinceSeconds", String.valueOf(sinceSeconds)); } else if (sinceTimestamp != null) { sb.append("&sinceTime=").append(sinceTimestamp); httpUrlBuilder.addQueryParameter("sinceTime", sinceTimestamp); } if (withTailingLines != null) { sb.append("&tailLines=").append(withTailingLines); httpUrlBuilder.addQueryParameter("tailLines", String.valueOf(withTailingLines)); } if (limitBytes != null) { sb.append("&limitBytes=").append(limitBytes); httpUrlBuilder.addQueryParameter("limitBytes", String.valueOf(limitBytes)); } if (withTimestamps) { sb.append("&timestamps=true"); httpUrlBuilder.addQueryParameter("timestamps", String.valueOf(Boolean.TRUE)); } return httpUrlBuilder.build().toString(); }

Target:
protected String getLogParameters() { StringBuilder sb = new StringBuilder(); sb.append("log?pretty=").append(withPrettyOutput); if (containerId != null && !containerId.isEmpty()) { sb.append("&container=").append(containerId); } if (withTerminatedStatus) { sb.append("&previous=true"); } if (sinceSeconds != null) { sb.append("&sinceSeconds=").append(sinceSeconds); } else if (sinceTimestamp != null) { sb.append("&sinceTime=").append(sinceTimestamp); } if (withTailingLines != null) { sb.append("&tailLines=").append(withTailingLines); } if (limitBytes != null) { sb.append("&limitBytes=").append(limitBytes); } if (withTimestamps) { sb.append("&timestamps=true"); } return sb.toString(); }
Source:
protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) { Uri imageUri = data.getData(); Timber.d(imageUri.toString()); UCrop.of(imageUri,Uri.fromFile(new File(getCacheDir(), imageUri.getUserInfo()+".png"))).start(this); } if (resultCode == RESULT_OK && requestCode == UCrop.REQUEST_CROP) { final Uri resultUri = UCrop.getOutput(data); InputStream imageStream = null; try { imageStream = getContentResolver().openInputStream(resultUri); } catch (FileNotFoundException e) { e.printStackTrace(); } Bitmap selectedImage = BitmapFactory.decodeStream(imageStream); encodedImage = encodeImage(selectedImage); StrategyRegistry.getInstance().getHttpStrategy().getPicassoWithCache() .load(resultUri) .transform(new CircleTransform()) .into(avatar); } else if (resultCode == UCrop.RESULT_ERROR) { final Throwable cropError = UCrop.getError(data); Timber.d(cropError, "EditProfileActivity UCrop Error %s"); } }

Target:
protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) { Uri imageUri = data.getData(); Timber.d(imageUri.toString()); UCrop.of(imageUri,Uri.fromFile(new File(getCacheDir(), imageUri.getUserInfo()+".png"))).start(this); } if (resultCode == RESULT_OK && requestCode == UCrop.REQUEST_CROP) { final Uri resultUri = UCrop.getOutput(data); InputStream imageStream = null; try { imageStream = getContentResolver().openInputStream(resultUri); } catch (FileNotFoundException e) { e.printStackTrace(); } Bitmap selectedImage = BitmapFactory.decodeStream(imageStream); encodedImage = encodeImage(selectedImage); StrategyRegistry.getInstance().getHttpStrategy().getPicassoWithCache() .load(resultUri) .transform(new CircleTransform()) .into(avatar); } else if (resultCode == UCrop.RESULT_ERROR) { final Throwable cropError = UCrop.getError(data); Timber.d("EditProfileActivity UCrop Error %s", cropError); } }
Source:
private JobExecution<Report.Result> toInternalModel(final ReportExecution beanModel) { final ReportExecution.State state = beanModel.getState(); switch (state) { case STARTED: return new JobExecution.Started.Builder<Report.Result>() .setJobId(beanModel.getReport().getUuid()) .setScheduled(beanModel.getScheduled()) .setStartedAt(beanModel.getStartedAt()) .build(); case FAILURE: @Nullable final Throwable throwable = beanModel.getError() == null ? null : beanModel.getError().getThrowable(); return new JobExecution.Failure.Builder<Report.Result>() .setJobId(beanModel.getReport().getUuid()) .setScheduled(beanModel.getScheduled()) .setStartedAt(beanModel.getStartedAt()) .setCompletedAt(beanModel.getCompletedAt()) .setError(throwable) .build(); case SUCCESS: return new JobExecution.Success.Builder<Report.Result>() .setJobId(beanModel.getReport().getUuid()) .setScheduled(beanModel.getScheduled()) .setCompletedAt(beanModel.getCompletedAt()) .setStartedAt(beanModel.getStartedAt()) .setResult(beanModel.getResult()) .build(); default: throw new AssertionError("unexpected state: " + state); } }

Target:
private JobExecution<Report.Result> toInternalModel(final ReportExecution beanModel) { final ReportExecution.State state = beanModel.getState(); switch (state) { case STARTED: return new JobExecution.Started.Builder<Report.Result>() .setJobId(beanModel.getReport().getUuid()) .setScheduled(beanModel.getScheduled()) .setStartedAt(beanModel.getStartedAt()) .build(); case FAILURE: @Nullable final Throwable throwable = beanModel.getError() == null ? null : new Throwable(beanModel.getError()); return new JobExecution.Failure.Builder<Report.Result>() .setJobId(beanModel.getReport().getUuid()) .setScheduled(beanModel.getScheduled()) .setStartedAt(beanModel.getStartedAt()) .setCompletedAt(beanModel.getCompletedAt()) .setError(throwable) .build(); case SUCCESS: return new JobExecution.Success.Builder<Report.Result>() .setJobId(beanModel.getReport().getUuid()) .setScheduled(beanModel.getScheduled()) .setCompletedAt(beanModel.getCompletedAt()) .setStartedAt(beanModel.getStartedAt()) .setResult(beanModel.getResult()) .build(); default: throw new AssertionError("unexpected state: " + state); } }
Source:
public List<Location> getFilteredLocations(final Set<Integer> types, final List<Integer> locationIds, final String programUUID) { final List<Location> locations; try { final Criteria criteria = this.getSession().createCriteria(Location.class); if (types != null && !types.isEmpty()) { criteria.add(Restrictions.in(LocationDAO.LTYPE, types)); } if (locationIds != null && !locationIds.isEmpty()) { criteria.add(Restrictions.in(LocationDAO.LOCID, locationIds)); } criteria.add( Restrictions.or(Restrictions.eq(LocationDAO.UNIQUE_ID, programUUID), Restrictions.isNull(LocationDAO.UNIQUE_ID))); criteria.addOrder(Order.asc(LocationDAO.LNAME)); locations = criteria.list(); } catch (final HibernateException e) { throw new MiddlewareQueryException( this.getLogExceptionMessage("getFilteredLocations", "types,locationIds,programUUID", "", e.getMessage(), LocationDAO.CLASS_NAME_LOCATION), e); } return locations; }

Target:
public List<Location> getFilteredLocations(final Set<Integer> types, final List<Integer> locationIds, final String programUUID) { final List<Location> locations; try { final Criteria criteria = this.getSession().createCriteria(Location.class); if (types != null && !types.isEmpty()) { criteria.add(Restrictions.in(LocationDAO.LTYPE, types)); } if (locationIds != null && !locationIds.isEmpty()) { criteria.add(Restrictions.in(LocationDAO.LOCID, locationIds)); } criteria.add( Restrictions.or(Restrictions.eq(LocationDAO.UNIQUE_ID, programUUID), Restrictions.isNull(LocationDAO.UNIQUE_ID))); criteria.addOrder(Order.asc(LocationDAO.LNAME)); locations = criteria.list(); } catch (final HibernateException e) { LocationDAO.LOG.error(e.getMessage(), e); throw new MiddlewareQueryException( this.getLogExceptionMessage("getFilteredLocations", "types,locationIds,programUUID", "", e.getMessage(), LocationDAO.CLASS_NAME_LOCATION), e); } return locations; }
Source:
public void testReplicationStatusSink() throws Exception { try (Admin hbaseAdmin = UTIL2.getConnection().getAdmin()) { ServerName server = UTIL2.getHBaseCluster().getRegionServer(0).getServerName(); ReplicationLoadSink loadSink = getLatestSinkMetric(hbaseAdmin, server); assertEquals(loadSink.getTimestampStarted(), loadSink.getTimestampsOfLastAppliedOp()); insertRowsOnSource(); Thread.sleep(10000); loadSink = getLatestSinkMetric(hbaseAdmin, server); assertTrue(loadSink.getTimestampsOfLastAppliedOp()>loadSink.getTimestampStarted()); } }

Target:
public void testReplicationStatusSink() throws Exception { try (Admin hbaseAdmin = UTIL2.getConnection().getAdmin()) { ServerName server = UTIL2.getHBaseCluster().getRegionServer(0).getServerName(); ReplicationLoadSink loadSink = getLatestSinkMetric(hbaseAdmin, server); assertEquals(loadSink.getTimestampStarted(), loadSink.getTimestampsOfLastAppliedOp()); insertRowsOnSource(); long wait = Waiter.waitFor(UTIL2.getConfiguration(), 10000, new Waiter.Predicate<Exception>() { @Override public boolean evaluate() throws Exception { ReplicationLoadSink loadSink = getLatestSinkMetric(hbaseAdmin, server); return loadSink.getTimestampsOfLastAppliedOp()>loadSink.getTimestampStarted(); } }); assertTrue(wait>=0); } }