auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
long maxArtifactSizeToBytes(EnforcerRuleHelper helper) throws EnforcerRuleException { String convertArtifactSize = maxArtifactSize; if (StringUtils.isEmpty(convertArtifactSize)) { helper .getLog() .info( String.format( "maxArtifactSize property not specified. Using default maxArtifactSize size: %s", DEFAULT_MAX_ARTIFACT_SIZE)); convertArtifactSize = DEFAULT_MAX_ARTIFACT_SIZE; } if (convertArtifactSize.endsWith(BYTES)) { return Long.parseLong(convertArtifactSize.split(BYTES)[0]); } else if (convertArtifactSize.endsWith(KILO_BYTES)) { return (long) (Double.parseDouble(convertArtifactSize.split(KILO_BYTES)[0]) * 1024); } else if (convertArtifactSize.endsWith(MEGA_BYTES)) { return (long) (Double.parseDouble(convertArtifactSize.split(MEGA_BYTES)[0]) * 1024 * 1024); } else { throw new EnforcerRuleException( String.format(UNKNOWN_ARTIFACT_SIZE_UNIT_MSG, BYTES, KILO_BYTES, MEGA_BYTES)); } }

Target:
long maxArtifactSizeToBytes(EnforcerRuleHelper helper) throws EnforcerRuleException { String convertArtifactSize = maxArtifactSize; if (StringUtils.isEmpty(convertArtifactSize)) { helper .getLog() .info( String.format( "maxArtifactSize property not specified. Using default maxArtifactSize size: %s", DEFAULT_MAX_ARTIFACT_SIZE)); convertArtifactSize = DEFAULT_MAX_ARTIFACT_SIZE; } try { return convertInputSize(convertArtifactSize); } catch (NumberFormatException e) { throw new EnforcerRuleException( String.format("Unparsable input size of %s", convertArtifactSize)); } }
Source:
public void testFederateGetResults() throws Exception { List<String> sourceIds = ImmutableList.of("1"); QueryRequest fedQueryRequest = new QueryRequestImpl(mockQuery, false, sourceIds, properties); Source mockSource = mock(Source.class); when(mockSource.getId()).thenReturn("1"); when(mockSource.query(any(QueryRequest.class))).thenReturn(mockResponse); List<Source> sourceList = ImmutableList.of(mockSource, mockSource, mockSource); when(mockResponse.getHits()).thenReturn((long) sourceList.size()); QueryResponse federateResponse = federateStrategy.federate(sourceList, fedQueryRequest); assertThat(federateResponse.getResults().size(), is(sourceList.size())); }

Target:
public void testFederateGetResults() throws Exception { QueryRequest fedQueryRequest = new QueryRequestImpl(mockQuery, false, null, properties); Source mockSource1 = getMockSource(); Source mockSource2 = getMockSource(); Source mockSource3 = getMockSource(); List<Source> sourceList = ImmutableList.of(mockSource1, mockSource2, mockSource3); QueryResponse federateResponse = federateStrategy.federate(sourceList, fedQueryRequest); assertThat(federateResponse.getResults().size(), is(sourceList.size())); }
Source:
public void onVcsRefresh(VcsRefreshEvent event) { JsVectorString branches = pVcsState_.get().getBranchInfo().getBranches().cast(); if (branches.length() != branches_.length()) { branches_ = branches.slice().cast(); menuRebuildRequired_ = true; } for (int i = 0; i < branches.length(); i++) { if (!StringUtil.equals(branches.get(i), branches_.get(i))) { branches_ = branches.slice(); menuRebuildRequired_ = true; break; } } }

Target:
public void onVcsRefresh(VcsRefreshEvent event) { JsVectorString branches = pVcsState_.get().getBranchInfo().getBranches().cast(); if (branches.length() != branches_.length()) { branches_ = branches.slice().cast(); menuRebuildRequired_ = true; return; } for (int i = 0; i < branches.length(); i++) { if (!StringUtil.equals(branches.get(i), branches_.get(i))) { branches_ = branches.slice(); menuRebuildRequired_ = true; return; } } }
Source:
public float op(float origin, float other) { return FastMath.max(origin, other); }

Target:
public float op(float origin, float other) { return origin; }
Source:
private void populateViews() { AnalyticsTracker.track(AnalyticsTracker.Stat.CREATED_ACCOUNT); mEmailAddress = mAccountStore.getAccount().getEmail(); mDisplayName = createDisplayNameFromEmail(); mUsername = !TextUtils.isEmpty(mAccountStore.getAccount().getUserName()) ? mAccountStore.getAccount().getUserName() : createUsernameFromEmail(); mHeaderDisplayName.setText(mDisplayName); mHeaderEmailAddress.setText(mEmailAddress); mEditTextDisplayName.setText(mDisplayName); mEditTextUsername.setText(mUsername); Bundle args = new Bundle(); args.putString(ARG_DISPLAY_NAME, mDisplayName); args.putString(ARG_EMAIL_ADDRESS, mEmailAddress); args.putString(ARG_PHOTO_URL, mPhotoUrl); args.putString(ARG_USERNAME, mUsername); args.putBoolean(ARG_IS_EMAIL_SIGNUP, mIsEmailSignup); setArguments(args); }

Target:
private void populateViews() { mEmailAddress = mAccountStore.getAccount().getEmail(); mDisplayName = createDisplayNameFromEmail(); mUsername = !TextUtils.isEmpty(mAccountStore.getAccount().getUserName()) ? mAccountStore.getAccount().getUserName() : createUsernameFromEmail(); mHeaderDisplayName.setText(mDisplayName); mHeaderEmailAddress.setText(mEmailAddress); mEditTextDisplayName.setText(mDisplayName); mEditTextUsername.setText(mUsername); Bundle args = new Bundle(); args.putString(ARG_DISPLAY_NAME, mDisplayName); args.putString(ARG_EMAIL_ADDRESS, mEmailAddress); args.putString(ARG_PHOTO_URL, mPhotoUrl); args.putString(ARG_USERNAME, mUsername); args.putBoolean(ARG_IS_EMAIL_SIGNUP, mIsEmailSignup); setArguments(args); }
Source:
static private AbstractConfigValue findKeyOrNull(AbstractConfigObject self, String key, ConfigValueType expected, Path originalPath) { AbstractConfigValue v = self.peekAssumingResolved(key, originalPath); if (v == null) throw new ConfigException.Missing(self.origin(), originalPath); if (expected != null) v = DefaultTransformer.transform(v, expected); if (expected != null && (v.valueType() != expected && v.valueType() != ConfigValueType.NULL)) throw new ConfigException.WrongType(v.origin(), originalPath.render(), expected.name(), v.valueType().name()); else return v; }

