auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void testTooManyRequests() { ActionFactory factory = new ActionFactory(); WebRequestAction action = (WebRequestAction) factory.createWebRequestAction(testSprite, new Formula(TEST_URL), userVariable); action.setWebConnectionFactory(webConnectionFactory); Mockito.when(webConnectionFactory.getWebConnection(Mockito.anyString(), Mockito.any())).thenReturn(webConnection); Mockito.when(StageActivity.webConnectionHolder.addConnectionToList(Mockito.any(WebConnection.class))) .thenReturn(false); boolean isActionFinished = action.act(0f); assertTrue(isActionFinished); assertEquals(ERROR_TOO_MANY_REQUESTS, userVariable.getValue()); assertThat(action.getTime(), is(lessThan(60f))); }

Target:
public void testTooManyRequests() { WebRequestAction action = (WebRequestAction) testSprite.getActionFactory().createWebRequestAction( testSprite, new Formula(TEST_URL), userVariable ); action.setWebConnectionFactory(webConnectionFactory); when(webConnectionFactory.createWebConnection(anyString(), any())).thenReturn(webConnection); when(StageActivity.stageListener.webConnectionHolder.addConnection(any())).thenReturn(false); assertTrue(action.act(0f)); assertEquals(ERROR_TOO_MANY_REQUESTS, userVariable.getValue()); }
Source:
protected void validate(CommonHttpResponse response, int expected, IOperationMonitor monitor) throws BugzillaRestException { int statusCode = response.getStatusCode(); if (statusCode != expected && statusCode != 400) { if (statusCode == HttpStatus.SC_NOT_FOUND) { throw new BugzillaRestResourceNotFoundException( NLS.bind("Requested resource ''{0}'' does not exist", response.getRequestPath())); } throw new BugzillaRestException(NLS.bind("Unexpected response from Bugzilla REST server for ''{0}'': {1}", response.getRequestPath(), HttpUtil.getStatusText(statusCode))); } }

Target:
protected void validate(CommonHttpResponse response, int expected, IOperationMonitor monitor) throws BugzillaRestException { int statusCode = response.getStatusCode(); if (statusCode != expected && statusCode != HttpStatus.SC_BAD_REQUEST) { if (statusCode == HttpStatus.SC_NOT_FOUND) { throw new BugzillaRestResourceNotFoundException( NLS.bind("Requested resource ''{0}'' does not exist", response.getRequestPath())); } throw new BugzillaRestException(NLS.bind("Unexpected response from Bugzilla REST server for ''{0}'': {1}", response.getRequestPath(), HttpUtil.getStatusText(statusCode))); } }
Source:
private void validateInput() { if (getShell() == null) { return; } String tagNameMessage = tagNameValidator.isValid(tagNameText.getText()); if (tagNameErrorText != null && !tagNameErrorText.isDisposed()) tagNameErrorText .setText(tagNameMessage == null ? "\n" : tagNameMessage); String tagMessageVal = tagMessageText.getText().trim(); Control button = getButton(IDialogConstants.OK_ID); if (button != null) { boolean containsTagNameAndMessage = (tagNameMessage == null || tagMessageVal .isEmpty()) && !tagMessageVal.isEmpty(); boolean shouldOverwriteTag = (overwriteButton.getSelection() && Repository .isValidRefName(Constants.R_TAGS + tagNameText.getText())); button.setEnabled(containsTagNameAndMessage || shouldOverwriteTag); } }

Target:
private void validateInput() { if (getShell() == null) { return; } String tagNameMessage = tagNameValidator.isValid(tagNameText.getText()); if (tagNameErrorText != null && !tagNameErrorText.isDisposed()) tagNameErrorText .setText(tagNameMessage == null ? "\n" : tagNameMessage); String tagMessageVal = tagMessageText.getText().trim(); Control button = getButton(IDialogConstants.OK_ID); if (button != null) { boolean containsTagNameAndMessage = (tagNameMessage == null || tagMessageVal .length() == 0) && tagMessageVal.length() != 0; boolean shouldOverwriteTag = (overwriteButton.getSelection() && Repository .isValidRefName(Constants.R_TAGS + tagNameText.getText())); button.setEnabled(containsTagNameAndMessage || shouldOverwriteTag); } }
Source:
void correctUrlIsAccessedAfterLogin(TestUtils setup, TestReference testReference) { setup.deletePage(testReference); setup.createPage(testReference, "whatever"); setup.setRights(testReference, "XWiki.XWikiAllGroup", "", "view", true); setup.forceGuestUser(); setup.gotoPage(testReference); LoginPage loginPage = new LoginPage(); setup.getDriver().waitUntilPageIsReloaded(); loginPage.assertOnPage(); assertFalse(loginPage.isAuthenticated()); loginPage.loginAsAdmin(); setup.assertOnPage(testReference); }

Target:
void correctUrlIsAccessedAfterLogin(TestUtils setup, TestReference testReference) { setup.loginAsAdmin(); setup.deletePage(testReference); setup.createPage(testReference, "whatever"); setup.setRights(testReference, null, "XWiki.XWikiGuest", "view", false); setup.forceGuestUser(); setup.gotoPage(testReference); LoginPage loginPage = new LoginPage(); loginPage.assertOnPage(); assertFalse(loginPage.isAuthenticated()); loginPage.loginAsAdmin(); setup.assertOnPage(testReference); }
Source:
private File createArtifact() throws MojoExecutionException { try { File payload = getPayload(); File newArtifact = new File(outputDirectory, project.getArtifactId() + "-" + project.getVersion() + ".zip"); if (newArtifact.exists()) { newArtifact.delete(); } if (payload.exists()) { DefaultFileSet fs = new DefaultFileSet(); fs.setDirectory(payload); zipArchiver.addFileSet(fs); } else { zipArchiver.addFile(new File(outputDirectory, IU.P2_IU), "emptyArtifact.xml"); } zipArchiver.setDestFile(newArtifact); zipArchiver.setCompress(true); zipArchiver.createArchive(); return newArtifact; } catch (IOException e) { throw new MojoExecutionException("Error assembling ZIP", e); } catch (ArchiverException e) { throw new MojoExecutionException("Error assembling ZIP", e); } }

