auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public EncodedDoubleValue(String name, int shift, int bits, double factor, long defaultValue, int maxValue, boolean allowZero) { super(name, shift, bits, factor, defaultValue, maxValue, allowZero); double factorDivision = maxValue / factor; if (factorDivision != (int) factorDivision) { throw new IllegalStateException("MaxValue needs to be divideable by factor without remainder"); } }

Target:
public EncodedDoubleValue(String name, int shift, int bits, double factor, long defaultValue, int maxValue, boolean allowZero) { super(name, shift, bits, factor, defaultValue, maxValue, allowZero); double factorDivision = maxValue / factor; if (factorDivision != (int) factorDivision) { throw new IllegalStateException("MaxValue needs to be divisible by factor without remainder"); } }
Source:
protected boolean canDoAction() { boolean retValue=true; job = getJobDao().get(getParameters().getId()); if (job != null) { if (!job.isExternal()) { retValue = false; addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_NOT_EXTERNAL); } } else { parentStep = getStepDao().get(getParameters().getId()); } if (job == null && parentStep == null) { retValue=false; addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_NO_PARENT); } if (getParameters().getDescription().trim().length() == 0) { retValue=false; addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_EMPTY_DESCRIPTION); } if (!retValue) { addCanDoActionMessage(VdcBllMessages.VAR__ACTION__ADD); addCanDoActionMessage(VdcBllMessages.VAR__TYPE__EXTERNAL_JOB); } return retValue; }

Target:
protected boolean canDoAction() { boolean retValue=true; job = getJobDao().get(getParameters().getId()); if (job != null) { if (!job.isExternal()) { retValue = false; addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_NOT_EXTERNAL); } } else { parentStep = getStepDao().get(getParameters().getId()); } if (job == null && parentStep == null) { retValue=false; addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_NO_PARENT); } if (StringUtils.isEmpty(getParameters().getDescription())) { retValue=false; addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_EMPTY_DESCRIPTION); } if (!retValue) { addCanDoActionMessage(VdcBllMessages.VAR__ACTION__ADD); addCanDoActionMessage(VdcBllMessages.VAR__TYPE__EXTERNAL_JOB); } return retValue; }
Source:
public NewTopicBuilder replicationFactor(short replicationFactor) { if (replicationFactor == NO_REPLICATION_FACTOR) { return defaultReplicationFactor(); } this.replicationFactor = replicationFactor; return this; }

Target:
public NewTopicBuilder replicationFactor(short replicationFactor) { this.replicationFactor = replicationFactor; return this; }
Source:
private static List<Dimension> buildExtendedTablesFromQuery(Query q) { HashSet<Dimension> selectedDims = new HashSet<>(); if(null != q.getFields()) { for (DimensionField f : q.getFields()) { selectedDims.add(f.getDimension()); } } if (null != q.getJoinTables()) { for (Dimension d : q.getJoinTables()) { selectedDims.add(d); } } Set<Dimension> filterDims = q.resolveFilterDimensions(); if(null != filterDims) { selectedDims.addAll(filterDims); } List<Dimension> orderedTables = Dimension.resolveOrderedDimensions(selectedDims); if (q.getAggregateMeasures() != null && q.getAggregateMeasures().size() > 0) { AggregateMeasure aggregateMeasure = q.getAggregateMeasures().get(0); MeasureSqlSerializer serializer = MeasureSqlSerializerFactory.get(aggregateMeasure.getMeasure()); Dimension table = DbMappings.TABLE_NAME_TO_DIMENSION.get(serializer.toTableName()); Dimension optionalTable = DbMappings.TABLE_NAME_TO_DIMENSION.get(serializer.optionalJoinedTable()); orderedTables.add(table); if (optionalTable != null) { orderedTables.add(optionalTable); } } for (int i = 0 ; i < orderedTables.size() ; i++) { Dimension currentDimension = orderedTables.get(i); Dimension actualDimension = PSEUDO_DIMENSION_CONVERSION_TABLE.get(currentDimension); if (actualDimension != null) { orderedTables.remove(i); orderedTables.add(i, actualDimension); } } return orderedTables; }

Target:
private static List<Dimension> buildExtendedTablesFromQuery(Query q) { HashSet<Dimension> selectedDims = new HashSet<>(); if(null != q.getFields()) { for (DimensionField f : q.getFields()) { selectedDims.add(f.getDimension()); } } if (null != q.getJoinTables()) { for (Dimension d : q.getJoinTables()) { selectedDims.add(d); } } Set<Dimension> filterDims = q.resolveFilterDimensions(); if(null != filterDims) { selectedDims.addAll(filterDims); } List<Dimension> orderedTables = Dimension.resolveOrderedDimensions(selectedDims); if (q.getAggregateMeasures() != null && q.getAggregateMeasures().size() > 0) { AggregateMeasure aggregateMeasure = q.getAggregateMeasures().get(0); MeasureSqlSerializer serializer = MeasureSqlSerializerFactory.get(aggregateMeasure.getMeasure()); Dimension table = serializer.toTableDimension(); Dimension optionalTable = serializer.toSecondTableDimension(); orderedTables.add(table); if (optionalTable != null) { orderedTables.add(optionalTable); } } for (int i = 0 ; i < orderedTables.size() ; i++) { Dimension originalDimension = orderedTables.get(i); Dimension resolvedDimension = DbMappings.TABLE_NAME_TO_DIMENSION.get(DbMappings.DIMENSION_TO_TABLE_NAME.get(originalDimension)); if (resolvedDimension != originalDimension) { orderedTables.remove(i); orderedTables.add(i, resolvedDimension); } } return orderedTables; }
Source:
public void testGetMenuLanguage() throws Exception { HdmiCecUtils hdmiCecUtils = new HdmiCecUtils(CecDevice.PLAYBACK_1, "1.0.0.0"); if (hdmiCecUtils.init()) { try { hdmiCecUtils.sendCecMessage(CecDevice.TV, CecMessage.GET_MENU_LANGUAGE); String message = hdmiCecUtils.checkExpectedOutput (CecDevice.TV, CecMessage.FEATURE_ABORT); } finally { hdmiCecUtils.killCecProcess(); } } }