Target:
static private AbstractConfigValue findKeyOrNull(AbstractConfigObject self, String key, ConfigValueType expected, Path originalPath) { AbstractConfigValue v = self.peekAssumingResolved(key, originalPath); if (v == null) throw new ConfigException.Missing(self.origin(), originalPath.render()); if (expected != null) v = DefaultTransformer.transform(v, expected); if (expected != null && (v.valueType() != expected && v.valueType() != ConfigValueType.NULL)) throw new ConfigException.WrongType(v.origin(), originalPath.render(), expected.name(), v.valueType().name()); else return v; }
Source:
public JsonElement serialize(ITmfStateInterval src, @Nullable Type typeOfSrc, @Nullable JsonSerializationContext context) { JsonObject jsonObject = new JsonObject(); jsonObject.addProperty(TmfIntervalStrings.START, src.getStartTime()); jsonObject.addProperty(TmfIntervalStrings.END, src.getEndTime()); jsonObject.addProperty(TmfIntervalStrings.QUARK, src.getAttribute()); Object value = src.getValue(); if (value == null) { jsonObject.addProperty(TmfIntervalStrings.TYPE, TmfIntervalStrings.NULL); return jsonObject; } if (value.getClass().isInstance(CustomStateValue.class)) { jsonObject.addProperty(TmfIntervalStrings.TYPE, CustomStateValue.class.toString()); } else { jsonObject.addProperty(TmfIntervalStrings.TYPE, value.getClass().getName()); } if (value instanceof CustomStateValue) { CustomStateValue customValue = (CustomStateValue) value; int size = customValue.getSerializedSize(); ByteBuffer buffer = ByteBuffer.allocate(size); buffer.clear(); ISafeByteBufferWriter sbbw = SafeByteBufferFactory.wrapWriter(buffer, size); customValue.serialize(sbbw); byte[] serializedValue = buffer.array(); jsonObject.addProperty(TmfIntervalStrings.VALUE, Base64.getEncoder().encodeToString(serializedValue)); } else if (value instanceof Number) { Number number = (Number) value; jsonObject.addProperty(TmfIntervalStrings.VALUE, number); } else if (value instanceof String) { jsonObject.addProperty(TmfIntervalStrings.VALUE, (String) value); } else { jsonObject.addProperty(TmfIntervalStrings.VALUE, value.toString()); } return jsonObject; }

Target:
public JsonElement serialize(ITmfStateInterval src, @Nullable Type typeOfSrc, @Nullable JsonSerializationContext context) { JsonObject jsonObject = new JsonObject(); jsonObject.addProperty(TmfIntervalStrings.START, src.getStartTime()); jsonObject.addProperty(TmfIntervalStrings.END, src.getEndTime()); jsonObject.addProperty(TmfIntervalStrings.QUARK, src.getAttribute()); Object value = src.getValue(); if (value == null) { jsonObject.addProperty(TmfIntervalStrings.TYPE, TmfIntervalStrings.NULL); return jsonObject; } if (value.getClass().isInstance(CustomStateValue.class)) { jsonObject.addProperty(TmfIntervalStrings.TYPE, CustomStateValue.class.getName()); } else { jsonObject.addProperty(TmfIntervalStrings.TYPE, value.getClass().getName()); } if (value instanceof CustomStateValue) { CustomStateValue customValue = (CustomStateValue) value; int size = customValue.getSerializedSize(); ByteBuffer buffer = ByteBuffer.allocate(size); buffer.clear(); ISafeByteBufferWriter sbbw = SafeByteBufferFactory.wrapWriter(buffer, size); customValue.serialize(sbbw); byte[] serializedValue = buffer.array(); jsonObject.addProperty(TmfIntervalStrings.VALUE, Base64.getEncoder().encodeToString(serializedValue)); } else if (value instanceof Number) { Number number = (Number) value; jsonObject.addProperty(TmfIntervalStrings.VALUE, number); } else if (value instanceof String) { jsonObject.addProperty(TmfIntervalStrings.VALUE, (String) value); } else { jsonObject.addProperty(TmfIntervalStrings.VALUE, value.toString()); } return jsonObject; }
Source:
public File getLogFile() { if (job == null) { return null; } else { return new File(job.getRootDir(), "github-polling.log"); } }

Target:
public File getLogFile() { try { return getLogFileForJob(notNull(job, "Job can't be null!")); } catch (IOException ex) { throw new RuntimeException(ex); } }
Source:
public List<Client> getAllRegisteredNamespaces() { return jdbi.withExtension(SqlitePaxosStateLog.Queries.class, SqlitePaxosStateLog.Queries::getAllNamespaces) .stream() .map(Client::of) .collect(Collectors.toList()); }

Target:
public Set<Client> getAllRegisteredNamespaces() { return jdbi.withExtension(SqlitePaxosStateLog.Queries.class, SqlitePaxosStateLog.Queries::getAllNamespaces) .stream() .map(Client::of) .collect(Collectors.toSet()); }
Source:
public BodyPrint(final Response res) { this.bytes = new IoChecked<>( new Sticky<>( () -> { final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final byte[] buf = new byte[4096]; try (InputStream body = res.body()) { while (true) { final int bts = body.read(buf); if (bts < 0) { break; } baos.write(buf, 0, bts); } } finally { baos.flush(); } return baos.toByteArray(); } ) ); }

Target:
public BodyPrint(final Response res) { this.response = res; }
Source:
protected void executeQueryCommand() { clusterId = getParameters().getClusterId(); if (clusterId == null) { clusterId = volume.getClusterId(); } Guid volumeId = getParameters().getVolumeId(); if (volumeId != null) { volume = getGlusterVolumeDao().getById(volumeId); if (volume == null) { throw new RuntimeException(VdcBllMessages.ACTION_TYPE_FAILED_GLUSTER_VOLUME_INVALID.toString()); } asyncTask = volume.getAsyncTask(); if (asyncTask == null) { getQueryReturnValue().setReturnValue(null); return; } getQueryReturnValue().setReturnValue(fetchTaskStatusDetails()); } }