Target:
private File createArtifact() throws MojoExecutionException { try { File payload = getPayloadDir(); File newArtifact = new File(outputDirectory, project.getArtifactId() + "-" + project.getVersion() + ".zip"); if (newArtifact.exists()) { newArtifact.delete(); } if (hasPayload()) { DefaultFileSet fs = new DefaultFileSet(); fs.setDirectory(payload); zipArchiver.addFileSet(fs); zipArchiver.setDestFile(newArtifact); zipArchiver.setCompress(true); zipArchiver.createArchive(); } else { newArtifact.createNewFile(); } return newArtifact; } catch (IOException e) { throw new MojoExecutionException("Error assembling ZIP", e); } catch (ArchiverException e) { throw new MojoExecutionException("Error assembling ZIP", e); } }
Source:
public void run() { try { while (running.get()) { try { if (!hardDelete(true)) { isCaughtUp = true; synchronized (hardDeleteThread) { if (!running.get()) { break; } isWaiting = true; hardDeleteThread.wait(hardDeleterSleepTimeWhenCaughtUpMs); isWaiting = false; } } else if (isCaughtUp) { isCaughtUp = false; logger.info("Resumed hard deletes for after having caught up", dataDir); } } catch (StoreException e) { if (e.getErrorCode() != StoreErrorCodes.Store_Shutting_Down) { logger.error("Caught store exception: ", e); } else { logger.trace("Caught exception during hard deletes", e); } } catch (InterruptedException e) { logger.trace("Caught exception during hard deletes", e); } } } finally { close(); } }

Target:
public void run() { try { while (running.get()) { try { if (!hardDelete(true)) { isCaughtUp = true; synchronized (hardDeleteThread) { if (!running.get()) { break; } hardDeleteThread.wait(hardDeleterSleepTimeWhenCaughtUpMs); } } else if (isCaughtUp) { isCaughtUp = false; logger.info("Resumed hard deletes for after having caught up", dataDir); } } catch (StoreException e) { if (e.getErrorCode() != StoreErrorCodes.Store_Shutting_Down) { logger.error("Caught store exception: ", e); } else { logger.trace("Caught exception during hard deletes", e); } } catch (InterruptedException e) { logger.trace("Caught exception during hard deletes", e); } } } finally { close(); } }
Source:
public void reset() { initSlabs(max(size / 7, initialSize)); }

Target:
public void reset() { this.initialSlabSize = max(bytesUsed / 7, initialSlabSize); if (Log.DEBUG) LOG.debug(String.format("initial slab of size %d", initialSlabSize)); this.slabs.clear(); this.bytesAllocated = 0; this.bytesUsed = 0; this.currentSlab = EMPTY_SLAB; this.currentSlabIndex = 0; }
Source:
public void tearDown() { dbClient.shutdown(); }

Target:
public void tearDown() { if(dbClient != null) { dbClient.shutdown(); } }
Source:
public void onSessionReady(@NonNull Session session) { lock.writeLock().lock(); try { sessionReady = true; delegate.onSessionReady(session); if (replayInitEvents) { for (InitEvent event : initEvents) { event.invoke(delegate); } } } finally { lock.writeLock().unlock(); } }

Target:
public void onSessionReady(@NonNull Session session) { lock.writeLock().lock(); try { if (!sessionReady) { sessionReady = true; delegate.onSessionReady(session); if (replayInitEvents) { for (InitEvent event : initEvents) { event.invoke(delegate); } } } } finally { lock.writeLock().unlock(); } }
Source:
public static Object[][] testGetReplicasCountDataProvider() { return new Object[][] {{null, true, AUTOWIRE, 0, "false"}, {null, false, STATIC, 1, "false"}, {"0-all", false, BOUNDED, -1, "0-all"}, {"5", true, STATIC, 5, "false"}, {"5", false, STATIC, 5, "false"}, }; }

Target:
public static Object[][] testGetReplicasCountDataProvider() { return new Object[][] {{null, true, AUTOWIRE, 0, "false"}, {null, false, STATIC, 1, "false"}, {"0-all", false, BOUNDED, -1, "0-all"}, {"5", true, STATIC, 5, "false"}, {"5", false, STATIC, 5, "false"}, {"autowire", true, AUTOWIRE, 0, "false"}}; }
Source:
public List<ToolVersionV1> getVersionsV1() { List<ToolVersion> toolVersions = this.tool.getVersions(); return toolVersions.parallelStream().map(toolVersion -> new ToolVersionV1(toolVersion)).collect(Collectors.toList()); }

Target:
public List<ToolVersionV1> getVersionsV1() { List<ToolVersion> toolVersions = this.tool.getVersions(); return toolVersions.stream().map(toolVersion -> new ToolVersionV1(toolVersion)).collect(Collectors.toList()); }
Source:
public static void reset() { FACADE.reset(); }

Target:
static void reset() { FACADE.reset(); }
Source:
public void endOfAnalysis() { if (!(context instanceof AnalyzerMessageReporter)) { return; } AnalyzerMessageReporter reporter = (AnalyzerMessageReporter) context; messagesPerPackage.entrySet().stream() .filter(entry -> scannedPackages.stream().noneMatch(entry.getKey()::contains)) .forEach(entry -> entry.getValue().forEach(reporter::reportIssue)); }

Target:
public void endOfAnalysis() { DefaultJavaFileScannerContext defaultContext = (DefaultJavaFileScannerContext) context; messagesPerPackage.entrySet().stream() .filter(entry -> packagesScannedBySpring.stream().noneMatch(entry.getKey()::contains)) .forEach(entry -> entry.getValue().forEach(defaultContext::reportIssue)); }
Source:
void testRepositoryAccessModelFormInvalidEmptyPrivileges() { RepositoryAccessModelForm repositoryAccessModelForm = new RepositoryAccessModelForm(); repositoryAccessModelForm.setStorageId(STORAGE_ID_VALID); repositoryAccessModelForm.setRepositoryId(REPOSITORY_ID_VALID); repositoryAccessModelForm.setPrivileges(Collections.emptyList()); Set<ConstraintViolation<RepositoryAccessModelForm>> violations = validator.validate(repositoryAccessModelForm); assertThat(violations.isEmpty()).as("Violations are empty!").isFalse(); assertThat(violations.size()).isEqualTo(1); assertThat(violations).extracting("message").containsAnyOf("A collection of privileges must be specified."); }

Target:
void testRepositoryAccessModelFormInvalidEmptyPrivileges() { RepositoryAccessModelForm repositoryAccessModelForm = new RepositoryAccessModelForm(); repositoryAccessModelForm.setStorageId(STORAGE_ID_VALID); repositoryAccessModelForm.setRepositoryId(REPOSITORY_ID_VALID); repositoryAccessModelForm.setPrivileges(Collections.emptyList()); Set<ConstraintViolation<RepositoryAccessModelForm>> violations = validator.validate(repositoryAccessModelForm); assertThat(violations).as("Violations are empty!").hasSize(1); assertThat(violations).extracting("message").containsAnyOf("A collection of privileges must be specified."); }
Source:
public static <T> T last(Class<T>type){ return findById(type, count(type)); }