Target:
public void testGetMenuLanguage() throws Exception { HdmiCecUtils hdmiCecUtils = new HdmiCecUtils(CecDevice.PLAYBACK_1, "1.0.0.0"); if (hdmiCecUtils.init()) { try { hdmiCecUtils.sendCecMessage(CecDevice.TV, CecMessage.GET_MENU_LANGUAGE); String message = hdmiCecUtils.checkExpectedOutput (CecDevice.TV, CecMessage.FEATURE_ABORT); String params = hdmiCecUtils.getParamsFromMessage(message, CecMessage.GET_MENU_LANGUAGE.toString().length()); assertEquals(params, CecMessage.GET_MENU_LANGUAGE.toString()); } finally { hdmiCecUtils.killCecProcess(); } } }
Source:
private void removeFromImpactCache(Pattern pattern) { Set<URI> referredUris = PatternLanguageHelper.getReferencedPatternsTransitive(pattern).stream().map(p -> p.eResource().getURI()).collect(Collectors.toSet()); referredUris.forEach(u -> impactCache.remove(u, pattern)); }

Target:
private void removeFromImpactCache(Pattern pattern) { Set<URI> referredUris = PatternLanguageHelper.getReferencedPatternsTransitive(pattern).stream() .map(p -> p.eResource().getURI()).collect(Collectors.toSet()); referredUris.forEach(u -> dependencyCache.remove(u, pattern)); }
Source:
public Object execute(final ExecutionEvent event) throws ExecutionException { final ISelection currentSelection = HandlerUtil.getCurrentSelection(event); final Resource resourceSelected = getSelectedResource(currentSelection); final TableConfiguration configuration = getEditedTableConfiguration(resourceSelected); CreateNattableConfigurationWizard wizard = new CreateNattableConfigurationWizard(configuration, resourceSelected); WizardDialog dialog = new WizardDialog(Display.getDefault().getActiveShell(), wizard); dialog.open(); return null; }

Target:
public Object execute(final ExecutionEvent event) throws ExecutionException { final ISelection currentSelection = HandlerUtil.getCurrentSelection(event); final Resource resourceSelected = getSelectedResource(currentSelection); final TableConfiguration configuration = getEditedTableConfiguration(resourceSelected); final CreateNattableConfigurationWizard wizard = new CreateNattableConfigurationWizard(configuration, resourceSelected); final WizardDialog dialog = new WizardDialog(Display.getDefault().getActiveShell(), wizard); dialog.open(); return null; }
Source:
private Integer getNumPartitions(String topic) { try { return this.kafka.partitionsFor(topic).size(); } catch(TimeoutException e) { LOGGER.error("Topic '" + topic + "' name does not exist. Exception: " + e.getLocalizedMessage()); throw e; } }

Target:
private Integer getNumPartitions(String topic) { try { return this.kafka.partitionsFor(topic).size(); } catch (KafkaException e) { LOGGER.error("Topic '" + topic + "' name does not exist. Exception: " + e.getLocalizedMessage()); throw e; } }
Source:
public boolean removeReplica(ReplicaId replicaId) { if (!partitionToPartitionInfo.containsKey(replicaId.getPartitionId())) { logger.error("{} doesn't exist in replication manager, skipping removing replica request.", replicaId.getPartitionId()); return false; } PartitionInfo partitionInfo = partitionToPartitionInfo.get(replicaId.getPartitionId()); List<RemoteReplicaInfo> remoteReplicaInfos = partitionInfo.getRemoteReplicaInfos(); logger.info("Removing remote replicas of from replica threads", replicaId.getPartitionId()); removeRemoteReplicaInfoFromReplicaThread(remoteReplicaInfos); mountPathToPartitionInfos.get(replicaId.getMountPath()).remove(partitionInfo); partitionToPartitionInfo.remove(replicaId.getPartitionId()); return true; }

Target:
public boolean removeReplica(ReplicaId replicaId) { if (!partitionToPartitionInfo.containsKey(replicaId.getPartitionId())) { logger.error("{} doesn't exist in replication manager, skipping removing replica request.", replicaId.getPartitionId()); return false; } PartitionInfo partitionInfo = partitionToPartitionInfo.get(replicaId.getPartitionId()); List<RemoteReplicaInfo> remoteReplicaInfos = partitionInfo.getRemoteReplicaInfos(); logger.info("Removing remote replicas of from replica threads", replicaId.getPartitionId()); removeRemoteReplicaInfoFromReplicaThread(remoteReplicaInfos); mountPathToPartitionInfos.computeIfPresent(replicaId.getMountPath(), (k, v) -> { v.remove(partitionInfo); return v; }); partitionToPartitionInfo.remove(replicaId.getPartitionId()); logger.info("{} is successfully removed from replication manager", replicaId.getPartitionId()); return true; }
Source:
private void annotateDataMutations(UngroupedAggregateRegionObserver.MutationList mutationsList, Scan scan) { byte[] tenantId = null; byte[] logicalTableName = null; byte[] schemaName = null; byte[] tableType = null; byte[] ddlTimestamp = null; tenantId = scan.getAttribute(MutationState.MutationMetadataType.TENANT_ID.toString()); schemaName = scan.getAttribute(MutationState.MutationMetadataType.SCHEMA_NAME.toString()); logicalTableName = scan.getAttribute(MutationState.MutationMetadataType.LOGICAL_TABLE_NAME.toString()); tableType = scan.getAttribute(MutationState.MutationMetadataType.TABLE_TYPE.toString()); ddlTimestamp = scan.getAttribute(MutationState.MutationMetadataType.TIMESTAMP.toString()); for (Mutation m : mutationsList) { if (tenantId != null) { m.setAttribute(MutationState.MutationMetadataType.TENANT_ID.toString(), tenantId); } m.setAttribute(MutationState.MutationMetadataType.SCHEMA_NAME.toString(), schemaName); m.setAttribute(MutationState.MutationMetadataType.LOGICAL_TABLE_NAME.toString(), logicalTableName); m.setAttribute(MutationState.MutationMetadataType.TABLE_TYPE.toString(), tableType); m.setAttribute(MutationState.MutationMetadataType.TIMESTAMP.toString(), ddlTimestamp); } }

Target:
private void annotateDataMutations(UngroupedAggregateRegionObserver.MutationList mutationsList, Scan scan) { byte[] tenantId = scan.getAttribute(MutationState.MutationMetadataType.TENANT_ID.toString()); byte[] schemaName = scan.getAttribute(MutationState.MutationMetadataType.SCHEMA_NAME.toString()); byte[] logicalTableName = scan.getAttribute(MutationState.MutationMetadataType.LOGICAL_TABLE_NAME.toString()); byte[] tableType = scan.getAttribute(MutationState.MutationMetadataType.TABLE_TYPE.toString()); byte[] ddlTimestamp = scan.getAttribute(MutationState.MutationMetadataType.TIMESTAMP.toString()); for (Mutation m : mutationsList) { annotateMutation(m, tenantId, schemaName, logicalTableName, tableType, ddlTimestamp); } }
Source:
protected void connectSensors() { super.connectSensors(); connectServiceUpIsRunning(); setBrokerUrl(); setAttribute(MANAGEMENT_URL, format("http://%s:%s/", getAttribute(HOSTNAME), getAttribute(MANAGEMENT_PORT))); }