Target:
protected void executeQueryCommand() { clusterId = getParameters().getClusterId(); Guid volumeId = getParameters().getVolumeId(); if (volumeId != null) { volume = getGlusterVolumeDao().getById(volumeId); if (volume == null) { throw new RuntimeException(VdcBllMessages.ACTION_TYPE_FAILED_GLUSTER_VOLUME_INVALID.toString()); } if (clusterId == null) { clusterId = volume.getClusterId(); } asyncTask = volume.getAsyncTask(); if (asyncTask == null) { getQueryReturnValue().setReturnValue(null); return; } getQueryReturnValue().setReturnValue(fetchTaskStatusDetails()); } }
Source:
public Response revokeSingleToken(@PathParam("accountId") String accountId, JsonNode payload) { JsonNode jsonNode; if (payload == null || (jsonNode = payload.get("token_link")) == null) { return Response.status(BAD_REQUEST).entity(ImmutableMap.of("message","Missing fields: [token_link]")).build(); } Optional<String> revokedDate = authDao.revokeSingleToken(accountId, jsonNode.asText()); if (revokedDate.isPresent()) { return Response.ok(ImmutableMap.of("revoked", revokedDate.get())).build(); } return Response.status(NOT_FOUND).entity(ImmutableMap.of("message","Could not revoke token")).build(); }

Target:
public Response revokeSingleToken(@PathParam("accountId") String accountId, JsonNode payload) { JsonNode jsonNode; if (payload == null || (jsonNode = payload.get("token_link")) == null) { return badRequestResponse(logger, "Missing fields: [token_link]"); } return authDao.revokeSingleToken(accountId, jsonNode.asText()) .map(revokedDate -> ok(ImmutableMap.of("revoked", revokedDate)).build()) .orElseGet(() -> notFoundResponse(logger, "Could not revoke token")); }
Source:
public void testDoubleForEachCacheInjected() { Cache<Double, String> cache = getCache(0); int range = 10; DoubleStream.iterate(0.0, d -> d + .5).limit(10).boxed().forEach(i -> cache.put(i, i + "-value")); assertEquals(range, cache.size()); CacheSet<Map.Entry<Double, String>> entrySet = cache.entrySet(); int cacheOffset = populateNextForEachStructure(cache); int offset = populateNextForEachStructure(new DoubleSummaryStatistics()); try { createStream(entrySet).mapToDouble(toDouble).forEach(new ForEachDoubleInjected(cacheOffset, offset)); DoubleSummaryStatistics stats = getForEachObject(offset); assertEquals(2.25, stats.getAverage()); assertEquals(0.0, stats.getMin()); assertEquals(4.5, stats.getMax()); assertEquals(10, stats.getCount()); assertEquals(22.5, stats.getSum()); } finally { clearForEachObject(cacheOffset); clearForEachObject(offset); } }

Target:
public void testDoubleForEachCacheInjected() { Cache<Double, String> cache = getCache(0); int cacheOffset = populateNextForEachStructure(cache); int offset = populateNextForEachStructure(new DoubleSummaryStatistics()); try { testDoubleOperation(() -> { createStream(cache.entrySet()).mapToDouble(toDouble).forEach(new ForEachDoubleInjected<>(cacheOffset, offset)); return getForEachObject(offset); }, cache); } finally { clearForEachObject(cacheOffset); clearForEachObject(offset); } }
Source:
protected int getCurrentOuterSnapshotVersion() { return version; }

Target:
protected int getCurrentOuterSnapshotVersion() { return VERSION; }
Source:
public static String ensureTopicExists( AmazonSNS amazonSNS, ARN topicARN, AmazonPubsubSubscription subscription) { String createdTopicARN = amazonSNS.createTopic(topicARN.getName()).getTopicArn(); log.debug( (createdTopicARN.equals(topicARN.getArn())) ? "Reusing existing topic {}" : "Created topic {}", createdTopicARN); if (!subscription.getAccountIds().isEmpty()) { amazonSNS.setTopicAttributes( new SetTopicAttributesRequest() .withTopicArn(createdTopicARN) .withAttributeName("Policy") .withAttributeValue( buildSNSPolicy(new ARN(createdTopicARN), subscription.getAccountIds()).toJson())); } return createdTopicARN; }

Target:
public static String ensureTopicExists( AmazonSNS amazonSNS, ARN topicARN, AmazonPubsubSubscription subscription) { String createdTopicARN = retrySupport.retry( () -> amazonSNS.createTopic(topicARN.getName()).getTopicArn(), MAX_RETRIES, RETRY_BACKOFF, EXPONENTIAL); log.debug( (createdTopicARN.equals(topicARN.getArn())) ? "Reusing existing topic {}" : "Created topic {}", createdTopicARN); if (!subscription.getAccountIds().isEmpty()) { amazonSNS.setTopicAttributes( new SetTopicAttributesRequest() .withTopicArn(createdTopicARN) .withAttributeName("Policy") .withAttributeValue( buildSNSPolicy(new ARN(createdTopicARN), subscription.getAccountIds()).toJson())); } return createdTopicARN; }
Source:
public void process() { PerformanceMonitor.startActivity("Render World (Shadow Map)"); shadowMap.bind(); setViewportToSizeOf(shadowMap); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); GL11.glDisable(GL_CULL_FACE); camera.lookThrough(); shadowMapShader.enable(); worldRenderer.renderChunks(renderQueues.chunksOpaqueShadow, ChunkMesh.RenderPhase.OPAQUE, camera, WorldRendererImpl.ChunkRenderMode.SHADOW_MAP); playerCamera.lookThrough(); GL11.glEnable(GL_CULL_FACE); bindDisplay(); PerformanceMonitor.endActivity(); }

Target:
public void process() { this.shadowMap = frameBuffersManager.getFBO("sceneShadowMap"); positionShadowMapCamera(); boolean processCondition = renderingConfig.isDynamicShadows() && worldRenderer.isFirstRenderingStageForCurrentFrame(); if (!processCondition) { return; } PerformanceMonitor.startActivity("Render World (Shadow Map)"); shadowMap.bind(); setViewportToSizeOf(shadowMap); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); GL11.glDisable(GL_CULL_FACE); shadowMapCamera.lookThrough(); shadowMapShader.enable(); worldRenderer.renderChunks(renderQueues.chunksOpaqueShadow, ChunkMesh.RenderPhase.OPAQUE, shadowMapCamera, WorldRendererImpl.ChunkRenderMode.SHADOW_MAP); playerCamera.lookThrough(); GL11.glEnable(GL_CULL_FACE); bindDisplay(); PerformanceMonitor.endActivity(); }
Source:
public void processElement(ProcessContext context) throws Exception { LOG.trace("Persisting {}", Bytes.toString(context.element().getRow())); mutator.mutate(context.element()); }

Target:
public void processElement(ProcessContext context) throws Exception { Mutation mutation = context.element(); if (LOG.isTraceEnabled()) { LOG.trace("Persisting {}", Bytes.toString(mutation.getRow())); } mutator.mutate(mutation); }
Source:
static void verifyMultipleReads(ColumnIndexDirectory columnDirectory, String column, int numIter) throws Exception { for (int ii = 0; ii < numIter; ii++) { PinotDataBuffer buf = ColumnIndexDirectoryTestHelper.getIndexBuffer(columnDirectory, column, ii); int numValues = (int) (buf.size() / 4); for (int j = 0; j < numValues; ++j) { Assert.assertEquals(buf.getInt(j * 4), j, "Inconsistent value at index: " + j); } } }