Target:
public static <T> T last(Class<T>type){ List<T> list = findWithQuery(type, "SELECT * FROM " + NamingHelper.toSQLName(type) + " ORDER BY ROWID DESC LIMIT 1"); if (list.isEmpty()) return null; return list.get(0); }
Source:
public void selectionChanged(IWorkbenchPart part, ISelection sel) { List<IReview> lastServers = reviews; if (part instanceof TaskEditor) { TaskEditor editor = (TaskEditor) part; IFormPage page = editor.getActivePageInstance(); if (page instanceof AbstractReviewTaskEditorPage) { IReview review = ((AbstractReviewTaskEditorPage) page).getReview(); if (review != null) { reviews = Collections.singletonList(review); } else { reviews = Collections.emptyList(); } lastPartHint = part; if (!reviews.equals(lastServers)) { update(); } } } updateContentDescription(); refreshAction.setEnabled(!reviews.isEmpty()); }

Target:
public void selectionChanged(IWorkbenchPart part, ISelection sel) { List<IReview> lastReviews = reviews; if (part instanceof TaskEditor) { TaskEditor editor = (TaskEditor) part; IFormPage page = editor.getActivePageInstance(); if (page instanceof AbstractReviewTaskEditorPage) { IReview review = ((AbstractReviewTaskEditorPage) page).getReview(); if (review != null) { reviews = Collections.singletonList(review); } else { reviews = Collections.emptyList(); } lastPartHint = part; if (!reviews.equals(lastReviews)) { update(); } } } updateContentDescription(); refreshAction.setEnabled(!reviews.isEmpty()); }
Source:
public void init(final GatewayConfig config, final Map<String, String> options) throws ServiceLifecycleException { tokenEvictionInterval = config.getKnoxTokenEvictionInterval(); if (tokenEvictionInterval > 0) { evictionScheduler.scheduleAtFixedRate(() -> evictExpiredTokens(), tokenEvictionInterval, tokenEvictionInterval, TimeUnit.SECONDS); } }

Target:
public void init(final GatewayConfig config, final Map<String, String> options) throws ServiceLifecycleException { tokenEvictionInterval = config.getKnoxTokenEvictionInterval(); tokenEvictionGracePeriod = config.getKnoxTokenEvictionGracePeriod(); }
Source:
public List<FlowLog> getFlowLogsByFlowIdsCreatedDesc(Set<String> flowIds) { LOGGER.info("Getting flow logs by these flow ids: {}", Joiner.on(",").join(flowIds)); if (flowIds.size() > 0) { return flowLogRepository.findAllByFlowIdsCreatedDesc(flowIds); } else { return Collections.emptyList(); } }

Target:
public List<FlowLog> getFlowLogsByFlowIdsCreatedDesc(Set<String> flowIds) { LOGGER.info("Getting flow logs by these flow ids: {}", Joiner.on(",").join(flowIds)); if (!flowIds.isEmpty()) { return flowLogRepository.findAllByFlowIdsCreatedDesc(flowIds); } else { return Collections.emptyList(); } }
Source:
public SearchResponseData saveIssueAndPreloadSearchResponseData(DbSession dbSession, DefaultIssue issue, IssueChangeContext context, @Nullable String comment, boolean refreshMeasures) { Optional<RuleDefinitionDto> rule = getRuleByKey(dbSession, issue.getRuleKey()); ComponentDto project = dbClient.componentDao().selectOrFailByUuid(dbSession, issue.projectUuid()); ComponentDto component = dbClient.componentDao().selectOrFailByUuid(dbSession, issue.componentUuid()); IssueDto issueDto = doSaveIssue(dbSession, issue, context, comment, rule, project, component); if (refreshMeasures) { issueChangePostProcessor.process(dbSession, singleton(component)); } SearchResponseData preloadedSearchResponseData = new SearchResponseData(issueDto); rule.ifPresent(r -> preloadedSearchResponseData.setRules(singletonList(r))); preloadedSearchResponseData.addComponents(singleton(project)); preloadedSearchResponseData.addComponents(singleton(component)); return preloadedSearchResponseData; }

Target:
public SearchResponseData saveIssueAndPreloadSearchResponseData(DbSession dbSession, DefaultIssue issue, IssueChangeContext context, @Nullable String comment, boolean refreshMeasures) { Optional<RuleDefinitionDto> rule = getRuleByKey(dbSession, issue.getRuleKey()); ComponentDto project = dbClient.componentDao().selectOrFailByUuid(dbSession, issue.projectUuid()); ComponentDto component = dbClient.componentDao().selectOrFailByUuid(dbSession, issue.componentUuid()); IssueDto issueDto = doSaveIssue(dbSession, issue, context, comment, rule, project, component); SearchResponseData result = new SearchResponseData(issueDto); rule.ifPresent(r -> result.setRules(singletonList(r))); result.addComponents(singleton(project)); result.addComponents(singleton(component)); if (refreshMeasures) { List<DefaultIssue> changedIssues = result.getIssues().stream().map(IssueDto::toDefaultIssue).collect(MoreCollectors.toList(result.getIssues().size())); issueChangePostProcessor.process(dbSession, changedIssues, singleton(component)); } return result; }
Source:
private void setObjectManagers(Set<String> affectedNamespaces, IObjectManager manager) { for (String string : affectedNamespaces) { getDelta(string).setObjectManager(manager); } if (eventDelta != null) eventDelta.setObjectManager(manager); }

Target:
private void setObjectManagers(Set<String> affectedNamespaces, IObjectManager manager) { for (String namespace : affectedNamespaces) { getDelta(namespace).setObjectManager(manager); } if (eventDelta != null) eventDelta.setObjectManager(manager); }
Source:
protected MutableBoundedValue<Short> constructValue(Short actualValue) { return SpongeValueFactory.boundedBuilder(Keys.SPAWNER_MINIMUM_DELAY) .minimum((short) 0) .maximum(Short.MAX_VALUE) .defaultValue((short) 200) .actualValue(actualValue) .build(); }

Target:
protected MutableBoundedValue<Short> constructValue(Short actualValue) { return SpongeValueFactory.boundedBuilder(Keys.SPAWNER_MINIMUM_DELAY) .minimum((short) 0) .maximum(Short.MAX_VALUE) .defaultValue(DataConstants.DEFAULT_SPAWNER_MINIMUM_SPAWN_DELAY) .actualValue(actualValue) .build(); }
Source:
public void process() { PerformanceMonitor.startActivity("rendering/backdrop"); sceneOpaque = dynamicFBM.getFBO(DefaultDynamicFBOs.ReadOnlyGBuffer.getResourceUrn()); initialClearing(); sceneOpaque.bind(); setRenderBufferMask(sceneOpaque, true, true, true); playerCamera.lookThroughNormalized(); setRenderBufferMask(sceneOpaque, true, false, false); backdropRenderer.render(playerCamera); PerformanceMonitor.endActivity(); }