Target:
protected void connectSensors() { super.connectSensors(); connectServiceUpIsRunning(); setBrokerUrl(); if (getEnableManagementPlugin()) { setAttribute(MANAGEMENT_URL, format("http://%s:%s/", getAttribute(HOSTNAME), getAttribute(MANAGEMENT_PORT))); } }
Source:
public void loadGroupByCenter(int centerId) { checkViewAttached(); getMvpView().showProgressbar(true); mSubscription.add(collectionDataManager.fetchGroupsAssociatedWithCenter(centerId) .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()) .subscribe(new Subscriber<CenterWithAssociations>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { getMvpView().showProgressbar(false); try { if (e instanceof HttpException) { String errorMessage = ((HttpException) e).response().errorBody() .string(); getMvpView().showError(MFErrorParser.parseError(errorMessage) .getErrors().get(0).getDefaultUserMessage()); } } catch (Throwable throwable) { RxJavaPlugins.getInstance().getErrorHandler().handleError(e); } } @Override public void onNext(CenterWithAssociations centerWithAssociations) { getMvpView().showProgressbar(false); getMvpView().showGroupByCenter(centerWithAssociations); } })); }

Target:
public void loadGroupByCenter(int centerId) { checkViewAttached(); getMvpView().showProgressbar(true); mSubscription.add(collectionDataManager.fetchGroupsAssociatedWithCenter(centerId) .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()) .subscribe(new Subscriber<CenterWithAssociations>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { getMvpView().showProgressbar(false); getMvpView().showError(MFErrorParser.errorMessage(e)); } @Override public void onNext(CenterWithAssociations centerWithAssociations) { getMvpView().showProgressbar(false); getMvpView().showGroupByCenter(centerWithAssociations); } })); }
Source:
public Transferable getTransferable() { if (!myStatusIsSpecified && !isDataFlavorSupported(ItemTransferable.DESIGNER_FLAVOR) && isDataFlavorSupported(DataFlavor.stringFlavor)) { accept(DnDConstants.ACTION_COPY); } if (myDragEvent != null) { return myDragEvent.getTransferable(); } else { return myDropEvent.getTransferable(); } }

Target:
public Transferable getTransferable() { if (!myStatusSpecified && !isDataFlavorSupported(ItemTransferable.DESIGNER_FLAVOR) && isDataFlavorSupported(DataFlavor.stringFlavor)) { accept(DnDConstants.ACTION_COPY); } if (myDragEvent != null) { return myDragEvent.getTransferable(); } else { return myDropEvent.getTransferable(); } }
Source:
public void process(Exchange exchange) throws Exception { final HazelcastOperation operation = lookupOperation(exchange); switch ((operation != null) ? operation : HazelcastOperation.PUBLISH) { case PUBLISH: this.publish(exchange); break; default: throw new IllegalArgumentException(String.format("The value '%s' is not allowed for parameter '%s' on the TOPIC cache.", operation, HazelcastConstants.OPERATION)); } HazelcastComponentHelper.copyHeaders(exchange); }

Target:
public void process(Exchange exchange) throws Exception { final HazelcastOperation operation = lookupOperation(exchange); switch (operation) { case PUBLISH: this.publish(exchange); break; default: throw new IllegalArgumentException(String.format("The value '%s' is not allowed for parameter '%s' on the TOPIC cache.", operation, HazelcastConstants.OPERATION)); } HazelcastComponentHelper.copyHeaders(exchange); }
Source:
public List<String> getTabCompletions(MinecraftServer server, ICommandSender sender, String[] args, @Nullable BlockPos targetPos) { if (args.length == 1) { List<String> list = new ArrayList<>(Arrays.asList(server.getOnlinePlayerNames())); list.addAll(defaultSelectors); return list; } else { return Collections.emptyList(); } }

Target:
public List<String> getTabCompletions(MinecraftServer server, ICommandSender sender, String[] args, @Nullable BlockPos targetPos) { if (args.length == 1) { List<String> list = new ArrayList<>(Arrays.asList(server.getOnlinePlayerNames())); list.addAll(DEFAULT_SELECTORS); return getListOfStringsMatchingLastWord(args, list); } else { return Collections.emptyList(); } }
Source:
public void testFailedRegionMove() throws Exception { MiniHBaseCluster cluster = TEST_UTIL.getHBaseCluster(); Admin admin = TEST_UTIL.getAdmin(); Table table = TEST_UTIL.getConnection().getTable(TABLE_NAME); List<Put> puts = new ArrayList<>(); for (int i = 0; i < 1000; i++) { puts.add(new Put(Bytes.toBytes("rowkey_" + i)) .addColumn(Bytes.toBytes("fam1"), Bytes.toBytes("q1"), Bytes.toBytes("val_" + i))); } table.put(puts); admin.flush(TABLE_NAME); HRegionServer regionServer = cluster.getRegionServer(0); String rsName = regionServer.getServerName().getAddress().toString(); int numRegions = regionServer.getNumberOfOnlineRegions(); List<HRegion> hRegions = regionServer.getRegions().stream() .filter(hRegion -> hRegion.getRegionInfo().getTable().equals(TABLE_NAME)) .collect(Collectors.toList()); RegionMover.RegionMoverBuilder rmBuilder = new RegionMover.RegionMoverBuilder(rsName, TEST_UTIL.getConfiguration()).ack(true) .maxthreads(8); try (RegionMover rm = rmBuilder.build()) { LOG.debug("Unloading " + regionServer.getServerName()); rm.unload(); Assert.assertEquals(0, regionServer.getNumberOfOnlineRegions()); LOG.debug("Successfully Unloaded\nNow Loading"); admin.offline(hRegions.get(0).getRegionInfo().getRegionName()); Assert.assertFalse(rm.load()); } }