Target:
static void verifyMultipleReads(ColumnIndexDirectory columnDirectory, String column, int numIter) throws Exception { for (int i = 0; i < numIter; i++) { PinotDataBuffer buf = ColumnIndexDirectoryTestHelper.getIndexBuffer(columnDirectory, column, i); int numValues = (int) (buf.size() / 4); for (int j = 0; j < numValues; ++j) { Assert.assertEquals(buf.getInt(j * 4), j, "Inconsistent value at index: " + j); } } }
Source:
public void run() { if (!partitionStateManager.isInitialized()) { return; } if (!node.getClusterService().getClusterState().isJoinAllowed()) { logger.fine("Will not repair partition table at the moment. " + "Cluster state does not allow new members to join."); return; } Map<Address, Collection<MigrationInfo>> promotions = removeUnknownAddressesAndCollectPromotions(); boolean success = promoteBackupsForMissingOwners(promotions); partitionServiceLock.lock(); try { if (success) { if (logger.isFinestEnabled()) { logger.finest("RepartitioningTask scheduled"); } migrationQueue.add(new RepartitioningTask()); } else { triggerControlTask(); } } finally { partitionServiceLock.unlock(); } }

Target:
public void run() { if (!partitionStateManager.isInitialized()) { return; } ClusterState clusterState = node.getClusterService().getClusterState(); if (!clusterState.isMigrationAllowed() && !clusterState.isPartitionPromotionAllowed()) { logger.fine("Will not repair partition table at the moment. " + "Cluster state does not allow to modify partition table."); return; } Map<Address, Collection<MigrationInfo>> promotions = removeUnknownAddressesAndCollectPromotions(); boolean success = promoteBackupsForMissingOwners(promotions); partitionServiceLock.lock(); try { if (success) { if (logger.isFinestEnabled()) { logger.finest("RepartitioningTask scheduled"); } migrationQueue.add(new RepartitioningTask()); } else { triggerControlTask(); } } finally { partitionServiceLock.unlock(); } }
Source:
@Override protected void writeExternalData(ObjectOutput out) throws IOException { throw new RuntimeException("TODO"); }

Target:
@Override protected void writeExternalData(ObjectOutput out) throws IOException { out.writeObject(topVer); U.writeCollection(out, assignment); U.writeMap(out, primary); U.writeMap(out, backup); }
Source:
private static void clear() { flush(BriefcasePreferences.appScoped()); Stream.of( PullTransferPanel.class, PushTransferPanel.class, PullPanel.class, PushPanel.class, ExportPanel.class ).map(BriefcasePreferences::forClass) .forEach(ClearPreferences::flush); }

Target:
private static void clear() { flush(BriefcasePreferences.appScoped()); Stream.of( PullPanel.class, PushPanel.class, ExportPanel.class ).map(BriefcasePreferences::forClass) .forEach(ClearPreferences::flush); }
Source:
public <T extends Action> List<T> getActions(Class<T> type) { List<T> _actions = Util.filter(getPersistedActions(), type); for (TransientActionFactory<?> taf : TransientActionFactory.factoriesFor(getClass(), type)) { _actions.addAll(Util.filter(createFor(taf), type)); } return Collections.unmodifiableList(_actions); }

Target:
public <T extends Action> List<T> getActions(Class<T> type) { List<T> _actions = Util.filter(getActions(), type); for (TransientActionFactory<?> taf : TransientActionFactory.factoriesFor(getClass(), type)) { _actions.addAll(Util.filter(createFor(taf), type)); } return Collections.unmodifiableList(_actions); }
Source:
private String attributeKeyFrom(String key) { String formattedAttribute = Stream.of(key.split("\\.")) .map(part -> Stream.of(part.split("-")).collect(Collectors.joining(" "))) .collect(Collectors.joining(" ")); return WordUtils.capitalize(formattedAttribute); }

Target:
private String attributeKeyFrom(String key) { String formattedAttribute = Stream.of(key.split("\\.")) .map(part -> part.replaceAll("-", " ")) .collect(Collectors.joining(" ")); return WordUtils.capitalize(formattedAttribute); }
Source:
public static void setUpConfiguration() { projectId = TestHelper.getTestProperty(PROJECT_ID_KEY); instanceId = TestHelper.getTestProperty(INSTANCE_ID_KEY); gcsPath = TestHelper.getTestProperty("google.dataflow.gcsPath"); gcsWorkDir = gcsPath + "/" + UUID.randomUUID().toString(); stagingLocation = gcsWorkDir + "/staging"; tempLocation = gcsWorkDir + "/temp"; }

Target:
public static void setUpConfiguration() { projectId = TestHelper.getTestProperty(PROJECT_ID_KEY); instanceId = TestHelper.getTestProperty(INSTANCE_ID_KEY); gcsPath = TestHelper.getTestProperty("google.bigtable.dataflow.gcsPath"); gcsWorkDir = gcsPath + "/" + UUID.randomUUID().toString(); stagingLocation = gcsWorkDir + "/staging"; tempLocation = gcsWorkDir + "/temp"; }
Source:
private boolean checkJoinGroupNode(StaticAnalysis sa, JoinGroupNode node, Set<IVariable<?>> projectedVars) { AtomicBoolean res = new AtomicBoolean(); node.forEach(child -> { res.compareAndSet(false, checkIfNodeProducesVars(sa, child, projectedVars)); }); return res.get(); }

Target:
private boolean checkJoinGroupNode(StaticAnalysis sa, JoinGroupNode node, Set<IVariable<?>> projectedVars) { AtomicBoolean res = new AtomicBoolean(); node.forEach(child -> res.compareAndSet(false, checkIfNodeProducesVars(sa, child, projectedVars))); return res.get(); }
Source:
public static void readFromNBT(NBTTagCompound nbt, String str, IInventory inventory) { NBTTagList var2 = nbt.getTagList(str, 10); for (int var3 = 0; var3 < var2.tagCount(); ++var3) { NBTTagCompound var4 = (NBTTagCompound) var2.getCompoundTagAt(var3); int var5 = var4.getByte("Slot") & 255; if (var5 >= 0 && var5 < inventory.getSizeInventory()) { inventory.setInventorySlotContents(var5, ItemStack.loadItemStackFromNBT(var4)); } } }