Target:
public void process() { PerformanceMonitor.startActivity("rendering/backdrop"); initialClearing(); READ_ONLY_GBUFFER.bind(); READ_ONLY_GBUFFER.setRenderBufferMask(true, true, true); playerCamera.lookThroughNormalized(); READ_ONLY_GBUFFER.setRenderBufferMask(true, false, false); backdropRenderer.render(playerCamera); PerformanceMonitor.endActivity(); }
Source:
public static void init() { registerLoader(new ResourceLocation("forge:obj"), OBJLoader2.INSTANCE); registerLoader(new ResourceLocation("forge:bucket"), ModelDynBucket.Loader.INSTANCE); registerLoader(new ResourceLocation("forge:composite"), CompositeModel.Loader.INSTANCE); registerLoader(new ResourceLocation("minecraft:elements"), VanillaProxy.Loader.INSTANCE); registerLoader(new ResourceLocation("forge:b3d"), new ModelLoaderAdapter(B3DLoader.INSTANCE)); registerLoader(new ResourceLocation("forge:fluid"), new ModelLoaderAdapter(ModelFluid.FluidLoader.INSTANCE)); registerLoader(new ResourceLocation("forge:multi-layer"), new ModelLoaderAdapter(MultiLayerModel.Loader.INSTANCE)); }

Target:
public static void init() { registerLoader(new ResourceLocation("minecraft","elements"), VanillaProxy.Loader.INSTANCE); registerLoader(new ResourceLocation("forge","obj"), OBJLoader2.INSTANCE); registerLoader(new ResourceLocation("forge","bucket"), ModelDynBucket.Loader.INSTANCE); registerLoader(new ResourceLocation("forge","composite"), CompositeModel.Loader.INSTANCE); registerLoader(new ResourceLocation("forge","b3d"), new ModelLoaderAdapter(B3DLoader.INSTANCE)); registerLoader(new ResourceLocation("forge","fluid"), new ModelLoaderAdapter(ModelFluid.FluidLoader.INSTANCE)); registerLoader(new ResourceLocation("forge","multi-layer"), new ModelLoaderAdapter(MultiLayerModel.Loader.INSTANCE)); }
Source:
protected void mapFileDomain(StorageDomain model, org.ovirt.engine.core.common.businessentities.StorageDomain entity) { final Storage storage = model.getStorage(); StorageServerConnections cnx = getStorageServerConnection(entity.getStorage()); if (cnx.getconnection().contains(":")) { String[] parts = cnx.getconnection().split(":"); model.getStorage().setAddress(parts[0]); model.getStorage().setPath(parts[1]); } else { model.getStorage().setPath(cnx.getconnection()); } storage.setMountOptions(cnx.getMountOptions()); storage.setVfsType(cnx.getVfsType()); if (entity.getStorageType() == StorageType.NFS) { if (cnx.getNfsRetrans() != null) { model.getStorage().setNfsRetrans(cnx.getNfsRetrans().intValue()); } if (cnx.getNfsTimeo() != null) { model.getStorage().setNfsTimeo(cnx.getNfsTimeo().intValue()); } if (cnx.getNfsVersion() != null) { model.getStorage().setNfsVersion(StorageDomainMapper.map(cnx.getNfsVersion(), null)); } } }

Target:
protected void mapFileDomain(StorageDomain model, org.ovirt.engine.core.common.businessentities.StorageDomain entity) { final Storage storage = model.getStorage(); StorageServerConnections cnx = getStorageServerConnection(entity.getStorage()); if (cnx.getconnection().contains(":")) { String[] parts = cnx.getconnection().split(":"); storage.setAddress(parts[0]); storage.setPath(parts[1]); } else { storage.setPath(cnx.getconnection()); } storage.setMountOptions(cnx.getMountOptions()); storage.setVfsType(cnx.getVfsType()); if (entity.getStorageType() == StorageType.NFS) { if (cnx.getNfsRetrans() != null) { storage.setNfsRetrans(cnx.getNfsRetrans().intValue()); } if (cnx.getNfsTimeo() != null) { storage.setNfsTimeo(cnx.getNfsTimeo().intValue()); } if (cnx.getNfsVersion() != null) { storage.setNfsVersion(StorageDomainMapper.map(cnx.getNfsVersion(), null)); } } }
Source:
public void shouldNotUpdateTimelineEntriesAndEntriesForRollbackUponFailureDuringRetrieval() throws Exception { Object[] pipelineRow1 = {"p1", new BigInteger("1"), new BigInteger("1"), new Date(), "fingerprint", 1.0, "r1", null, new BigInteger("1"), new BigInteger("1")}; Object[] pipelineRow2 = {"p1", "2abcd", new BigInteger("2"), new Date(), "fingerprint", 2.0, "r2", null, new BigInteger("1"), new BigInteger("1")}; stubPipelineInstancesInDb(pipelineRow1, pipelineRow2); ArrayList<PipelineTimelineEntry> tempEntries = new ArrayList<>(); PipelineTimeline pipelineTimeline = new PipelineTimeline(pipelineRepository, transactionTemplate, transactionSynchronizationManager); try { pipelineRepository.updatePipelineTimeline(pipelineTimeline, tempEntries); fail("Should fail to retrieve pipeline."); } catch (ClassCastException e) { assertThat(tempEntries.size(), is(0)); assertThat(pipelineTimeline.instanceCount(new CaseInsensitiveString("p1")), is(0)); } }