Target:
public void testFailedRegionMove() throws Exception { final TableName tableName = TableName.valueOf(name.getMethodName()); MiniHBaseCluster cluster = TEST_UTIL.getHBaseCluster(); Admin admin = TEST_UTIL.getAdmin(); Table table = TEST_UTIL.getConnection().getTable(tableName); List<Put> puts = new ArrayList<>(); for (int i = 0; i < 1000; i++) { puts.add(new Put(Bytes.toBytes("rowkey_" + i)) .addColumn(Bytes.toBytes("fam1"), Bytes.toBytes("q1"), Bytes.toBytes("val_" + i))); } table.put(puts); admin.flush(tableName); HRegionServer regionServer = cluster.getRegionServer(0); String rsName = regionServer.getServerName().getAddress().toString(); int numRegions = regionServer.getNumberOfOnlineRegions(); List<HRegion> hRegions = regionServer.getRegions().stream() .filter(hRegion -> hRegion.getRegionInfo().getTable().equals(tableName)) .collect(Collectors.toList()); RegionMover.RegionMoverBuilder rmBuilder = new RegionMover.RegionMoverBuilder(rsName, TEST_UTIL.getConfiguration()).ack(true) .maxthreads(8); try (RegionMover rm = rmBuilder.build()) { LOG.debug("Unloading {}", regionServer.getServerName()); rm.unload(); Assert.assertEquals(0, regionServer.getNumberOfOnlineRegions()); LOG.debug("Successfully Unloaded, now Loading"); admin.offline(hRegions.get(0).getRegionInfo().getRegionName()); Assert.assertFalse(rm.load()); } }
Source:
public OffsetDateTime getScheduledEnqueueTime() { OffsetDateTime scheduledEnqueueTime = null; Map<String, Object> messageAnnotationMap = amqpAnnotatedMessage.getMessageAnnotations(); if (messageAnnotationMap.containsKey(SCHEDULED_ENQUEUE_UTC_TIME_NAME.getValue())) { scheduledEnqueueTime = ((Date) messageAnnotationMap.get(SCHEDULED_ENQUEUE_UTC_TIME_NAME.getValue())) .toInstant().atOffset(ZoneOffset.UTC); } return scheduledEnqueueTime; }

Target:
public OffsetDateTime getScheduledEnqueueTime() { Object value = amqpAnnotatedMessage.getMessageAnnotations().get(SCHEDULED_ENQUEUE_UTC_TIME_NAME.getValue()); return value != null ? ((Date) value).toInstant().atOffset(ZoneOffset.UTC) : null; }
Source:
public static void input(MethodHandle methodHandle, NullableDoubleState state, double value) { if (state.isNull()) { state.setNull(false); state.setDouble(value); return; } try { if ((boolean) methodHandle.invokeExact(value, state.getDouble())) { state.setDouble(value); } } catch (Throwable t) { throw internalError(t); } }

Target:
public static void input(MethodHandle methodHandle, NullableDoubleState state, double value) { compareAndUpdateState(methodHandle, state, value); }
Source:
public void thingUpdated(final Thing thing, ThingTrackerEvent thingTrackerEvent) { ThingUID thingUID = thing.getUID(); Thing oldThing = getThing(thingUID); if (oldThing != thing) { this.things.remove(oldThing); this.things.add(thing); } final ThingHandler thingHandler = thingHandlers.get(thingUID); if (thingHandler != null) { if (oldThing != thing) { thing.setHandler(thingHandler); } if (ThingHandlerHelper.isHandlerInitialized(thing)) { try { if (!thingUpdatedLock.contains(thingUID)) { SafeMethodCaller.call(new SafeMethodCaller.ActionWithException<Void>() { @Override public Void call() throws Exception { thingHandler.thingUpdated(thing); return null; } }); } } catch (Exception ex) { logger.error("Exception occured while calling thing updated at ThingHandler '{}': {}", thingHandler, ex.getMessage(), ex); } } else { logger.debug( "Cannot notify handler about updated thing '{}', because thing is not initialized (must be in status ONLINE or OFFLINE). Start handler initialization instead.", thing.getThingTypeUID()); initializeHandler(thing); } } else { registerAndInitializeHandler(thing, getThingHandlerFactory(thing)); } if (oldThing != thing) { oldThing.setHandler(null); } }

Target:
public void thingUpdated(final Thing thing, ThingTrackerEvent thingTrackerEvent) { ThingUID thingUID = thing.getUID(); Thing oldThing = getThing(thingUID); if (oldThing != thing) { this.things.remove(oldThing); this.things.add(thing); } final ThingHandler thingHandler = thingHandlers.get(thingUID); if (thingHandler != null) { if (oldThing != thing) { thing.setHandler(thingHandler); } if (ThingHandlerHelper.isHandlerInitialized(thing)) { try { if (!thingUpdatedLock.contains(thingUID)) { SafeMethodCaller.call(new SafeMethodCaller.ActionWithException<Void>() { @Override public Void call() throws Exception { thingHandler.thingUpdated(thing); return null; } }); } } catch (Exception ex) { logger.error("Exception occured while calling thing updated at ThingHandler '{}': {}", thingHandler, ex.getMessage(), ex); } } else { logger.debug( "Cannot notify handler about updated thing '{}', because handler is not initialized (must be in status ONLINE or OFFLINE). Start handler initialization instead.", thing.getThingTypeUID()); initializeHandler(thing); } } else { registerAndInitializeHandler(thing, getThingHandlerFactory(thing)); } if (oldThing != thing) { oldThing.setHandler(null); } }
Source:
private void findNextElement() { if (metricFamilySamples != null && metricFamilySamples.hasNext()) { next = filter(metricFamilySamples.next()); } else { while (collectorIter.hasNext()) { metricFamilySamples = collectorIter.next().collect().iterator(); if (metricFamilySamples.hasNext()) { next = filter(metricFamilySamples.next()); if(next == null) { continue; } return; } } next = null; } }

Target:
private void findNextElement() { next = null; while (metricFamilySamples != null && metricFamilySamples.hasNext()) { next = filter(metricFamilySamples.next()); if (next != null) { return; } } if (next == null) { while (collectorIter.hasNext()) { metricFamilySamples = collectorIter.next().collect().iterator(); while (metricFamilySamples.hasNext()) { next = filter(metricFamilySamples.next()); if (next != null) { return; } } } } }
Source:
public static Map<Integer, RegionProjection> projectionsOfRegions(int featureIdx, int maxDepth, IntStream regionIndexes, int blockSize, IgniteFunction<Integer, Object> affinity, UUID trainingUUID, Ignite ignite) { HashMap<Integer, RegionProjection> regsForSearch = new HashMap<>(); IgniteCache<RegionKey, List<RegionProjection>> cache = getOrCreate(ignite); PrimitiveIterator.OfInt itr = regionIndexes.iterator(); int curBlockIdx = -1; List<RegionProjection> block = null; Object affKey = affinity.apply(featureIdx); while (itr.hasNext()) { int i = itr.nextInt(); int blockIdx = i / blockSize; if (blockIdx != curBlockIdx) { block = cache.localPeek(key(featureIdx, blockIdx, affKey, trainingUUID)); curBlockIdx = blockIdx; } if (block == null) throw new IllegalStateException("Unexpected null block at index " + i); RegionProjection reg = block.get(i % blockSize); if (reg.depth() <= maxDepth) regsForSearch.put(i, reg); } return regsForSearch; }