Target:
public static void readFromNBT(NBTTagCompound nbt, String str, IInventory inventory) { NBTTagList var2 = nbt.getTagList(str, 10); for (int var3 = 0; var3 < var2.tagCount(); ++var3) { NBTTagCompound var4 = (NBTTagCompound) var2.getCompoundTagAt(var3); int var5 = var4.getByte("Slot") & 255; if (var5 < inventory.getSizeInventory()) { inventory.setInventorySlotContents(var5, new ItemStack(var4)); } } }
Source:
public List<SinkRecord> flush() throws SQLException { if (records.isEmpty()) { log.debug("Records is empty"); return new ArrayList<>(); } log.debug("Flushing Buffered Records", records.size()); for (SinkRecord record : records) { preparedStatementBinder.bindRecord(record); } int totalUpdateCount = 0; boolean successNoInfo = false; for (int updateCount : preparedStatement.executeBatch()) { if (updateCount == Statement.SUCCESS_NO_INFO) { successNoInfo = true; continue; } totalUpdateCount += updateCount; } if (totalUpdateCount != records.size() && !successNoInfo) { switch (config.insertMode) { case INSERT: throw new ConnectException(String.format( "Update count (%d) did not sum up to total number of records inserted (%d)", totalUpdateCount, records.size() )); case UPSERT: case UPDATE: log.debug( "{} records:{} resulting in in totalUpdateCount:{}", config.insertMode, records.size(), totalUpdateCount ); break; default: throw new ConnectException("Unknown insert mode: " + config.insertMode); } } if (successNoInfo) { log.info( "{} records:{} , but no count of the number of rows it affected is available", config.insertMode, records.size() ); } final List<SinkRecord> flushedRecords = records; records = new ArrayList<>(); return flushedRecords; }

Target:
public List<SinkRecord> flush() throws SQLException { if (records.isEmpty()) { log.debug("Records is empty"); return new ArrayList<>(); } log.debug("Flushing buffered records", records.size()); for (SinkRecord record : records) { preparedStatementBinder.bindRecord(record); } int totalUpdateCount = 0; boolean successNoInfo = false; for (int updateCount : preparedStatement.executeBatch()) { if (updateCount == Statement.SUCCESS_NO_INFO) { successNoInfo = true; continue; } totalUpdateCount += updateCount; } if (totalUpdateCount != records.size() && !successNoInfo) { switch (config.insertMode) { case INSERT: throw new ConnectException(String.format( "Update count (%d) did not sum up to total number of records inserted (%d)", totalUpdateCount, records.size() )); case UPSERT: case UPDATE: log.debug( "{} records:{} resulting in in totalUpdateCount:{}", config.insertMode, records.size(), totalUpdateCount ); break; default: throw new ConnectException("Unknown insert mode: " + config.insertMode); } } if (successNoInfo) { log.info( "{} records:{} , but no count of the number of rows it affected is available", config.insertMode, records.size() ); } final List<SinkRecord> flushedRecords = records; records = new ArrayList<>(); return flushedRecords; }
Source:
private EmailWrapper getEmailToStudent(StudentAttributes student, List<EmailWrapper> emailsSent) { for (EmailWrapper email : emailsSent) { boolean emailSentToThisStudent = email.getFirstRecipient().equalsIgnoreCase(student.email); if (emailSentToThisStudent) { return email; } } return null; }

Target:
private EmailWrapper getEmailToStudent(StudentAttributes student, List<EmailWrapper> emailsSent) { for (EmailWrapper email : emailsSent) { boolean isEmailSentToThisStudent = email.getFirstRecipient().equalsIgnoreCase(student.email); if (isEmailSentToThisStudent) { return email; } } return null; }
Source:
public void shouldAddDifferentEntryIntoList() throws Exception { operation.xpath = "lists:double"; operation.value = 1.0; operation.run(doc); operation.value = 2.0; operation.run(doc); Double[] doubleValues = (Double[]) doc.getPropertyValue("lists:double"); assertEquals(2, doubleValues.length); assertEquals(1.0, doubleValues[0]); assertEquals(2.0, doubleValues[1]); operation.xpath = "lists:boolean"; operation.value = true; operation.run(doc); operation.value = false; operation.run(doc); Boolean[] booleanValues = (Boolean[]) doc.getPropertyValue("lists:boolean"); assertEquals(2, booleanValues.length); assertEquals(Boolean.TRUE, booleanValues[0]); assertEquals(Boolean.FALSE, booleanValues[1]); operation.xpath = "lists:integer"; operation.value = 1; operation.run(doc); operation.value = 2; operation.run(doc); Long[] longValues = (Long[]) doc.getPropertyValue("lists:integer"); assertEquals(2, longValues.length); assertEquals(Long.valueOf(1), longValues[0]); assertEquals(Long.valueOf(2), longValues[1]); operation.xpath = "lists:date"; Calendar now1 = Calendar.getInstance(); sleep(1); Calendar now2 = Calendar.getInstance(); operation.value = now1; operation.run(doc); operation.value = now2; operation.run(doc); Calendar[] dateValues = (Calendar[]) doc.getPropertyValue("lists:date"); assertEquals(2, dateValues.length); assertEquals(now1, dateValues[0]); assertEquals(now2, dateValues[1]); }

Target:
public void shouldAddDifferentEntryIntoList() throws Exception { operation.xpath = "lists:double"; operation.value = 1.0; operation.run(doc); operation.value = 2.0; operation.run(doc); Double[] doubleValues = (Double[]) doc.getPropertyValue("lists:double"); assertEquals(2, doubleValues.length); assertEquals(1.0, doubleValues[0]); assertEquals(2.0, doubleValues[1]); operation.xpath = "lists:boolean"; operation.value = true; operation.run(doc); operation.value = false; operation.run(doc); Boolean[] booleanValues = (Boolean[]) doc.getPropertyValue("lists:boolean"); assertEquals(2, booleanValues.length); assertEquals(Boolean.TRUE, booleanValues[0]); assertEquals(Boolean.FALSE, booleanValues[1]); operation.xpath = "lists:integer"; operation.value = 1; operation.run(doc); operation.value = 2; operation.run(doc); Long[] longValues = (Long[]) doc.getPropertyValue("lists:integer"); assertEquals(2, longValues.length); assertEquals(Long.valueOf(1), longValues[0]); assertEquals(Long.valueOf(2), longValues[1]); operation.xpath = "lists:date"; Calendar now1 = Calendar.getInstance(); Thread.sleep(10); Calendar now2 = Calendar.getInstance(); operation.value = now1; operation.run(doc); operation.value = now2; operation.run(doc); Calendar[] dateValues = (Calendar[]) doc.getPropertyValue("lists:date"); assertEquals(2, dateValues.length); assertEquals(now1, dateValues[0]); assertEquals(now2, dateValues[1]); }
Source:
private synchronized void scheduleSuggesterIndexBuild() throws PluginExecutionException { if (future != null) { future.cancel(false); } try { future = executor.schedule(buildSuggesterIndex, 1, TimeUnit.MINUTES); } catch (RejectedExecutionException e) { LOGGER.info( "The offline gazetteer's suggester index could not be built automatically. It may have " + "to be built manually with the 'gazetteer:build-suggester-index' command."); throw new PluginExecutionException(e); } }