Target:
public void shouldNotUpdateTimelineEntriesAndEntriesForRollbackUponFailureDuringRetrieval() throws Exception { Object[] pipelineRow1 = {"p1", new BigInteger("1"), new BigInteger("1"), new Date(), "fingerprint", 1.0, "r1", null, new BigInteger("1"), new BigInteger("1")}; Object[] pipelineRow2 = {"p1", "cause-failure-during-retrieval", new BigInteger("2"), new Date(), "fingerprint", 2.0, "r2", null, new BigInteger("1"), new BigInteger("1")}; stubPipelineInstancesInDb(pipelineRow1, pipelineRow2); ArrayList<PipelineTimelineEntry> tempEntries = new ArrayList<>(); PipelineTimeline pipelineTimeline = new PipelineTimeline(pipelineRepository, transactionTemplate, transactionSynchronizationManager); try { pipelineRepository.updatePipelineTimeline(pipelineTimeline, tempEntries); fail("Should fail to retrieve pipeline."); } catch (ClassCastException e) { assertThat(tempEntries.size(), is(0)); assertThat(pipelineTimeline.instanceCount(new CaseInsensitiveString("p1")), is(0)); } }
Source:
public boolean callAllPartitionProcedure(AllPartitionProcedureCallback callback, String procedureName, Object... params) throws IOException, NoConnectionsException, ProcCallException { Object[] args = new Object[params.length + 1]; System.arraycopy(params, 0, args, 1, params.length); setPartitions(); int partitionCount = m_partitionKeys.size(); PartitionClientResponse[] responses = new PartitionClientResponse[partitionCount]; CountDownLatch responseWaiter = new CountDownLatch(partitionCount); for (int key : m_partitionKeys) { args[0] = key; partitionCount--; PartitionProcedureCallback cb = new PartitionProcedureCallback(responseWaiter, key, partitionCount, responses); if(!callProcedure(cb, procedureName, args)){ return false; } } try { responseWaiter.await(); callback.clientCallback(responses); } catch (Exception e) { throw new IOException (e); } return true; }

Target:
public boolean callAllPartitionProcedure(AllPartitionProcedureCallback callback, String procedureName, Object... params) throws IOException, NoConnectionsException, ProcCallException { if (callback == null) { throw new IOException("AllPartitionProcedureCallback can not be null"); } Object[] args = new Object[params.length + 1]; System.arraycopy(params, 0, args, 1, params.length); int partitionCount = getPartitionIntegerKeys().size(); assert(partitionCount > 0); ClientResponseWithPartitionKey[] responses = new ClientResponseWithPartitionKey[partitionCount]; AtomicInteger counter = new AtomicInteger(partitionCount); for (Integer key : getPartitionIntegerKeys()) { args[0] = key; partitionCount--; OnePartitionProcedureCallback cb = new OnePartitionProcedureCallback(counter, key, partitionCount, responses, callback); try { if (callback instanceof SyncAllPartitionProcedureCallback) { ClientResponse response = callProcedure(procedureName, args); cb.clientCallback(response); } else { if (!callProcedure(cb, procedureName, args)) { cb.clientCallback(null); } } } catch(Exception ex){ try { cb.exceptionCallback(ex); } catch (Exception e) { throw new IOException(e); } } } return true; }
Source:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Mapbox.getInstance(this, getString(R.string.access_token)); setContentView(R.layout.activity_style_line); mapView = findViewById(R.id.mapView); mapView.onCreate(savedInstanceState); mapView.getMapAsync(new OnMapReadyCallback() { @Override public void onMapReady(@NonNull final MapboxMap mapboxMap) { mapboxMap.setStyle(Style.MAPBOX_STREETS, new Style.OnStyleLoaded() { @Override public void onStyleLoaded(@NonNull Style style) { GeoJsonSource linesSource = new GeoJsonSource("lines", loadGeoJsonFromAsset("golden_gate_lines.geojson")); mapboxMap.getStyle().addSource(linesSource); LineLayer linesLayer = new LineLayer("finalLines", "lines").withProperties( PropertyFactory.lineColor( match(get("color"), rgb(0, 0, 0), stop("red", rgb(247, 69, 93)), stop("blue", rgb(51, 201, 235)))), PropertyFactory.visibility(Property.VISIBLE), PropertyFactory.lineWidth(3f) ); mapboxMap.getStyle().addLayer(linesLayer); } }); } }); }

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Mapbox.getInstance(this, getString(R.string.access_token)); setContentView(R.layout.activity_style_line); mapView = findViewById(R.id.mapView); mapView.onCreate(savedInstanceState); mapView.getMapAsync(new OnMapReadyCallback() { @Override public void onMapReady(@NonNull final MapboxMap mapboxMap) { mapboxMap.setStyle(Style.MAPBOX_STREETS, new Style.OnStyleLoaded() { @Override public void onStyleLoaded(@NonNull Style style) { style.addSource(new GeoJsonSource("lines", loadGeoJsonFromAsset("golden_gate_lines.geojson"))); style.addLayer(new LineLayer("finalLines", "lines").withProperties( PropertyFactory.lineColor( match(get("color"), rgb(0, 0, 0), stop("red", rgb(247, 69, 93)), stop("blue", rgb(51, 201, 235)))), PropertyFactory.visibility(Property.VISIBLE), PropertyFactory.lineWidth(3f) )); } }); } }); }
Source:
private UploadItem getUploadItem(UploadableFile uploadableFile, Place place, String source, SimilarImageInterface similarImageInterface) { fileProcessor.initFileDetails(Objects.requireNonNull(uploadableFile.getFilePath()), context.getContentResolver()); UploadableFile.DateTimeWithSource dateTimeWithSource = uploadableFile .getFileCreatedDate(context); long fileCreatedDate = -1; String createdTimestampSource = ""; if (dateTimeWithSource != null) { fileCreatedDate = dateTimeWithSource.getEpochDate(); createdTimestampSource = dateTimeWithSource.getSource(); } Timber.d("File created date is %d", fileCreatedDate); GPSExtractor gpsExtractor = fileProcessor .processFileCoordinates(similarImageInterface, context); UploadItem uploadItem = new UploadItem(uploadableFile.getContentUri(), Uri.parse(uploadableFile.getFilePath()), uploadableFile.getMimeType(context), source, gpsExtractor, place, fileCreatedDate, createdTimestampSource); if (place != null) { uploadItem.title.setTitleText(place.name); if(uploadItem.descriptions.isEmpty()) { uploadItem.descriptions.add(new Description()); } uploadItem.descriptions.get(0).setDescriptionText(place.getLongDescription()); uploadItem.descriptions.get(0).setLanguageCode("en"); } if (!items.contains(uploadItem)) { items.add(uploadItem); } return uploadItem; }

Target:
private UploadItem getUploadItem(UploadableFile uploadableFile, Place place, String source, SimilarImageInterface similarImageInterface) { fileProcessor.initFileDetails(Objects.requireNonNull(uploadableFile.getFilePath()), context.getContentResolver()); UploadableFile.DateTimeWithSource dateTimeWithSource = uploadableFile .getFileCreatedDate(context); long fileCreatedDate = -1; String createdTimestampSource = ""; if (dateTimeWithSource != null) { fileCreatedDate = dateTimeWithSource.getEpochDate(); createdTimestampSource = dateTimeWithSource.getSource(); } Timber.d("File created date is %d", fileCreatedDate); GPSExtractor gpsExtractor = fileProcessor .processFileCoordinates(similarImageInterface, context); UploadItem uploadItem = new UploadItem(uploadableFile.getContentUri(), Uri.parse(uploadableFile.getFilePath()), uploadableFile.getMimeType(context), source, gpsExtractor, place, fileCreatedDate, createdTimestampSource); if (place != null) { uploadItem.title.setTitleText(place.name); uploadItem.descriptions.get(0).setDescriptionText(place.getLongDescription()); uploadItem.descriptions.get(0).setLanguageCode("en"); } if (!items.contains(uploadItem)) { items.add(uploadItem); } return uploadItem; }
Source:
public void privateConstructorTest() { try { WeldContainer container = new Weld().initialize(); } catch (DeploymentException e) { Assert.assertTrue(e.getMessage().contains("Bean class which has decorators should declare at least one non private constructor")); } }