Target:
public static Map<Integer, RegionProjection> projectionsOfRegions(int featureIdx, int maxDepth, IntStream regionIndexes, int blockSize, IgniteFunction<Integer, Object> affinity, UUID trainingUUID, Ignite ignite) { HashMap<Integer, RegionProjection> regsForSearch = new HashMap<>(); IgniteCache<RegionKey, List<RegionProjection>> cache = getOrCreate(ignite); PrimitiveIterator.OfInt itr = regionIndexes.iterator(); int curBlockIdx = -1; List<RegionProjection> block = null; Object affinityKey = affinity.apply(featureIdx); while (itr.hasNext()) { int i = itr.nextInt(); int blockIdx = i / blockSize; if (blockIdx != curBlockIdx) { block = cache.localPeek(key(featureIdx, blockIdx, affinityKey, trainingUUID)); curBlockIdx = blockIdx; } if (block == null) throw new IllegalStateException("Unexpected null block at index " + i); RegionProjection reg = block.get(i % blockSize); if (reg.depth() < maxDepth) regsForSearch.put(i, reg); } return regsForSearch; }
Source:
private boolean isOrphan(File file) { String fileName = file.getName(); return fileName.startsWith("pack") && (fileName.endsWith(PackExt.BITMAP_INDEX.getExtension()) || fileName.endsWith(PackExt.INDEX.getExtension())) && !new File(file.getParentFile(), fileName.substring(0, fileName.lastIndexOf(".") + 1) + PackExt.PACK.getExtension()).exists(); }

Target:
private boolean isOrphan(File file) { String fileName = file.getName(); return fileName.startsWith("pack") && (fileName.endsWith("." + PackExt.BITMAP_INDEX.getExtension()) || fileName .endsWith("." + PackExt.INDEX.getExtension())) && !new File(file.getParentFile(), fileName.substring(0, fileName.lastIndexOf(".") + 1) + PackExt.PACK.getExtension()).exists(); }
Source:
public boolean isMirrored() { Object property = getProperty("MIRRORED"); return property instanceof Boolean && ((Boolean)property).booleanValue(); }

Target:
public boolean isMirrored() { Object property = getProperty(EMFCompareConfiguration.MIRRORED); return property instanceof Boolean && ((Boolean)property).booleanValue(); }
Source:
public synchronized void registerListener(DruidNodeDiscovery.Listener listener) { for (DiscoveryDruidNode node : nodes.values()) { listenerExecutor.submit(() -> { try { listener.nodeAdded(node); } catch (Exception ex) { log.error(ex, "Exception occured in DiscoveryDruidNode.nodeAdded(node=[%s]) in listener [%s].", node, listener); } }); } nodeListeners.add(listener); }

Target:
public void registerListener(DruidNodeDiscovery.Listener listener) { synchronized (lock) { for (DiscoveryDruidNode node : nodes.values()) { listenerExecutor.submit(() -> { try { listener.nodeAdded(node); } catch (Exception ex) { log.error( ex, "Exception occured in DiscoveryDruidNode.nodeAdded(node=[%s]) in listener [%s].", node, listener ); } }); } nodeListeners.add(listener); } }
Source:
catch (ClassNotFoundException e) { throw new IllegalStateException(e); }

Target:
catch (ClassNotFoundException e) { log.warn("Spring Data Hadoop is required on the classpath to register modules to HDFS. This feature is disabled."); }
Source:
public void run() { try { int entryCount; ScanResults currentScanResults = scanResults.get(); if (isScanning || currentScanResults == null) { return; } else { entryCount = queueEntryCount.get(); } long processStartTimeMs = time.milliseconds(); for (int i = 0; i < entryCount && !cancelled; i++) { EntryContext entryContext = recentEntryQueue.poll(); if (entryContext == null) { throw new IllegalStateException( String.format("Invalid queue state in store %s. Expected entryCount %d, current index: %d", storeId, entryCount, i)); } metrics.statsRecentEntryQueueSize.update(queueEntryCount.decrementAndGet()); StoreKey key = entryContext.key; IndexValue newValue = entryContext.currentValue; IndexValue originalPut = entryContext.originalPutValue; IndexValue previousValue = entryContext.previousValue; if (newValue.getOffset().compareTo(currentScanResults.scannedEndOffset) >= 0) { if (newValue.isDelete()) { processNewDelete(currentScanResults, key, newValue, originalPut, previousValue); } else if (newValue.isUndelete()) { processNewUndelete(currentScanResults, key, newValue, originalPut, previousValue); } else if (newValue.isTtlUpdate()) { processNewTtlUpdate(currentScanResults, newValue, originalPut); } else { processNewPut(currentScanResults, newValue); } } } metrics.statsRecentEntryQueueProcessTimeMs.update(time.milliseconds() - processStartTimeMs, TimeUnit.MILLISECONDS); } catch (Exception e) { logger.error("Unexpected exception while running QueueProcessor in store {}", storeId, e); metrics.blobStoreStatsQueueProcessorErrorCount.inc(); } }

Target:
public void run() { try { int entryCount; ScanResults currentScanResults = scanResults.get(); if (isScanning || currentScanResults == null) { return; } else { entryCount = queueEntryCount.get(); } long processStartTimeMs = time.milliseconds(); for (int i = 0; i < entryCount && !cancelled && !isScanning; i++) { EntryContext entryContext = recentEntryQueue.poll(); if (entryContext == null) { throw new IllegalStateException( String.format("Invalid queue state in store %s. Expected entryCount %d, current index: %d", storeId, entryCount, i)); } metrics.statsRecentEntryQueueSize.update(queueEntryCount.decrementAndGet()); StoreKey key = entryContext.key; IndexValue newValue = entryContext.currentValue; IndexValue originalPut = entryContext.originalPutValue; IndexValue previousValue = entryContext.previousValue; if (newValue.getOffset().compareTo(currentScanResults.scannedEndOffset) >= 0) { if (newValue.isDelete()) { processNewDelete(currentScanResults, key, newValue, originalPut, previousValue); } else if (newValue.isUndelete()) { processNewUndelete(currentScanResults, key, newValue, originalPut, previousValue); } else if (newValue.isTtlUpdate()) { processNewTtlUpdate(currentScanResults, newValue, originalPut); } else { processNewPut(currentScanResults, newValue); } } } metrics.statsRecentEntryQueueProcessTimeMs.update(time.milliseconds() - processStartTimeMs, TimeUnit.MILLISECONDS); } catch (Exception e) { logger.error("Unexpected exception while running QueueProcessor in store {}", storeId, e); metrics.blobStoreStatsQueueProcessorErrorCount.inc(); } }
Source:
public Builder withLimits(List<JLimit> limits) { this.limits = limits; return this; }