Target:
private synchronized void scheduleSuggesterIndexBuild() throws PluginExecutionException { if (future != null) { future.cancel(false); } try { future = executor.schedule(buildSuggesterIndex, 1, TimeUnit.MINUTES); } catch (RejectedExecutionException e) { LOGGER.warn( "The offline gazetteer's suggester index could not be built automatically. It may have " + "to be built manually with the 'gazetteer:build-suggester-index' command."); throw new PluginExecutionException(e); } }
Source:
public void start(ServiceProvider<Service> serviceProvider) { LOGGER.debug("Starting service"); CacheManagerProviderService cacheManagerProviderService = serviceProvider.getService(CacheManagerProviderService.class); if (cacheManagerProviderService != null) { cacheManager = cacheManagerProviderService.getCacheManager(); cacheManager.registerListener(this); } started = true; }

Target:
public void start(ServiceProvider<Service> serviceProvider) { LOGGER.debug("Starting service"); CacheManagerProviderService cacheManagerProviderService = serviceProvider.getService(CacheManagerProviderService.class); cacheManager = cacheManagerProviderService.getCacheManager(); cacheManager.registerListener(this); }
Source:
public String getUuid() { return this.getIdentifierType().getUuid(); }

Target:
public String getUuid() { return this.getId().toString(); }
Source:
public void testInitWithClassesAndNoSchema() throws Exception { System.out.println("Creating a .jar file using all of the classes associated with this test."); InMemoryJarfile originalInMemoryJar = new InMemoryJarfile(); VoltCompiler compiler = new VoltCompiler(false, false); ClassPath classpath = ClassPath.from(this.getClass().getClassLoader()); String packageName = "org.voltdb_testprocs.fakeusecase.greetings"; int classesFound = 0; for (ClassInfo myclass : classpath.getTopLevelClassesRecursive(packageName)) { compiler.addClassToJar(originalInMemoryJar, myclass.load()); classesFound++; } assertEquals(5, classesFound); System.out.println("Writing " + classesFound + " classes to jar file"); File classesJarfile = File.createTempFile("TestInitStartWithClasses-procedures", ".jar"); classesJarfile.deleteOnExit(); originalInMemoryJar.writeToFile(classesJarfile); Configuration c1 = new Configuration( new String[]{"initialize", "voltdbroot", rootDH.getPath(), "force", "classes", classesJarfile.getPath()}); ServerThread server = new ServerThread(c1); server.setUncaughtExceptionHandler(handleUncaught); server.start(); server.join(); validateStagedCatalog(null, originalInMemoryJar); }

Target:
public void testInitWithClassesAndNoSchema() throws Exception { System.out.println("Creating a .jar file using all of the classes associated with this test."); InMemoryJarfile originalInMemoryJar = new InMemoryJarfile(); VoltCompiler compiler = new VoltCompiler(false, false); ClassPath classpath = ClassPath.from(this.getClass().getClassLoader()); String packageName = "org.voltdb_testprocs.fakeusecase.greetings"; int classesFound = 0; for (ClassInfo myclass : classpath.getTopLevelClassesRecursive(packageName)) { compiler.addClassToJar(originalInMemoryJar, myclass.load()); classesFound++; } assertEquals(5, classesFound); System.out.println("Writing " + classesFound + " classes to jar file"); File classesJarfile = File.createTempFile("TestInitStartWithClassesNoSchema-procedures", ".jar"); classesJarfile.deleteOnExit(); originalInMemoryJar.writeToFile(classesJarfile); Configuration c1 = new Configuration( new String[]{"initialize", "voltdbroot", rootDH.getPath(), "force", "classes", classesJarfile.getPath()}); ServerThread server = new ServerThread(c1); server.setUncaughtExceptionHandler(handleUncaught); server.start(); server.join(); validateStagedCatalog(null, originalInMemoryJar); }
Source:
private static List<? extends PerturbationMapping<?>> createMappingsForAllCombinations( List<? extends PerturbationMapping<?>> mappings) { int count = countScenarios(mappings, true); return IntStream.range(0, mappings.size()).boxed() .map(i -> multiplyPerturbations(mappings.get(i), count, i)) .collect(toImmutableList()); }

Target:
private static List<? extends PerturbationMapping<?>> createMappingsForAllCombinations( List<? extends PerturbationMapping<?>> mappings) { int count = countScenarios(mappings, true); return Seq.seq(mappings) .zipWithIndex() .map(tp -> multiplyPerturbations(tp.v1, count, tp.v2.intValue())) .collect(toImmutableList()); }
Source:
public void shouldNotLogMessageAsInfo() { logFeature.setLevel(DEPRECATED_LOGGER, "FATAL"); System.setProperty(Framework.NUXEO_DEV_SYSTEM_PROP, "false"); logDeprecatedMessageAndVerify(false); }

Target:
public void shouldNotLogMessageAsInfo() { logDeprecatedMessageAndVerify(false); }
Source:
public void setZoom(int mapzoom) { mapController.setZoom(mapzoom > maxZoomLevel ? maxZoomLevel : mapzoom); }

Target:
public void setZoom(int mapzoom) { mapController.setZoom(Math.min(mapzoom, maxZoomLevel)); }
Source:
private void deployApplications() throws MojoFailureException { log.info("Deploying application [" + application + "]"); try { mule.deploy(application.getAbsolutePath()); } catch (MuleControllerException e) { log.error("Couldn't deploy application: " + application + ". Check Mule Runtime logs"); } }

Target:
private void deployApplications() throws DeploymentException { log.info("Deploying application [" + application + "]"); try { mule.deploy(application.getAbsolutePath()); } catch (MuleControllerException e) { throw new DeploymentException("Couldn't deploy application: " + application + ". Check Mule Runtime logs"); } }
Source:
private List<String> parsePoints(Element testcase) { List<String> points = new ArrayList<>(); NodeList messages = testcase.getElementsByTagName("Message"); for (int i = 0; i < messages.getLength(); i++) { Element message = (Element) messages.item(i); Element desc = (Element) message.getElementsByTagName("Description").item(0); String text = desc.getTextContent(); if (text.matches("^(TMC:.*)")) { String[] split = text.split("\\."); points.add(split[1]); } } return points; }