Target:
public void privateConstructorTest() { WeldContainer container = new Weld() .property("org.jboss.weld.construction.relaxed", true) .initialize(); Assert.fail(); }
Source:
private Boolean hasActiveContainerPlacementAction(String processorId) { Optional<ContainerPlacementMetadata> metadata = getPlacementActionMetadata(processorId); if (metadata.isPresent()) { ContainerPlacementMessage.StatusCode actionStatus = metadata.get().getActionStatus(); return (actionStatus == ContainerPlacementMessage.StatusCode.CREATED) || (actionStatus == ContainerPlacementMessage.StatusCode.ACCEPTED) || (actionStatus == ContainerPlacementMessage.StatusCode.IN_PROGRESS); } return false; }

Target:
private boolean hasActiveContainerPlacementAction(String processorId) { Optional<ContainerPlacementMetadata> metadata = getPlacementActionMetadata(processorId); if (metadata.isPresent()) { switch (metadata.get().getActionStatus()) { case ACCEPTED: case CREATED: case IN_PROGRESS: return true; default: return false; } } return false; }
Source:
private <T extends Rule> Set<UniqueSetting> register(RuleRegistry<T> registry, Class<T> ruleType, EObject domainObject, final EObject viewModel) { final Set<UniqueSetting> result = new HashSet<UniqueSetting>(); if (hasRule(ruleType, viewModel)) { final VElement renderable = (VElement) viewModel; @SuppressWarnings("unchecked") final Collection<T> rules = (Collection<T>) getRules(renderable); for (final T rule : rules) { result.addAll(registry.register(renderable, rule, rule.getCondition(), domainObject)); } } return result; }

Target:
private <T extends Rule> Set<UniqueSetting> register(RuleRegistry<T> registry, Class<T> ruleType, EObject domainObject, final EObject viewModel) { final Set<UniqueSetting> result = new HashSet<UniqueSetting>(); if (viewModel instanceof VElement) { final VElement renderable = (VElement) viewModel; final T rule = getRule(ruleType, renderable); if (rule != null) { result.addAll(registry.register(renderable, rule, rule.getCondition(), domainObject)); } } return result; }
Source:
public String getMessageLevel() { return message.getMessageLevel(); }

Target:
public Message.MessageLevel getMessageLevel() { return message.getMessageLevel(); }
Source:
protected RemoteOperationResult run(WebdavClient client) { RemoteOperationResult result = null; int status = -1; GetMethod get = new GetMethod(mUrl + TAG_OCS_ROUTE); Log.d(TAG, "URL ------> " + mUrl + TAG_OCS_ROUTE); get.addRequestHeader(TAG_HEADER_CONTENT, TAG_HEADER_CONTENT_VALUE); get.addRequestHeader(TAG_HEADER_OCS_API, TAG_HEADER_OCS_API_VALUE); get.setRequestHeader(TAG_HEADER_COOKIE, mSessionCookie); try { status = client.executeMethod(get); if(isSuccess(status)) { Log.d(TAG, "Obtain RESPONSE"); String response = get.getResponseBodyAsString(); Log.d(TAG, "GET RESPONSE.................... " + response); JSONObject respJSON = new JSONObject(response); JSONObject respOCS = respJSON.getJSONObject(TAG_OCS); JSONObject respData = respOCS.getJSONObject(TAG_DATA); String id = respData.getString(TAG_ID); String displayName = respData.getString(TAG_DISPLAY_NAME); String email = respData.getString(TAG_EMAIL); result = new RemoteOperationResult(isSuccess(status), status, (get != null ? get.getResponseHeaders() : null)); result.setUserName(displayName); Log.d(TAG, "Response: " + id + " - " + displayName + " - " + email); } } catch (HttpException e) { result = new RemoteOperationResult(e); e.printStackTrace(); } catch (IOException e) { result = new RemoteOperationResult(e); e.printStackTrace(); } catch (JSONException e) { result = new RemoteOperationResult(e); e.printStackTrace(); } finally { get.releaseConnection(); } return result; }

Target:
protected RemoteOperationResult run(WebdavClient client) { RemoteOperationResult result = null; int status = -1; GetMethod get = new GetMethod(client.getBaseUri() + OCS_ROUTE); Log.d(TAG, "URL ------> " + client.getBaseUri() + OCS_ROUTE); get.addRequestHeader(HEADER_OCS_API, HEADER_OCS_API_VALUE); try { status = client.executeMethod(get); if(isSuccess(status)) { Log.d(TAG, "Obtain RESPONSE"); String response = get.getResponseBodyAsString(); Log.d(TAG, "GET RESPONSE.................... " + response); JSONObject respJSON = new JSONObject(response); JSONObject respOCS = respJSON.getJSONObject(NODE_OCS); JSONObject respData = respOCS.getJSONObject(NODE_DATA); String id = respData.getString(NODE_ID); String displayName = respData.getString(NODE_DISPLAY_NAME); String email = respData.getString(NODE_EMAIL); result = new RemoteOperationResult(isSuccess(status), status, (get != null ? get.getResponseHeaders() : null)); mUserName = displayName; Log.d(TAG, "Response: " + id + " - " + displayName + " - " + email); } } catch (HttpException e) { result = new RemoteOperationResult(e); e.printStackTrace(); } catch (IOException e) { result = new RemoteOperationResult(e); e.printStackTrace(); } catch (JSONException e) { result = new RemoteOperationResult(e); e.printStackTrace(); } finally { get.releaseConnection(); } return result; }
Source:
private boolean extractChatStateMUC(Conversation conversation, final MessagePacket packet) { ChatState state = ChatState.parse(packet); Jid FROM=packet.getFrom(); if (state != null && conversation != null) { final Account account = conversation.getAccount(); Jid from = packet.getFrom(); if (from.toBareJid().equals(account.getJid().toBareJid())) { conversation.setOutgoingChatState(state); if (state == ChatState.ACTIVE || state == ChatState.COMPOSING) { mXmppConnectionService.markRead(conversation); activateGracePeriod(account); } return false; } else { if(conversation.getMucOptions().findUserByFullJid(FROM)!=null) conversation.getMucOptions().findUserByFullJid(FROM).setChatState(state); return conversation.setIncomingChatState(state); } } return false; }