Target:
public Builder withLimits(List<JLimit> limits) { Objects.requireNonNull(limits); this.limits = limits; return this; }
Source:
public ServerTest() throws InterruptedException, IOException, StoreException, InstantiationException { notificationSystem = new MockNotificationSystem(9); nonSSLCluster = new MockCluster(notificationSystem, false, "", "", ""); sslCluster = new MockCluster(notificationSystem, true, "DC2,DC3", "DC1,DC3", "DC1,DC2"); }

Target:
public ServerTest() throws InterruptedException, IOException, StoreException, InstantiationException { notificationSystem = new MockNotificationSystem(9); }
Source:
public void broadcast(BroadcastMessage message, @Nullable NodeAddress sender, @Nullable BroadcastHandler.Listener listener) { broadcastRequests.add(new BroadcastRequest(message, sender, listener)); log.info("Broadcast requested for {}. We queue it up for next bundled broadcast.", message.getClass().getSimpleName()); if (timer == null) { timer = UserThread.runAfter(this::maybeBroadcastBundle, BROADCAST_INTERVAL_MS, TimeUnit.MILLISECONDS); } }

Target:
public void broadcast(BroadcastMessage message, @Nullable NodeAddress sender, @Nullable BroadcastHandler.Listener listener) { broadcastRequests.add(new BroadcastRequest(message, sender, listener)); log.debug("Broadcast requested for {}. We queue it up for next bundled broadcast.", message.getClass().getSimpleName()); if (timer == null) { timer = UserThread.runAfter(this::maybeBroadcastBundle, BROADCAST_INTERVAL_MS, TimeUnit.MILLISECONDS); } }
Source:
public static List<Object[]> data() { return Arrays.asList( new Object[][]{{MessageFormatRecord.Message_Header_Version_V1}, {MessageFormatRecord.Message_Header_Version_V1}}); }

Target:
public static List<Object[]> data() { return Arrays.asList( new Object[][]{{MessageFormatRecord.Message_Header_Version_V1}, {MessageFormatRecord.Message_Header_Version_V2}}); }
Source:
public void tryMouseDoubleclickZoom() throws InterruptedException { final boolean[] dirty = { true }; final TmfTimeRange[] timeRange = new TmfTimeRange[1]; super.treeTest(); loadFlameGraph(); ITimeGraphEntry entry = selectRoot(); assertEquals(3, entry.getChildren().size()); ITimeGraphEntry actualEntry = entry.getChildren().get(1); ITimeEvent actualEvent = getFirstEvent(actualEntry); assertNotNull(actualEvent); TimeGraphControl timeGraphControl = fTimeGraphViewer.getTimeGraphControl(); fTimeGraphViewer.addRangeListener((TimeGraphRangeUpdateEvent event) -> { dirty[0] = false; timeRange[0] = new TmfTimeRange(TmfTimestamp.fromNanos(event.getStartTime()), TmfTimestamp.fromNanos(event.getEndTime())); }); int x = UIThreadRunnable.syncExec(() -> timeGraphControl.getXForTime((long) ((actualEvent.getDuration() + actualEvent.getTime()) * 0.5))); fBot.waitUntil(new SWTBotTestCondition() { @Override public boolean test() throws Exception { return !dirty[0]; } }); SWTBotCanvas canvasBot = new SWTBotCanvas(timeGraphControl); canvasBot.doubleClick(x, 45); fFg.waitForUpdate(); UIThreadRunnable.syncExec(() -> fTimeGraphViewer.refresh()); assertEquals(new TmfTimeRange(TmfTimestamp.fromNanos(0), TmfTimestamp.fromNanos(100)), timeRange[0]); }

Target:
public void tryMouseDoubleclickZoom() throws InterruptedException { super.treeTest(); loadFlameGraph(); ITimeGraphEntry entry = selectRoot(); assertEquals(3, entry.getChildren().size()); ITimeGraphEntry actualEntry = entry.getChildren().get(1); ITimeEvent actualEvent = getFirstEvent(actualEntry); assertNotNull(actualEvent); TimeGraphControl timeGraphControl = fTimeGraphViewer.getTimeGraphControl(); int x = UIThreadRunnable.syncExec(() -> timeGraphControl.getXForTime((long) ((actualEvent.getDuration() + actualEvent.getTime()) * 0.5))); SWTBotCanvas canvasBot = new SWTBotCanvas(timeGraphControl); canvasBot.doubleClick(x, 45); fFg.waitForUpdate(); UIThreadRunnable.syncExec(() -> fTimeGraphViewer.refresh()); assertEquals(new TmfTimeRange(TmfTimestamp.fromNanos(0), TmfTimestamp.fromNanos(80)), new TmfTimeRange(TmfTimestamp.fromNanos(fTimeGraphViewer.getTime0()), TmfTimestamp.fromNanos(fTimeGraphViewer.getTime1()))); }
Source:
private void assertSuccess() throws Exception { for (RequestAndResult requestAndResult : requestAndResultsList) { String blobId = requestAndResult.result.result(); Exception exception = requestAndResult.result.error(); Assert.assertNotNull("blobId should not be null", blobId); Assert.assertNull("exception should be null", exception); HashMap<String, ByteBuffer> allChunks = new HashMap<String, ByteBuffer>(); for (MockServer mockServer : mockServerLayout.getMockServers()) { for (Map.Entry<String, ByteBuffer> blobEntry : mockServer.getBlobs().entrySet()) { ByteBuffer chunk = allChunks.get(blobEntry.getKey()); if (chunk == null) { allChunks.put(blobEntry.getKey(), blobEntry.getValue()); } else { if (checkContentEquality) { Assert.assertTrue("All requests for the same blob id must be identical except for correlation id", areIdenticalPutRequests(chunk.array(), blobEntry.getValue().array())); } } } } verifyBlob(blobId, requestAndResult.putContent, allChunks); } }