Target:
private List<String> parsePoints(Element testcase) { List<String> points = new ArrayList<>(); NodeList messages = testcase.getElementsByTagName("Message"); for (int i = 0; i < messages.getLength(); i++) { Element message = (Element) messages.item(i); Element desc = (Element) message.getElementsByTagName("Description").item(0); String text = desc.getTextContent(); if (text.matches("^(TMC:.*)")) { String result = text.substring(text.indexOf(".") + 1); points.add(result); } } return points; }
Source:
static Collection<Field> collectInjectedFields(Class<?> clazz) { return collectNonStaticFieldsWithAnnotation(clazz, Inject.class, false); }

Target:
static Collection<Field> collectInjectedFields(Class<?> clazz) { return collectNonStaticFieldsWithAnnotation(clazz, InjectBean.class, false); }
Source:
public void register(Member member) throws Exception { Search.getFullTextEntityManager(em).persist(member); initNewMember(); }

Target:
public void register(Member member) throws Exception { em.persist(member); initNewMember(); }
Source:
private void saveMedications( @Nonnull final XWikiDocument docX, @Nonnull final Patient patient, @Nonnull final PatientData<Medication> medications, @Nonnull final PatientWritePolicy policy, @Nonnull final XWikiContext context) { final Stream<Medication> medsStream; if (PatientWritePolicy.MERGE.equals(policy)) { final PatientData<Medication> storedMedications = load(patient); medsStream = storedMedications != null ? buildMergedMedicationsMap(medications, storedMedications).entrySet().stream() .flatMap(mapEntry -> mapEntry.getValue().stream()) : StreamSupport.stream(medications.spliterator(), false) .filter(Objects::nonNull); docX.removeXObjects(Medication.CLASS_REFERENCE); } else { medsStream = StreamSupport.stream(medications.spliterator(), false) .filter(Objects::nonNull); docX.removeXObjects(Medication.CLASS_REFERENCE); } medsStream.forEach(medication -> saveMedication(docX, medication, context)); }

Target:
private void saveMedications( @Nonnull final XWikiDocument docX, @Nonnull final Patient patient, @Nonnull final PatientData<Medication> medications, @Nonnull final PatientWritePolicy policy, @Nonnull final XWikiContext context) { final Stream<Medication> medsStream; if (PatientWritePolicy.MERGE.equals(policy)) { final PatientData<Medication> storedMedications = load(patient); medsStream = storedMedications != null ? buildMergedMedicationsMap(medications, storedMedications).entrySet().stream() .flatMap(mapEntry -> mapEntry.getValue().stream()) : StreamSupport.stream(medications.spliterator(), false) .filter(Objects::nonNull); } else { medsStream = StreamSupport.stream(medications.spliterator(), false) .filter(Objects::nonNull); } docX.removeXObjects(Medication.CLASS_REFERENCE); medsStream.forEach(medication -> saveMedication(docX, medication, context)); }
Source:
public void postGen(World world, Random rand, BlockPos pos) { if(isGoodBiome(world.getBiome(pos))) { Blocks.FIRE.setFireInfo(world.getBlockState(pos).getBlock(), 5, 5); } }

Target:
public void postGen(World world, Random rand, BlockPos pos)
Source:
protected static boolean hasDefaultClause(SwitchStatementTree switchStatement) { return switchStatement.cases().stream() .anyMatch(caseGroupTree -> caseGroupTree.labels().stream() .anyMatch(caseLabelTree -> caseLabelTree.caseOrDefaultKeyword().text().equals("default"))); }