Target:
private boolean extractChatStateMUC(Conversation conversation, final MessagePacket packet) { ChatState state = ChatState.parse(packet); Jid FROM=packet.getFrom(); if (state != null && conversation != null) { MucOptions.User user = conversation.getMucOptions().findUserByFullJid(FROM); if(user!=null) { return user.setChatState(state); } } return false; }
Source:
private DiskImage getDiskForVolumeInfo(DiskImage disk) { if (getParameters().getCopyCollapse()) { DiskImage ancestor = DbFacade.getInstance().getDiskImageDao().getAncestor(disk.getImageId()); if (ancestor == null) { log.warnFormat("Can't find ancestor of Disk with ID {0}, using original disk for volume info.", disk.getImageId()); ancestor = disk; } return ancestor; } else { return disk; } }

Target:
private DiskImage getDiskForVolumeInfo(DiskImage disk) { if (getParameters().getCopyCollapse()) { DiskImage ancestor = getDiskImageDao().getAncestor(disk.getImageId()); if (ancestor == null) { log.warnFormat("Can't find ancestor of Disk with ID {0}, using original disk for volume info.", disk.getImageId()); ancestor = disk; } return ancestor; } else { return disk; } }
Source:
public void testDynamicItem_AddOne() { contextRule.createAndRunWorkbench(window); ToolBarManager tbm = getManager(toolBar); assertTrue(tbm.getSize() == 0); MToolItem toolItem1 = ems.createModelElement(MDirectToolItem.class); toolBar.getChildren().add(toolItem1); assertTrue(tbm.getSize() == 1); }

Target:
public void testDynamicItem_AddOne() { contextRule.createAndRunWorkbench(window); ToolBarManager tbm = getManager(toolBar); assertEquals(tbm.getSize(), 0); MToolItem toolItem1 = ems.createModelElement(MDirectToolItem.class); toolBar.getChildren().add(toolItem1); assertEquals(tbm.getSize(), 1); }
Source:
private String removeVisualEditorProgressTag(String originalText) { if (originalText != null && originalText.contains("<progress")) { String regex = "<progress.*?><\\/progress>|<span id=\"img_container.*?>"; return originalText.replaceAll(regex, ""); } else { return originalText; } }

Target:
private String removeVisualEditorProgressTag(String originalText) { if (originalText != null && originalText.contains("<progress")) { String regex = "<progress.*?><\\/progress>|<span id=\"img_container.*? class=\"img_container\" contenteditable=\"false\">"; return originalText.replaceAll(regex, ""); } else { return originalText; } }
Source:
private void initRuleQueryBasedOnVersion(final String version) { if (XPATH_1_0.equals(version)) { xpathRuleQuery = new JaxenXPathRuleQuery(); } else { xpathRuleQuery = new SaxonXPathRuleQuery(); } }

Target:
private void initRuleQueryBasedOnVersion(final String version) { xpathRuleQuery = XPATH_1_0.equals(version) ? new JaxenXPathRuleQuery() : new SaxonXPathRuleQuery(); }
Source:
public Change perform(IProgressMonitor pm) throws CoreException { try { pm.beginTask(getName(), 1); if (makeWrittable) { WriteAccessChecker.setWritable(recource); } else { WriteAccessChecker.setReadable(recource); } return new ResourceAccessChange(recource, false); } finally { pm.done(); } }

Target:
public Change perform(IProgressMonitor pm) throws CoreException { try { pm.beginTask(getName(), 1); if (makeWrittable) { WriteAccessChecker.setWritable(recource, true); return new ResourceAccessChange(recource, false); } else { WriteAccessChecker.setWritable(recource, false); return new ResourceAccessChange(recource, true); } } finally { pm.done(); } }
Source:
public IndexIOConfig( @Deprecated @JsonProperty("firehose") @Nullable FirehoseFactory firehoseFactory, @JsonProperty("inputSource") @Nullable InputSource inputSource, @JsonProperty("inputFormat") @Nullable InputFormat inputFormat, @JsonProperty("appendToExisting") @Nullable Boolean appendToExisting ) { Checks.checkOneNotNullOrEmpty( ImmutableList.of(new Property<>("firehose", firehoseFactory), new Property<>("inputSource", inputSource)) ); if (firehoseFactory != null && inputFormat != null) { throw new IAE("Cannot use firehose and inputFormat together. Try use inputSource instead of firehose."); } this.firehoseFactory = firehoseFactory; this.inputSource = inputSource; this.inputFormat = inputFormat; this.appendToExisting = appendToExisting == null ? DEFAULT_APPEND_TO_EXISTING : appendToExisting; }

Target:
public IndexIOConfig( @Deprecated @JsonProperty("firehose") @Nullable FirehoseFactory firehoseFactory, @JsonProperty("inputSource") @Nullable InputSource inputSource, @JsonProperty("inputFormat") @Nullable InputFormat inputFormat, @JsonProperty("appendToExisting") @Nullable Boolean appendToExisting ) { Checks.checkOneNotNullOrEmpty( ImmutableList.of(new Property<>("firehose", firehoseFactory), new Property<>("inputSource", inputSource)) ); if (firehoseFactory != null && inputFormat != null) { throw new IAE("Cannot use firehose and inputFormat together. Try using inputSource instead of firehose."); } this.firehoseFactory = firehoseFactory; this.inputSource = inputSource; this.inputFormat = inputFormat; this.appendToExisting = appendToExisting == null ? DEFAULT_APPEND_TO_EXISTING : appendToExisting; }
Source:
public ReadOnlyArrayInterface getArray(int index) { return (ReadOnlyArrayInterface) fleeceValueToObject(index); }

Target:
public ReadOnlyArray getArray(int index) { return (ReadOnlyArray) fleeceValueToObject(index); }
Source:
public void testValidateOverlapWithOtherPools( String range1From, String range1To, String range2From, String range2To, boolean overlapping) { MacRange range1 = new MacRange(); range1.setMacFrom(range1From); range1.setMacTo(range1To); MacRange range2 = new MacRange(); range2.setMacFrom(range2From); range2.setMacTo(range2To); PARAM_POOL.setId(Guid.newGuid()); PARAM_POOL.setName("p1"); PARAM_POOL.setRanges(Collections.singletonList(range1)); MacPool macPool2 = new MacPool(); macPool2.setId(Guid.newGuid()); macPool2.setName("p2"); macPool2.setRanges(Collections.singletonList(range2)); when(macPoolDao.getAll()).thenReturn(Collections.singletonList(macPool2)); MacPool oldMacPool = new MacPool(); oldMacPool.setId(Guid.newGuid()); when(macPoolDao.get(any())).thenReturn(oldMacPool); when(macPoolPerCluster.isDuplicateMacAddressesAllowed(any())).thenReturn(false); assertEquals(!overlapping, command.validate()); }