Target:
private void assertSuccess() throws Exception { HashMap<String, ByteBuffer> allChunks = new HashMap<String, ByteBuffer>(); for (MockServer mockServer : mockServerLayout.getMockServers()) { for (Map.Entry<String, ByteBuffer> blobEntry : mockServer.getBlobs().entrySet()) { ByteBuffer chunk = allChunks.get(blobEntry.getKey()); if (chunk == null) { allChunks.put(blobEntry.getKey(), blobEntry.getValue()); } else { if (checkContentEquality) { Assert.assertTrue("All requests for the same blob id must be identical except for correlation id", areIdenticalPutRequests(chunk.array(), blobEntry.getValue().array())); } } } } for (RequestAndResult requestAndResult : requestAndResultsList) { String blobId = requestAndResult.result.result(); Exception exception = requestAndResult.result.error(); Assert.assertNotNull("blobId should not be null", blobId); Assert.assertNull("exception should be null", exception); verifyBlob(blobId, requestAndResult.putContent, allChunks); } }
Source:
public void onLoad(ItemGroup<? extends Item> parent, String name) throws IOException { super.onLoad(parent, name); init2(); ArrayList<P> items = new ArrayList<>(getItems()); for (P item : items) { String itemName = item.getName(); String mangledName = NameMangler.apply(itemName); if (!itemName.equals(mangledName)) { if (getItem(mangledName) == null) { item.renameTo(mangledName); if (item.getDisplayNameOrNull() == null) { item.setDisplayName(itemName); item.save(); } } } } try { srcDigest = Util.getDigestOf(Items.XSTREAM2.toXML(sources)); } catch (XStreamException e) { srcDigest = null; } try { facDigest = Util.getDigestOf(Items.XSTREAM2.toXML(getProjectFactory())); } catch (XStreamException e) { facDigest = null; } if (state == null) { state = new State(this); } try { state.load(); } catch (XStreamException | IOException e) { LOGGER.log(Level.WARNING, "Could not read persisted state, will be recovered on next index.", e); state.reset(); } }

Target:
public void onLoad(ItemGroup<? extends Item> parent, String name) throws IOException { super.onLoad(parent, name); init2(); ArrayList<P> items = new ArrayList<>(getItems()); BranchProjectFactory<P, R> projectFactory = getProjectFactory(); for (P item : items) { if (projectFactory.isProject(item)) { String itemName = item.getName(); Branch branch = projectFactory.getBranch(item); String mangledName = branch.getEncodedName(); if (!itemName.equals(mangledName)) { if (super.getItem(mangledName) == null) { LOGGER.log(Level.INFO, "Non-mangled name detected for branch {0}. Renaming {1}/{2} to {1}/{3}", new Object[]{branch.getName(), getFullName(), itemName, mangledName}); item.renameTo(mangledName); if (item.getDisplayNameOrNull() == null) { item.setDisplayName(branch.getName()); item.save(); } } } } } try { srcDigest = Util.getDigestOf(Items.XSTREAM2.toXML(sources)); } catch (XStreamException e) { srcDigest = null; } try { facDigest = Util.getDigestOf(Items.XSTREAM2.toXML(projectFactory)); } catch (XStreamException e) { facDigest = null; } if (state == null) { state = new State(this); } try { state.load(); } catch (XStreamException | IOException e) { LOGGER.log(Level.WARNING, "Could not read persisted state, will be recovered on next index.", e); state.reset(); } }
Source:
public void setup() { random = new Random().nextInt(); random = random ^ random; }

Target:
public void setup() { random = new Random(0).nextInt(MATCH_CASES); }
Source:
public synchronized void playSoundFileWithStartTime(String pathToSoundfile, int startTimeInMilSeconds) { playSound(pathToSoundfile, startTimeInMilSeconds); }

Target:
public synchronized void playSoundFileWithStartTime(String pathToSoundfile, int startTimeInMilSeconds) { MediaPlayer mediaPlayer = getAvailableMediaPlayer(); if (mediaPlayer != null) { try { soundFiles.add(pathToSoundfile); mediaPlayer.setDataSource(pathToSoundfile); mediaPlayer.prepare(); mediaPlayer.seekTo(startTimeInMilSeconds); mediaPlayer.start(); } catch (Exception exception) { Log.e(TAG, "Couldn't play sound file '" + pathToSoundfile + "'", exception); } } }
Source:
private Widget editCondition( final Pattern52 origPattern, final ConditionCol52 origCol ) { Image edit = GuidedDecisionTableImageResources508.INSTANCE.Edit(); edit.setAltText( GuidedDecisionTableConstants.INSTANCE.EditThisColumnsConfiguration() ); return new ImageButton( edit, GuidedDecisionTableConstants.INSTANCE.EditThisColumnsConfiguration(), new ClickHandler() { public void onClick( ClickEvent w ) { presenter.getActiveDecisionTable().editCondition( origPattern, origCol ); } } ); }

Target:
private Widget editCondition( final Pattern52 origPattern, final ConditionCol52 origCol ) { return makeEditColumnWidget( GuidedDecisionTableConstants.INSTANCE.EditThisColumnsConfiguration(), () -> presenter.getActiveDecisionTable().editCondition( origPattern, origCol ) ); }
Source:
protected void tearDown() { boolean removed = api().deleteRole(roleName); assertTrue(removed); }

Target:
protected void tearDown() { api().deleteRole(roleName); }
Source:
public void init(final GlusterVolumeSnapshotModel model) { super.init(model); model.getInterval().getSelectedItemChangedEvent().addListener(new IEventListener<EventArgs>() { @Override public void eventRaised(Event<? extends EventArgs> ev, Object sender, EventArgs args) { getView().setCriticalIntervalLabelVisibility(model, Integer.parseInt(((ListModel<String>) sender).getSelectedItem())); } }); model.getRecurrence().getSelectedItemChangedEvent().addListener(new IEventListener<EventArgs>() { @Override public void eventRaised(Event<? extends EventArgs> ev, Object sender, EventArgs args) { getView().updateVisibilities(model); getView().setCriticalIntervalLabelVisibility(model, Integer.parseInt(model.getInterval().getSelectedItem())); getView().setMessage(null); } }); model.getEndByOptions().getSelectedItemChangedEvent().addListener(new IEventListener<EventArgs>() { @Override public void eventRaised(Event<? extends EventArgs> ev, Object sender, EventArgs args) { getView().setEndDateVisibility(model); } }); model.getPropertyChangedEvent().addListener(new IEventListener<PropertyChangedEventArgs>() { @Override public void eventRaised(Event<? extends PropertyChangedEventArgs> ev, Object sender, PropertyChangedEventArgs args) { if(args.propertyName.equalsIgnoreCase("validateAndSwitchAppropriateTab")) { getView().handleValidationErrors(model); getView().editorInvalidityBasedTabControl(); } else if(args.propertyName.equalsIgnoreCase("modelPropertiesChanged")) { getView().handleValidationErrors(model); } } }); }