Target:
protected static boolean hasDefaultClause(SwitchStatementTree switchStatement) { return switchStatement.cases().stream() .flatMap(caseGroupTree -> caseGroupTree.labels().stream()) .anyMatch(caseLabelTree -> caseLabelTree.caseOrDefaultKeyword().text().equals("default")); }
Source:
private void deleteAsyncQuery() { AsyncDbUtil asyncDbUtil = AsyncDbUtil.getInstance(elide); Iterable<Object> loaded = (Iterable<Object>) asyncDbUtil.executeInTransaction(elide.getDataStore(), (tx, scope) -> { try { EntityDictionary dictionary = elide.getElideSettings().getDictionary(); RSQLFilterDialect filterParser = new RSQLFilterDialect(dictionary); Calendar cal = Calendar.getInstance(); cal.setTime(new Date()); cal.add(Calendar.DATE, -(queryCleanupDays)); Date cleanupDate = cal.getTime(); Format dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'"); String cleanupDateFormatted = dateFormat.format(cleanupDate); log.debug("cleanupDateFormatted = {}", cleanupDateFormatted); FilterExpression filter = filterParser.parseFilterExpression("createdOn=le='" + cleanupDateFormatted + "'", AsyncQuery.class, false); log.debug("filter = {}", filter.toString()); EntityProjection asyncQueryCollection = EntityProjection.builder() .type(AsyncQuery.class) .filterExpression(filter) .build(); Iterable<Object> loadedObjects = tx.loadObjects(asyncQueryCollection, scope); return loadedObjects; } catch (Exception e) { log.error("Exception: {}", e.getMessage()); } return null; }); Iterator<Object> itr = loaded.iterator(); while(itr.hasNext()) { AsyncQuery query = (AsyncQuery) itr.next(); log.info("Found a query to DELETE"); asyncDbUtil.deleteAsyncQueryAndResult(query.getId()); } }

Target:
private void deleteAsyncQuery() { String cleanupDateFormatted = evaluateFormattedFilterDate(Calendar.DATE, queryCleanupDays); String filterExpression = "createdOn=le='" + cleanupDateFormatted + "'"; asyncQueryDao.deleteAsyncQueryAndResultCollection(filterExpression); }
Source:
protected String getHumanFriendlyText(String location) { JsonNode swaggerSchemaNode = findNode(location); if (swaggerSchemaNode == null) { return location; } JsonNode title = swaggerSchemaNode.get("title"); if (title != null) { return title.asText(); } JsonNode description = swaggerSchemaNode.get("title"); if (description != null) { return description.asText(); } JsonNode ref = swaggerSchemaNode.get("$ref"); if (ref != null) { return ref.asText().substring(ref.asText().lastIndexOf("/") + 1); } return location; }

Target:
protected String getHumanFriendlyText(String location) { JsonNode swaggerSchemaNode = findNode(location); if (swaggerSchemaNode == null) { return location; } JsonNode title = swaggerSchemaNode.get("title"); if (title != null) { return title.asText(); } JsonNode ref = swaggerSchemaNode.get("$ref"); if (ref != null) { return ref.asText().substring(ref.asText().lastIndexOf("/") + 1); } return location; }
Source:
FileEntry(String name, String href, long lastModified, int size, List<FileEntry> subdirs) { this.name = name; this.href = href; this.lastModified = lastModified; this.size = size; this.subdirs = subdirs; }

Target:
private FileEntry(String name, String href, long lastModified, int size, List<FileEntry> subdirs) { this(); this.name = name; this.href = href; this.lastModified = lastModified; this.size = size; this.subdirs = subdirs; }
Source:
public void testThreadsKilledClientClose() throws Exception { int preNumClientReaper = 0; Map<Thread, StackTraceElement[]> preStMap = Thread.getAllStackTraces(); for (Thread t : preStMap.keySet()) { if (t.getName().contains("VoltDB Client Reaper Thread")) { preNumClientReaper++; } } ClientConfig config = new ClientConfig(); Client client = ClientFactory.createClient(config); client.createConnection("localhost"); client.close(); Thread.sleep(2000); Map<Thread, StackTraceElement[]> stMap = Thread.getAllStackTraces(); int postNumClientReaper = 0; for (Entry<Thread, StackTraceElement[]> e : stMap.entrySet()) { Thread t = e.getKey(); StackTraceElement[] st = e.getValue(); if (t == Thread.currentThread()) { continue; } String threadName = t.getName(); if (threadName.contains("VoltDB Client Reaper Thread")) { postNumClientReaper++; } if (threadName.contains("Reverse DNS lookups") || threadName.contains("Async Logger")) { System.out.println("threadName: " + threadName); for (StackTraceElement element : st) { System.out.println("stack trace element: " + element); } fail("Something failed to clean up."); } } System.out.println("preNumClientReaper : " + preNumClientReaper); System.out.println("postNumClientReaper : " + postNumClientReaper); if (preNumClientReaper != postNumClientReaper) { fail("Something failed to clean up. ClientReaper"); } }

Target:
public void testThreadsKilledClientClose() throws Exception { int preNumClientReaper = 0; Map<Thread, StackTraceElement[]> preStMap = Thread.getAllStackTraces(); for (Thread t : preStMap.keySet()) { if (t.getName().contains("VoltDB Client Reaper Thread")) { preNumClientReaper++; } } ClientConfig config = new ClientConfig(); Client client = ClientFactory.createClient(config); client.createConnection("localhost"); client.close(); ClientFactory.decreaseClientNum(); Thread.sleep(2000); Map<Thread, StackTraceElement[]> stMap = Thread.getAllStackTraces(); int postNumClientReaper = 0; for (Entry<Thread, StackTraceElement[]> e : stMap.entrySet()) { Thread t = e.getKey(); if (t == Thread.currentThread()) { continue; } String threadName = t.getName(); if (threadName.contains("VoltDB Client Reaper Thread")) { postNumClientReaper++; } assertFalse(threadName.contains("Reverse DNS lookups") || threadName.contains("Async Logger") || threadName.contains("Estimated Time Updater")); } assertEquals(preNumClientReaper, postNumClientReaper); }
Source:
public void countTest() throws Exception { sendManagementCallOnClientToCollectStats(); Cache<String, String> cache = cacheManager.getCache("dedicated-cache-1", String.class, String.class); cache.put("one", "val1"); cache.put("two", "val2"); cache.get("one"); cache.get("two"); cache.get("three"); cache.get("four"); long cacheHitCount = 0; long clusteredHitCount = 0; long cacheMissCount = 0; long clusteredMissCount = 0; do { List<ContextualStatistics> stats = waitForNextStats(); for (ContextualStatistics stat : stats) { if (stat.getContext().contains("cacheName") && stat.getContext().get("cacheName").equals("dedicated-cache-1")) { System.out.println("stats:"); for (Map.Entry<String, Statistic<?, ?>> entry : stat.getStatistics().entrySet()) { System.out.println(" - " + entry.getKey() + " : " + entry.getValue()); } cacheHitCount = stat.getStatistic(Counter.class, "Cache:HitCount").getValue(); clusteredHitCount = stat.getStatistic(Counter.class, "Clustered:HitCount").getValue(); clusteredMissCount = stat.getStatistic(Counter.class, "Clustered:MissCount").getValue(); cacheMissCount = stat.getStatistic(Counter.class, "Cache:MissCount").getValue(); } } } while(!Thread.currentThread().isInterrupted() && (cacheHitCount != CACHE_HIT_COUNT) && (clusteredHitCount != CLUSTERED_HIT_COUNT) && (cacheMissCount != CACHE_MISS_COUNT) && (clusteredMissCount != CLUSTERED_MISS_COUNT)); Assert.assertThat(cacheHitCount,is(CACHE_HIT_COUNT)); Assert.assertThat(clusteredHitCount,is(CLUSTERED_HIT_COUNT)); Assert.assertThat(cacheMissCount,is(CACHE_MISS_COUNT)); Assert.assertThat(clusteredMissCount,is(CLUSTERED_MISS_COUNT)); }

Target:
public void countTest() throws Exception { sendManagementCallOnClientToCollectStats(); Cache<String, String> cache = cacheManager.getCache("dedicated-cache-1", String.class, String.class); cache.put("one", "val1"); cache.put("two", "val2"); cache.get("one"); cache.get("two"); cache.get("three"); cache.get("four"); long cacheHitCount = 0; long clusteredHitCount = 0; long cacheMissCount = 0; long clusteredMissCount = 0; do { List<ContextualStatistics> stats = waitForNextStats(); for (ContextualStatistics stat : stats) { if (stat.getContext().contains("cacheName") && stat.getContext().get("cacheName").equals("dedicated-cache-1")) { cacheHitCount = stat.getStatistic(Counter.class, "Cache:HitCount").getValue(); clusteredHitCount = stat.getStatistic(Counter.class, "Clustered:HitCount").getValue(); clusteredMissCount = stat.getStatistic(Counter.class, "Clustered:MissCount").getValue(); cacheMissCount = stat.getStatistic(Counter.class, "Cache:MissCount").getValue(); } } } while(!Thread.currentThread().isInterrupted() && (cacheHitCount != CACHE_HIT_COUNT) && (clusteredHitCount != CLUSTERED_HIT_COUNT) && (cacheMissCount != CACHE_MISS_COUNT) && (clusteredMissCount != CLUSTERED_MISS_COUNT)); Assert.assertThat(cacheHitCount,is(CACHE_HIT_COUNT)); Assert.assertThat(clusteredHitCount,is(CLUSTERED_HIT_COUNT)); Assert.assertThat(cacheMissCount,is(CACHE_MISS_COUNT)); Assert.assertThat(clusteredMissCount,is(CLUSTERED_MISS_COUNT)); }