Target:
public void testValidateOverlapWithOtherPools( String range1From, String range1To, String range2From, String range2To, boolean overlapping) { MacRange range1 = new MacRange(); range1.setMacFrom(range1From); range1.setMacTo(range1To); MacRange range2 = new MacRange(); range2.setMacFrom(range2From); range2.setMacTo(range2To); command.getParameters().getMacPool().setId(Guid.newGuid()); command.getParameters().getMacPool().setName("p1"); command.getParameters().getMacPool().setRanges(Collections.singletonList(range1)); MacPool macPool2 = new MacPool(); macPool2.setId(Guid.newGuid()); macPool2.setName("p2"); macPool2.setRanges(Collections.singletonList(range2)); when(macPoolDao.getAll()).thenReturn(Collections.singletonList(macPool2)); MacPool oldMacPool = new MacPool(); oldMacPool.setId(Guid.newGuid()); when(macPoolDao.get(any())).thenReturn(oldMacPool); when(macPoolPerCluster.isDuplicateMacAddressesAllowed(any())).thenReturn(false); assertEquals(!overlapping, command.validate()); }
Source:
private Set<Descriptor> queryStatisticsRegistry() { Set<Descriptor> capabilities = new HashSet<Descriptor>(); Map<String, RegisteredStatistic> registrations = statisticsRegistry.getRegistrations(); for(Entry entry : registrations.entrySet()) { String statisticName = entry.getKey().toString(); RegisteredStatistic registeredStatistic = registrations.get(statisticName); if(registeredStatistic instanceof RegisteredCompoundStatistic) { List<StatisticDescriptor> statistics = new ArrayList<StatisticDescriptor>(); statistics.add(new StatisticDescriptor(entry.getKey() + "Count", StatisticType.COUNTER_HISTORY)); statistics.add(new StatisticDescriptor(entry.getKey() + "Rate", StatisticType.RATE_HISTORY)); statistics.add(new StatisticDescriptor(entry.getKey() + "LatencyMinimum", StatisticType.DURATION_HISTORY)); statistics.add(new StatisticDescriptor(entry.getKey() + "LatencyMaximum", StatisticType.DURATION_HISTORY)); statistics.add(new StatisticDescriptor(entry.getKey() + "LatencyAverage", StatisticType.AVERAGE_HISTORY)); capabilities.addAll(statistics); } else if(registeredStatistic instanceof RegisteredRatioStatistic) { capabilities.add(new StatisticDescriptor(entry.getKey() + "Ratio", StatisticType.RATIO_HISTORY)); } else if(registeredStatistic instanceof RegisteredValueStatistic) { capabilities.add(new StatisticDescriptor(statisticName, statisticName.endsWith("Size") ? StatisticType.SIZE_HISTORY : StatisticType.COUNTER_HISTORY)); } } return capabilities; }

Target:
private Set<Descriptor> queryStatisticsRegistry() { Set<Descriptor> capabilities = new HashSet<Descriptor>(); Map<String, RegisteredStatistic> registrations = statisticsRegistry.getRegistrations(); for(Entry entry : registrations.entrySet()) { String statisticName = entry.getKey().toString(); RegisteredStatistic registeredStatistic = registrations.get(statisticName); if(registeredStatistic instanceof RegisteredCompoundStatistic) { List<StatisticDescriptor> statistics = new ArrayList<StatisticDescriptor>(); statistics.add(new StatisticDescriptor(entry.getKey() + "Count", StatisticType.COUNTER_HISTORY)); statistics.add(new StatisticDescriptor(entry.getKey() + "Rate", StatisticType.RATE_HISTORY)); statistics.add(new StatisticDescriptor(entry.getKey() + "LatencyMinimum", StatisticType.DURATION_HISTORY)); statistics.add(new StatisticDescriptor(entry.getKey() + "LatencyMaximum", StatisticType.DURATION_HISTORY)); statistics.add(new StatisticDescriptor(entry.getKey() + "LatencyAverage", StatisticType.AVERAGE_HISTORY)); capabilities.addAll(statistics); } else if(registeredStatistic instanceof RegisteredRatioStatistic) { capabilities.add(new StatisticDescriptor(entry.getKey() + "Ratio", StatisticType.RATIO_HISTORY)); } else if(registeredStatistic instanceof RegisteredCounterStatistic) { capabilities.add(new StatisticDescriptor(statisticName, StatisticType.COUNTER_HISTORY)); } else if(registeredStatistic instanceof RegisteredSizeStatistic) { capabilities.add(new StatisticDescriptor(statisticName, StatisticType.SIZE_HISTORY)); } } return capabilities; }
Source:
public <T> T[] runRelocateVerificationTest( AggregatorFactory factory, ColumnSelectorFactory selector, Class<T> clazz ) { T[] results = (T[]) Array.newInstance(clazz, 2); BufferAggregator agg = factory.factorizeBuffered(selector); ByteBuffer myBuf = ByteBuffer.allocate(10040902); agg.init(myBuf, 0); agg.aggregate(myBuf, 0); results[0] = (T) agg.get(myBuf, 0); byte[] theBytes = new byte[factory.getMaxIntermediateSize()]; myBuf.get(theBytes); ByteBuffer newBuf = ByteBuffer.allocate(941209); newBuf.position(7574); newBuf.put(theBytes); newBuf.position(0); agg.relocate(0, 7574, newBuf); results[1] = (T) agg.get(newBuf, 7574); return results; }

Target:
public <T> T[] runRelocateVerificationTest( AggregatorFactory factory, ColumnSelectorFactory selector, Class<T> clazz ) { T[] results = (T[]) Array.newInstance(clazz, 2); BufferAggregator agg = factory.factorizeBuffered(selector); ByteBuffer myBuf = ByteBuffer.allocate(10040902); agg.init(myBuf, 0); agg.aggregate(myBuf, 0); results[0] = (T) agg.get(myBuf, 0); byte[] theBytes = new byte[factory.getMaxIntermediateSize()]; myBuf.get(theBytes); ByteBuffer newBuf = ByteBuffer.allocate(941209); newBuf.position(7574); newBuf.put(theBytes); newBuf.position(0); agg.relocate(0, 7574, myBuf, newBuf); results[1] = (T) agg.get(newBuf, 7574); return results; }