Target:
public void init(final GlusterVolumeSnapshotModel model) { super.init(model); model.getInterval().getSelectedItemChangedEvent().addListener(new IEventListener<EventArgs>() { @Override public void eventRaised(Event<? extends EventArgs> ev, Object sender, EventArgs args) { getView().setCriticalIntervalLabelVisibility(model, Integer.parseInt(((ListModel<String>) sender).getSelectedItem())); } }); model.getRecurrence().getSelectedItemChangedEvent().addListener(new IEventListener<EventArgs>() { @Override public void eventRaised(Event<? extends EventArgs> ev, Object sender, EventArgs args) { getView().updateVisibilities(model); getView().setCriticalIntervalLabelVisibility(model, Integer.parseInt(model.getInterval().getSelectedItem())); getView().setMessage(null); } }); model.getEndByOptions().getSelectedItemChangedEvent().addListener(new IEventListener<EventArgs>() { @Override public void eventRaised(Event<? extends EventArgs> ev, Object sender, EventArgs args) { getView().setEndDateVisibility(model); } }); model.getPropertyChangedEvent().addListener(new IEventListener<PropertyChangedEventArgs>() { @Override public void eventRaised(Event<? extends PropertyChangedEventArgs> ev, Object sender, PropertyChangedEventArgs args) { if(args.propertyName.equalsIgnoreCase("validateAndSwitchAppropriateTab")) { getView().handleValidationErrors(model); getView().switchTabBasedOnEditorInvalidity(); } else if(args.propertyName.equalsIgnoreCase("modelPropertiesChanged")) { getView().handleValidationErrors(model); } } }); }
Source:
public void testSanity() { List<ConnectorTableLayoutResult> layouts = metadata.getTableLayouts(SESSION, tableHandle, Constraint.alwaysTrue(), Optional.empty()); assertEquals(layouts.size(), 1); ConnectorTableLayoutResult layout = getOnlyElement(layouts); assertInstanceOf(layout.getTableLayout().getHandle(), RaptorTableLayoutHandle.class); ConnectorSplitSource splitSource = getSplits(raptorSplitManager, layout); int splitCount = 0; while (!splitSource.isFinished()) { List<ConnectorSplit> splits = getSplits(splitSource, 1000); splitCount += splits.size(); RaptorSplit split = (RaptorSplit) (splits.get(0)); assertEquals(split.isTableSupportsDeltaDelete(), false); assertEquals(split.getColumnTypes(), Optional.empty()); } assertEquals(splitCount, 4); }

Target:
public void testSanity() { List<ConnectorTableLayoutResult> layouts = metadata.getTableLayouts(SESSION, tableHandle, Constraint.alwaysTrue(), Optional.empty()); assertEquals(layouts.size(), 1); ConnectorTableLayoutResult layout = getOnlyElement(layouts); assertInstanceOf(layout.getTableLayout().getHandle(), RaptorTableLayoutHandle.class); ConnectorSplitSource splitSource = getSplits(raptorSplitManager, layout); int splitCount = 0; while (!splitSource.isFinished()) { List<ConnectorSplit> splits = getSplits(splitSource, 1000); splitCount += splits.size(); RaptorSplit split = (RaptorSplit) (splits.get(0)); assertFalse(split.isTableSupportsDeltaDelete()); assertEquals(split.getColumnTypes(), Optional.empty()); } assertEquals(splitCount, 4); }
Source:
@Override public void start() throws IgniteCheckedException { for (MetricExporterSpi spi : getSpis()) spi.setMetricRegistry(this); startSpi(); ctx.internalSubscriptionProcessor().registerDistributedMetastorageListener( new DistributedMetastorageLifecycleListener() { @Override public void onReadyForRead(ReadableDistributedMetaStorage metastorage) { try { metastorage.iterate(HITRATE_CFG_PREFIX, (name, val) -> onHitRateConfigChanged( name.substring(HITRATE_CFG_PREFIX.length() + 1), (Long) val)); metastorage.iterate(HISTOGRAM_CFG_PREFIX, (name, val) -> onHistgoramConfigChanged( name.substring(HISTOGRAM_CFG_PREFIX.length() + 1), (long[]) val)); metastorage.listen(n -> n.startsWith(HITRATE_CFG_PREFIX), (name, oldVal, newVal) -> onHitRateConfigChanged( name.substring(HITRATE_CFG_PREFIX.length() + 1), (Long) newVal)); metastorage.listen(n -> n.startsWith(HISTOGRAM_CFG_PREFIX), (name, oldVal, newVal) -> onHistgoramConfigChanged( name.substring(HISTOGRAM_CFG_PREFIX.length() + 1), (long[]) newVal)); } catch (IgniteCheckedException e) { throw new IgniteException(e); } } @Override public void onReadyForWrite(DistributedMetaStorage metastorage) { metaLock.writeLock().lock(); try { GridMetricManager.this.metastorage = metastorage; } finally { metaLock.writeLock().unlock(); } } }); }

Target:
@Override public void start() throws IgniteCheckedException { for (MetricExporterSpi spi : getSpis()) spi.setMetricRegistry(this); startSpi(); ctx.internalSubscriptionProcessor().registerDistributedMetastorageListener( new DistributedMetastorageLifecycleListener() { @Override public void onReadyForRead(ReadableDistributedMetaStorage metastorage) { roMetastorage = metastorage; try { metastorage.iterate(HITRATE_CFG_PREFIX, (name, val) -> onHitRateConfigChanged( name.substring(HITRATE_CFG_PREFIX.length() + 1), (Long) val)); metastorage.iterate(HISTOGRAM_CFG_PREFIX, (name, val) -> onHistogramConfigChanged( name.substring(HISTOGRAM_CFG_PREFIX.length() + 1), (long[]) val)); } catch (IgniteCheckedException e) { throw new IgniteException(e); } metastorage.listen(n -> n.startsWith(HITRATE_CFG_PREFIX), (name, oldVal, newVal) -> onHitRateConfigChanged( name.substring(HITRATE_CFG_PREFIX.length() + 1), (Long) newVal)); metastorage.listen(n -> n.startsWith(HISTOGRAM_CFG_PREFIX), (name, oldVal, newVal) -> onHistogramConfigChanged( name.substring(HISTOGRAM_CFG_PREFIX.length() + 1), (long[]) newVal)); } @Override public void onReadyForWrite(DistributedMetaStorage metastorage) { GridMetricManager.this.metastorage = metastorage; } }); }