auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void download(int version) { try { if (metricFile.exists()) metricFile.delete(); info("# Starting download of MetricsModule build: #" + version); AtomicInteger lastPercentPosted = new AtomicInteger(); HttpResponse<File> response = Unirest.get(GH_REPO_RELEASES + "/" + version + "/" + REPO_NAME + ".jar") .downloadMonitor((b, fileName, bytesWritten, totalBytes) -> { int percent = (int) (20 * (Math.round((((double) bytesWritten / totalBytes) * 100) / 20))); if (percent != 0 && percent != lastPercentPosted.get()) { info("# Downloading... " + percent + "% " + "(" + bytesWritten + "/" + totalBytes + " bytes)"); lastPercentPosted.set(percent); } }) .asFile(metricFile.getPath()); if (response.isSuccess()) { info("Successfully downloaded " + REPO_NAME + " build: " + version); metricVersion = String.valueOf(version); } else <START> metricFile.delete(); <END> } catch (UnirestException e) { plugin.getLogger().log(Level.WARNING, "Failed to fetch the latest jar file from the" + " builds page. Perhaps GitHub is down."); } }</code><technical_language>I a failsafe lose metrics data</technical_language>

Target:
private boolean download(int version) { File f = new File(parentFolder, "Metrics-" + version + ".jar"); try { plugin.getLogger().info("# Starting download of MetricsModule build: #" + version); AtomicInteger lastPercentPosted = new AtomicInteger(); HttpResponse<File> response = Unirest.get(GH_REPO_RELEASES + "/" + version + "/" + REPO_NAME + ".jar") .downloadMonitor((b, fileName, bytesWritten, totalBytes) -> { int percent = (int) (20 * (Math.round((((double) bytesWritten / totalBytes) * 100) / 20))); if (percent != 0 && percent != lastPercentPosted.get()) { plugin.getLogger().info("# Downloading... " + percent + "% " + "(" + bytesWritten + "/" + totalBytes + " bytes)"); lastPercentPosted.set(percent); } }) .asFile(f.getPath()); if (response.isSuccess()) { plugin.getLogger().info("Successfully downloaded " + REPO_NAME + " build: " + version); Files.move(f.toPath(), metricFile.toPath(), StandardCopyOption.REPLACE_EXISTING); metricVersion = String.valueOf(version); newlyDownloaded = true; return true; } } catch (UnirestException e) { plugin.getLogger().log(Level.WARNING, "Failed to fetch the latest jar file from the" + " builds page. Perhaps GitHub is down."); } catch (IOException e) { plugin.getLogger().log(Level.WARNING, "Failed to replace the old metric file with the " + "new one. Please do this manually! Error: {0}", e.getMessage()); } return false; }
Source:
<code><START> Class getRootType() { <END> return rootType; }</code><technical_language>is ok... normal methods package protected instead of public? getRootType, getStartOffset, (and others)</technical_language>

Target:
protected Class getRootType() { return rootType; }
Source:
<code>public SendableResponse<RegisterResponse> register(Identity sender, RegisterRequest registerRequest, InetSocketAddress serverEndpoint) { Registration.Builder builder = new Registration.Builder(RegistrationHandler.createRegistrationId(), registerRequest.getEndpointName(), sender.getPeerAddress().getAddress(), sender.getPeerAddress() .getPort(), serverEndpoint); builder.lwM2mVersion(registerRequest.getLwVersion()).lifeTimeInSec(registerRequest.getLifetime()) .bindingMode(registerRequest.getBindingMode()).objectLinks(registerRequest.getObjectLinks()) .smsNumber(registerRequest.getSmsNumber()).registrationDate(new Date()).lastUpdate(new Date()) .additionalRegistrationAttributes(registerRequest.getAdditionalAttributes()); final Registration registration = builder.build(); if (!authorizer.isAuthorized(registerRequest, registration, sender)) { return new SendableResponse<>(RegisterResponse.forbidden(null)); } final Deregistration deregistration = registrationService.getStore().addRegistration(registration); LOG.debug("New registration: {}", registration); <START> Runnable whenSended = new Runnable (){ <END> public void run() { if (deregistration != null) { registrationService.fireUnregistered(deregistration.getRegistration()); } registrationService.fireRegistred(registration); }; }; return new SendableResponse<>(RegisterResponse.success(registration.getId()), whenSended); }</code><technical_language>whenSent</technical_language>

Target:
public SendableResponse<RegisterResponse> register(Identity sender, RegisterRequest registerRequest, InetSocketAddress serverEndpoint) { Registration.Builder builder = new Registration.Builder(RegistrationHandler.createRegistrationId(), registerRequest.getEndpointName(), sender.getPeerAddress().getAddress(), sender.getPeerAddress() .getPort(), serverEndpoint); builder.lwM2mVersion(registerRequest.getLwVersion()).lifeTimeInSec(registerRequest.getLifetime()) .bindingMode(registerRequest.getBindingMode()).objectLinks(registerRequest.getObjectLinks()) .smsNumber(registerRequest.getSmsNumber()).registrationDate(new Date()).lastUpdate(new Date()) .additionalRegistrationAttributes(registerRequest.getAdditionalAttributes()); final Registration registration = builder.build(); if (!authorizer.isAuthorized(registerRequest, registration, sender)) { return new SendableResponse<>(RegisterResponse.forbidden(null)); } final Deregistration deregistration = registrationService.getStore().addRegistration(registration); LOG.debug("New registration: {}", registration); Runnable whenSent = new Runnable() { @Override public void run() { if (deregistration != null) { registrationService.fireUnregistered(deregistration.getRegistration(), deregistration.getObservations()); } registrationService.fireRegistred(registration); } }; return new SendableResponse<>(RegisterResponse.success(registration.getId()), whenSent); }
Source:
<code>protected final void bindConsumerAndProducers(Module module) { MessageBus bus = findMessageBus(module); <START> Assert.notNull(bus, "MessageBus should be available in the context."); <END> MessageChannel inputChannel = module.getComponent(MODULE_INPUT_CHANNEL, MessageChannel.class); if (inputChannel != null) { bindConsumer(bus, module, inputChannel); } MessageChannel outputChannel = module.getComponent(MODULE_OUTPUT_CHANNEL, MessageChannel.class); if (outputChannel != null) { bindProducer(bus, module, outputChannel); createAndBindTapChannel(bus, module, outputChannel); } }</code><technical_language>move assertion in findMessageBus() method</technical_language>

Target:
protected final void bindConsumerAndProducers(Module module) { MessageChannel inputChannel = module.getComponent(MODULE_INPUT_CHANNEL, MessageChannel.class); if (inputChannel != null) { bindMessageConsumer(inputChannel, getInputChannelName(module), isAliasedInput(module)); } MessageChannel outputChannel = module.getComponent(MODULE_OUTPUT_CHANNEL, MessageChannel.class); if (outputChannel != null) { bindMessageProducer(outputChannel, getOutputChannelName(module), isAliasedOutput(module)); createAndBindTapChannel(module, outputChannel); } }
Source:
<code>public String toString() { StringBuilder sb = new StringBuilder(); sb.append(super.toString()); sb.append("\t\t Encoded identity value: "); sb.append(ByteArrayUtils.toHex(identityEncoded)); <START> sb.append("\n\t\tDiffie-Hellman public value: "); <END> sb.append(ByteArrayUtils.toHexString(pointEncoded)); sb.append(StringUtil.lineSeparator()); return sb.toString(); }</code><technical_language>this called *EC Diffie-Hellman public key*</technical_language>

Target:
public String toString() { StringBuilder sb = new StringBuilder(); sb.append(super.toString()); sb.append("\t\t Encoded identity value: "); sb.append(ByteArrayUtils.toHex(identityEncoded)).append(StringUtil.lineSeparator());; sb.append("\t\tEC Diffie-Hellman public value: "); sb.append(ByteArrayUtils.toHexString(pointEncoded)); sb.append(StringUtil.lineSeparator()); return sb.toString(); }
Source:
<code>public SireOfInsanity(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{4}{B}{R}"); this.subtype.add(SubType.DEMON); this.power = new MageInt(6); this.toughness = new MageInt(4); <START> this.addAbility(new BeginningOfEndStepTriggeredAbility(new SireOfInsanityEffect(), TargetController.YOU, false)); <END> }</code><technical_language>ANY, (At beginning of end step)</technical_language>

Target:
public SireOfInsanity(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{4}{B}{R}"); this.subtype.add(SubType.DEMON); this.power = new MageInt(6); this.toughness = new MageInt(4); this.addAbility(new BeginningOfEndStepTriggeredAbility( new SireOfInsanityEffect(), TargetController.ANY, false )); }
Source:
<code>public AsyncSystemProducer(String systemName, Config config, MetricsRegistry metricsRegistry) { StreamConfig sconfig = new StreamConfig(config); streamIds = config.getList(String.format(CONFIG_STREAM_LIST, systemName)); physicalToStreamIds = streamIds.stream().collect(Collectors.toMap(sconfig::getPhysicalName, Function.identity())); this.metricsRegistry = metricsRegistry; <START> ThreadFactoryBuilder threadFactoryBuilder = new ThreadFactoryBuilder().setNameFormat("SamzaHistogram_%d"); <END> executorService = Executors.newScheduledThreadPool(1, threadFactoryBuilder.build()); }</code><technical_language>"Samza Histogram Poll Thread-%d". daemon</technical_language>

Target:
public AsyncSystemProducer(String systemName, Config config, MetricsRegistry metricsRegistry) { StreamConfig sconfig = new StreamConfig(config); streamIds = config.getList(String.format(CONFIG_STREAM_LIST, systemName)); physicalToStreamIds = streamIds.stream().collect(Collectors.toMap(sconfig::getPhysicalName, Function.identity())); this.metricsRegistry = metricsRegistry; }
Source:
<code>public long relationshipsGetCount( ) { long base = storeReadLayer.relationshipsGetCount(); return ktx.hasTxStateWithChanges() ? base + ktx.txState().addedAndRemovedRelationships().delta() : base; <START> } <END></code><technical_language>Do need a ktx.assertOpen() here</technical_language>

Target:
public long relationshipsGetCount( ) { ktx.assertOpen(); long base = storeReadLayer.relationshipsGetCount(); return ktx.hasTxStateWithChanges() ? base + ktx.txState().addedAndRemovedRelationships().delta() : base; }
Source:
<code>protected static ActivityInstanceIncidentDto[] fromIncidents(Incident[] incidents) { ActivityInstanceIncidentDto[] incidentDtos = new ActivityInstanceIncidentDto[incidents.length]; for (int i = 0; i<incidents.length; i++) { <START> incidentDtos[i] = fromIncident(incidents[0]); <END> } return incidentDtos; }</code><technical_language>update index point current iteration of loop. This convert incident only. suggestion incidentDtos[i] = fromIncident(incidents[i]);</technical_language>

Target:
protected static ActivityInstanceIncidentDto[] fromIncidents(Incident[] incidents) { ActivityInstanceIncidentDto[] incidentDtos = new ActivityInstanceIncidentDto[incidents.length]; for (int i = 0; i<incidents.length; i++) { incidentDtos[i] = fromIncident(incidents[i]); } return incidentDtos; }
Source:
<code><START> public boolean pollWhileWaitingForTaskCompletion(FutureVDSCall<?> task, Guid hostId, long timeoutInMillis) { <END> return pollingWithTimeoutAndCustomCondition(hostId, timeoutInMillis, task::isDone); }</code><technical_language>for pollWithTimeout method</technical_language>

Target:
public boolean pollWhileWaitingForTaskCompletion(FutureVDSCall<?> task, Guid hostId, long timeoutInMillis) { return pollingWithTimeoutAndCustomCondition(hostId, timeoutInMillis, e -> task.isDone()); }
Source:
<code>public String getResourceTypeId() { <START> return idIfTypeCorrect(CanonicalPath.this, Resource.class); <END> }</code><technical_language>This suspicious too. getResourceTypeId -> ResourceType.class (?)</technical_language>

Target:
public String getResourceTypeId() { return idIfTypeCorrect(CanonicalPath.this, ResourceType.class); }
Source:
<code>public void setUp() <START> throws AssumptionViolatedException { <END> assumeTrue(CameraUtil.checkCameraDevice()); mAnalysisResults = new HashSet<>(); mAnalysisResultsSemaphore = new Semaphore( 0); mAnalyzer = new Analyzer() { @Override public void analyze(ImageProxy image, int rotationDegrees) { mAnalysisResults.add(new ImageProperties(image, rotationDegrees)); mAnalysisResultsSemaphore.release(); } }; Context context = ApplicationProvider.getApplicationContext(); AppConfig config = Camera2AppConfig.create(context); CameraFactory cameraFactory = config.getCameraFactory( null); try { mCameraId = cameraFactory.cameraIdForLensFacing(LensFacing.BACK); } catch (Exception e) { throw new IllegalArgumentException( "Unable to attach to camera with LensFacing " + LensFacing.BACK, e); } mCamera = cameraFactory.getCamera(mCameraId); CameraX.init(context, config); mHandlerThread = new HandlerThread("AnalysisThread"); mHandlerThread.start(); mHandler = new Handler(mHandlerThread.getLooper()); }</code><technical_language>AssumptionViolatedException is a RuntimeException, need declare 'throws' here. of other test classes</technical_language>

Target:
public void setUp() { assumeTrue(CameraUtil.deviceHasCamera()); mAnalysisResults = new HashSet<>(); mAnalysisResultsSemaphore = new Semaphore( 0); mAnalyzer = new Analyzer() { @Override public void analyze(ImageProxy image, int rotationDegrees) { mAnalysisResults.add(new ImageProperties(image, rotationDegrees)); mAnalysisResultsSemaphore.release(); } }; Context context = ApplicationProvider.getApplicationContext(); AppConfig config = Camera2AppConfig.create(context); CameraFactory cameraFactory = config.getCameraFactory( null); try { mCameraId = cameraFactory.cameraIdForLensFacing(LensFacing.BACK); } catch (Exception e) { throw new IllegalArgumentException( "Unable to attach to camera with LensFacing " + LensFacing.BACK, e); } mCamera = cameraFactory.getCamera(mCameraId); CameraX.init(context, config); mHandlerThread = new HandlerThread("AnalysisThread"); mHandlerThread.start(); mHandler = new Handler(mHandlerThread.getLooper()); }
Source:
<code>public static PutRequest readFrom(DataInputStream stream, ClusterMap map) throws IOException { int correlationId = stream.readInt(); String clientId = Utils.readIntString(stream); BlobId id = new BlobId(stream, map); BlobProperties properties = BlobPropertiesSerDe.getBlobPropertiesFromStream(stream); ByteBuffer metadata = Utils.readIntBuffer(stream); <START> InputStream data = stream; <END> return new PutRequest(correlationId, clientId, id, properties, metadata, data, properties.getBlobSize(), BlobDataType.DataBlob, Put_Request_Version_V1); }</code><technical_language>redundant line</technical_language>

Target:
static PutRequest readFrom(DataInputStream stream, ClusterMap map) throws IOException { int correlationId = stream.readInt(); String clientId = Utils.readIntString(stream); BlobId id = new BlobId(stream, map); BlobProperties properties = BlobPropertiesSerDe.getBlobPropertiesFromStream(stream); ByteBuffer metadata = Utils.readIntBuffer(stream); return new PutRequest(correlationId, clientId, id, properties, metadata, stream, properties.getBlobSize(), BlobType.DataBlob, Put_Request_Version_V1); }
Source:
<code>public static void testChangeInterestRateForActiveRevolvingCreditLoans() throws MambuApiException { methodName = new Object() {}.getClass().getEnclosingMethod().getName(); System.out.println("\nIn " + methodName); LoansService loanService = MambuAPIFactory.getLoanService(); AccountState accountState = loanService.getLoanAccount(NEW_LOAN_ACCOUNT_ID).getAccountState(); LoanProductType loanProductType = demoProduct.getLoanProductType(); if (loanProductType.equals(LoanProductType.REVOLVING_CREDIT) && accountState.equals(AccountState.ACTIVE)) { JSONTransactionRequest jsonTransactionRequest = new JSONTransactionRequest(); Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.MONTH, 1); jsonTransactionRequest.setDate(calendar.getTime()); jsonTransactionRequest.setRate(new BigDecimal(10)); jsonTransactionRequest .setNotes("Interest rate changet through API to be " + jsonTransactionRequest.getRate() + "%"); LoanTransaction loanTransaction = loanService.postInterestRateChange(NEW_LOAN_ACCOUNT_ID, LoanTransactionType.INTEREST_RATE_CHANGED, jsonTransactionRequest); <START> System.out.println("The interest rate was edited for the loan account " + NEW_LOAN_ACCOUNT_ID <END> + ". Transaction ID = " + loanTransaction); } else { System.out.println( "The loan account does not meet the prerequisites, therefore its interest rate will not be updated."); } }</code><technical_language>please log transaction ID here, instead of entire transaction</technical_language>

Target:
public static void testChangeInterestRateForActiveRevolvingCreditLoans() throws MambuApiException { methodName = new Object() {}.getClass().getEnclosingMethod().getName(); System.out.println("\nIn " + methodName); LoansService loanService = MambuAPIFactory.getLoanService(); AccountState accountState = loanService.getLoanAccount(NEW_LOAN_ACCOUNT_ID).getAccountState(); LoanProductType loanProductType = demoProduct.getLoanProductType(); if (loanProductType.equals(LoanProductType.REVOLVING_CREDIT) && accountState.equals(AccountState.ACTIVE)) { JSONTransactionRequest jsonTransactionRequest = new JSONTransactionRequest(); Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.MONTH, 1); jsonTransactionRequest.setDate(calendar.getTime()); jsonTransactionRequest.setRate(new BigDecimal(10)); jsonTransactionRequest .setNotes("Interest rate changed through API to be " + jsonTransactionRequest.getRate() + "%"); LoanTransaction loanTransaction = loanService.postInterestRateChange(NEW_LOAN_ACCOUNT_ID, jsonTransactionRequest); System.out.println("The interest rate was edited for the loan account " + NEW_LOAN_ACCOUNT_ID + ". Transaction ID = " + loanTransaction.getTransactionId()); } else { System.out.println( "The loan account does not meet the prerequisites, therefore its interest rate will not be updated."); } }
Source:
<code>protected boolean buildAndCheckDestStorageDomains() { if (diskInfoDestinationMap.isEmpty() && !fillDestMap()) { return false; } else if (!validateProvidedDestinations()) { <START> return false; <END> } if (getImagesToCheckDestinationStorageDomains().size() != diskInfoDestinationMap.size()) { log.error("Can not find any default active domain for one of the disks of template with id '{}'", vmDisksSource.getId()); return failValidation(EngineMessage.ACTION_TYPE_FAILED_MISSED_STORAGES_FOR_SOME_DISKS); } return validateIsImagesOnDomains(); }</code><technical_language>check validateProvidedDestinations in case: diskInfoDestinationMap.isEmpty() == true fillDestMap() == true is do before, safe replacing if-else statement with: if (..) { return false; } if (...) { return false; }</technical_language>

Target:
protected boolean buildAndCheckDestStorageDomains() { if (diskInfoDestinationMap.isEmpty()) { if (!fillDestMap()) { return false; } } else if (!validateProvidedDestinations()) { return false; } if (getImagesToCheckDestinationStorageDomains().size() != diskInfoDestinationMap.size()) { log.error("Can not find any default active domain for one of the disks of template with id '{}'", vmDisksSource.getId()); return failValidation(EngineMessage.ACTION_TYPE_FAILED_MISSED_STORAGES_FOR_SOME_DISKS); } return validateIsImagesOnDomains(); }
Source:
<code>public void testCleanStatefulCheckpoint() throws Exception { prepareClient(SimpleCheckpointManagerClient.RequestType.CLEAN_STATEFUL_CHECKOINTS); runClient(simpleCheckpointManagerClient); Thread.sleep(2 * 1000); verify(backendStorage).dispose(anyString(), anyString(), anyBoolean()); Message response = simpleCheckpointManagerClient.getResponse(); <START> Assert.assertTrue(response instanceof CheckpointManager.CleanStatefulCheckpointResponse); <END> Assert.assertEquals(StatusCode.OK, simpleCheckpointManagerClient.getResponseStatus()); }</code><technical_language>static imports for Assert.assertFoo calls improve readability</technical_language>

Target:
public void testCleanStatefulCheckpoint() throws Exception { prepareClient(SimpleCheckpointManagerClient.RequestType.CLEAN_STATEFUL_CHECKOINTS); runClient(simpleCheckpointManagerClient); finishedSignal.await(2, TimeUnit.SECONDS); verify(backendStorage).dispose(anyString(), anyString(), anyBoolean()); Message response = simpleCheckpointManagerClient.getResponse(); assertTrue(response instanceof CheckpointManager.CleanStatefulCheckpointResponse); assertEquals(StatusCode.OK, simpleCheckpointManagerClient.getResponseStatus()); }
Source:
<code>public void testHuffmanByteHelper() throws IOException { <START> int size = 100; <END> HuffmanParamsCalculator cal = new HuffmanParamsCalculator(); for (byte i = Byte.MIN_VALUE; i < Byte.MAX_VALUE; i++) { cal.add(i, (i + Byte.MIN_VALUE )/3 + 1); } cal.calculate(); HuffmanByteHelper helper = new HuffmanByteHelper(cal.getValuesAsBytes(), cal.getBitLens()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); DefaultBitOutputStream bos = new DefaultBitOutputStream(baos); for (int i = 0; i < size; i++) { for (byte b : cal.getValuesAsBytes()) { helper.write(bos, b); } } bos.close(); ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); DefaultBitInputStream bis = new DefaultBitInputStream(bais); int counter = 0; for (int i = 0; i < size; i++) { for (byte b : cal.getValuesAsBytes()) { byte v = helper.read(bis); if (v != b) { Assert.fail("Mismatch: " + v + " vs " + b + " at " + counter); } counter++; } } }</code><technical_language>final int</technical_language>

Target:
public void testHuffmanByteHelper() throws IOException { final int size = 100; final HuffmanParamsCalculator cal = new HuffmanParamsCalculator(); for (byte i = Byte.MIN_VALUE; i < Byte.MAX_VALUE; i++) { cal.add(i, (i + Byte.MIN_VALUE )/3 + 1); } cal.calculate(); final HuffmanByteHelper helper = new HuffmanByteHelper(cal.getValuesAsBytes(), cal.getBitLens()); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final DefaultBitOutputStream bos = new DefaultBitOutputStream(baos); for (int i = 0; i < size; i++) { for (final byte b : cal.getValuesAsBytes()) { helper.write(bos, b); } } bos.close(); final ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); final DefaultBitInputStream bis = new DefaultBitInputStream(bais); int counter = 0; for (int i = 0; i < size; i++) { for (final byte b : cal.getValuesAsBytes()) { final byte v = helper.read(bis); if (v != b) { Assert.fail("Mismatch: " + v + " vs " + b + " at " + counter); } counter++; } } }
Source:
<code>private void startEnvironment(Environment environment, String workspaceId, boolean recover) throws BadRequestException, ServerException, NotFoundException, ConflictException { final List<? extends MachineConfig> machineConfigs = new ArrayList<>(environment.getMachineConfigs()); final MachineConfig devCfg = findDev(machineConfigs); final MachineImpl devMachine; try { devMachine = createMachine(devCfg, workspaceId, environment.getName(), recover); } catch (MachineException | BadRequestException | NotFoundException | SnapshotException | ConflictException ex) { doRemoveWorkspace(workspaceId); throw ex; } lock.writeLock().lock(); try { addRunningMachine(devMachine); final RuntimeWorkspaceImpl workspace = idToWorkspaces.get(workspaceId); <START> if (workspace != null) { <END> workspace.setStatus(RUNNING); } } finally { lock.writeLock().unlock(); } machineConfigs.remove(devCfg); for (MachineConfig nonDevCfg : machineConfigs) { try { addRunningMachine(createMachine(nonDevCfg, workspaceId, environment.getName(), recover)); } catch (MachineException | BadRequestException | NotFoundException | SnapshotException | ConflictException ex) { LOG.error(format("Error while creating machine '%s' in workspace '%s', environment '%s'", nonDevCfg.getName(), workspaceId, environment.getName()), ex); } } }</code><technical_language>is this normal if workspace null</technical_language>

Target:
private void startEnvironment(Environment environment, String workspaceId, boolean recover) throws BadRequestException, ServerException, NotFoundException, ConflictException { final List<? extends MachineConfig> machineConfigs = new ArrayList<>(environment.getMachineConfigs()); final MachineConfig devCfg = findDev(machineConfigs); final MachineImpl devMachine; try { devMachine = createMachine(devCfg, workspaceId, environment.getName(), recover); } catch (MachineException | BadRequestException | NotFoundException | SnapshotException | ConflictException ex) { doRemoveWorkspace(workspaceId); throw ex; } lock.writeLock().lock(); try { if (!addRunningMachine(devMachine)) { throw new ServerException("Workspace '" + workspaceId + "' had been stopped before its dev-machine was started"); } idToWorkspaces.get(workspaceId).setStatus(RUNNING); } finally { lock.writeLock().unlock(); } machineConfigs.remove(devCfg); for (MachineConfig nonDevCfg : machineConfigs) { try { final MachineImpl nonDevMachine = createMachine(nonDevCfg, workspaceId, environment.getName(), recover); if (!addRunningMachine(nonDevMachine)) { if (!isStopped) { machineManager.destroy(nonDevMachine.getId(), false); } throw new ServerException("Workspace '" + workspaceId + "' had been stopped before all its machines were started"); } } catch (MachineException | BadRequestException | NotFoundException | SnapshotException | ConflictException ex) { LOG.error(format("Error while creating machine '%s' in workspace '%s', environment '%s'", nonDevCfg.getName(), workspaceId, environment.getName()), ex); } } }
Source:
<code>public static HibernateOrmBootstrapIntrospector create(Metadata metadata, ReflectionManager ormReflectionManager, ConfigurationPropertySource propertySource) { Collection<PersistentClass> persistentClasses = metadata.getEntityBindings() .stream() .filter( PersistentClass::hasPojoRepresentation ) <START> .filter( persistentClass -> !"org.hibernate.envers.DefaultRevisionEntity".equals( persistentClass.getClassName() ) ) <END> .collect( Collectors.toList() ); Map<Class<?>, HibernateOrmBasicTypeMetadata> typeMetadata = new HashMap<>(); collectPersistentTypes( typeMetadata, metadata.getEntityBindings() ); for ( PersistentClass persistentClass : persistentClasses ) { collectEmbeddedTypesRecursively( typeMetadata, persistentClass.getIdentifier() ); collectEmbeddedTypesRecursively( typeMetadata, persistentClass.getPropertyIterator() ); } MethodHandles.Lookup lookup = MethodHandles.publicLookup(); HibernateOrmReflectionStrategyName reflectionStrategyName = REFLECTION_STRATEGY.get( propertySource ); ValueReadHandleFactory valueReadHandleFactory; switch ( reflectionStrategyName ) { case JAVA_LANG_REFLECT: valueReadHandleFactory = ValueReadHandleFactory.usingJavaLangReflect(); break; case METHOD_HANDLE: valueReadHandleFactory = ValueReadHandleFactory.usingMethodHandle( lookup ); break; default: throw new AssertionFailure( "Unexpected reflection strategy name: " + reflectionStrategyName ); } return new HibernateOrmBootstrapIntrospector( typeMetadata, ormReflectionManager, valueReadHandleFactory ); }</code><technical_language>need explicitly exclude DefaultRevisionEntity? I issue other "non-pojo" persistent classes, i.e. trigger NPE, annotated @Indexed Hibernate Search ignore in end (it collect metadata forget it)</technical_language>

Target:
public static HibernateOrmBootstrapIntrospector create(Metadata metadata, ReflectionManager ormReflectionManager, ConfigurationPropertySource propertySource) { Collection<PersistentClass> persistentClasses = metadata.getEntityBindings() .stream() .filter( PersistentClass::hasPojoRepresentation ) .collect( Collectors.toList() ); Map<Class<?>, HibernateOrmBasicTypeMetadata> typeMetadata = new HashMap<>(); collectPersistentTypes( typeMetadata, persistentClasses ); for ( PersistentClass persistentClass : persistentClasses ) { collectEmbeddedTypesRecursively( typeMetadata, persistentClass.getIdentifier() ); collectEmbeddedTypesRecursively( typeMetadata, persistentClass.getPropertyIterator() ); } MethodHandles.Lookup lookup = MethodHandles.publicLookup(); HibernateOrmReflectionStrategyName reflectionStrategyName = REFLECTION_STRATEGY.get( propertySource ); ValueReadHandleFactory valueReadHandleFactory; switch ( reflectionStrategyName ) { case JAVA_LANG_REFLECT: valueReadHandleFactory = ValueReadHandleFactory.usingJavaLangReflect(); break; case METHOD_HANDLE: valueReadHandleFactory = ValueReadHandleFactory.usingMethodHandle( lookup ); break; default: throw new AssertionFailure( "Unexpected reflection strategy name: " + reflectionStrategyName ); } return new HibernateOrmBootstrapIntrospector( typeMetadata, ormReflectionManager, valueReadHandleFactory ); }
Source:
<code>void validateQualifier(String qualifier) throws MojoFailureException { try { <START> Version.parseVersion(Version.emptyVersion + <END> "." + qualifier); } catch (IllegalArgumentException e) { throw new MojoFailureException( "Invalid build qualifier, it does not match the OSGi qualifier constraint ([0..9]|[a..zA..Z]|'_'|'-')"); } }</code><technical_language>This is valid empty version is defined "0.0.0". AFAIK "0" well. a "0.0.0" (or "1.0.0") constant here</technical_language>

Target:
void validateQualifier(String qualifier) throws MojoFailureException { try { Version.parseVersion("1.0.0." + qualifier); } catch (IllegalArgumentException e) { throw new MojoFailureException( "Invalid build qualifier, it does not match the OSGi qualifier constraint ([0..9]|[a..zA..Z]|'_'|'-')"); } }
Source:
<code><START> public List<AddOn> getNewAddOns() { <END> if (this.getPreviousVersionInfo() != null) { return this.getPreviousVersionInfo().getNewAddOns(this.getLatestVersionInfo()); } return getLocalVersionInfo().getNewAddOns(this.getLatestVersionInfo()); }</code><technical_language>Ditto (same for new methods)</technical_language>

Target:
protected List<AddOn> getNewAddOns() { if (this.getPreviousVersionInfo() != null) { return this.getPreviousVersionInfo().getNewAddOns(this.getLatestVersionInfo()); } return getLocalVersionInfo().getNewAddOns(this.getLatestVersionInfo()); }
Source:
<code>private byte[] getSerializedEntity(ClientRequest request) { ClientRequest requestCopy = new ClientRequest(request); final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); requestCopy.setStreamProvider(new OutboundMessageContext.StreamProvider() { @Override public OutputStream getOutputStream(int contentLength) { return outputStream; } }); try { requestCopy.writeEntity(); } catch (IOException e) { <START> throw new WebApplicationException("Error reading content during signature"); <END> } return outputStream.toByteArray(); }</code><technical_language>Please wrap IOException</technical_language>

Target:
private byte[] getSerializedEntity(ClientRequest request) { ClientRequest requestCopy = new ClientRequest(request); final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); requestCopy.setStreamProvider(new OutboundMessageContext.StreamProvider() { @Override public OutputStream getOutputStream(int contentLength) { return outputStream; } }); try { requestCopy.writeEntity(); } catch (IOException ioe) { throw new WebApplicationException("Error reading content during signature", ioe); } return outputStream.toByteArray(); }
Source:
<code>protected static ILabel[] getLabels(IASTFunctionDefinition functionDefinition) { FindLabelsAction action = new FindLabelsAction(); functionDefinition.accept(action); ILabel[] result = <START> null; <END> if (action.labels != null) { for (int i = 0; i < action.labels.length && action.labels[i] != null; i++) { IASTLabelStatement labelStatement = action.labels[i]; IBinding binding = labelStatement.getName().resolveBinding(); if (binding != null) result = ArrayUtil.append(ILabel.class, result, (ILabel) binding); } } return ArrayUtil.trim(ILabel.class, result); }</code><technical_language>initialize ILabel.EMPTY_LABEL_ARRAY</technical_language>

Target:
protected static IBinding[] getLabels(IASTFunctionDefinition functionDefinition) { FindLabelsAction action = new FindLabelsAction(); functionDefinition.accept(action); IBinding[] result = ILabel.EMPTY_LABEL_ARRAY; if (action.labels != null) { for (int i = 0; i < action.labels.length && action.labels[i] != null; i++) { IASTLabelStatement labelStatement = (IASTLabelStatement) action.labels[i]; IBinding binding = labelStatement.getName().resolveBinding(); if (binding != null) result = ArrayUtil.append(result, (ILabel) binding); } } return ArrayUtil.trim(result); }
Source:
<code>public void add(T value) { this.elements.add(new ValueInfo<T>(Instant.now(), value)); <START> this.listGaugeEvictionPolicy.elementAddedCallback(); <END> }</code><technical_language>is a need for 2 types of evictions (size, time), I if do evictions inline add? need a separate interface then. This preferable approach. If need interface for a pluggable eviction policy, lines of: public class EvictionPolicy<T> { void evict(Iterable<TimestampedValue<T>> currentElements); } instead of public class ListGaugeEvictionPolicy<T> { public void elementAddedCallback(); }</technical_language>

Target:
public void add(T value) { this.elements.add(new TimestampedValue<T>(value, Instant.now().toEpochMilli())); this.evict(); }
Source:
<code>private Properties createJobProps(String topic, Path folder, DateTime folderHour, Path outputDir, FileSystem fs, CamusSweeperMetrics metrics) throws IOException { <START> Properties jobProps = new Properties(props); <END> jobProps.putAll(props); jobProps.put("topic", topic); String topicAndHour = topic + ":" + folderHour.toString(hourFormatter); jobProps.put(CamusHourlySweeper.TOPIC_AND_HOUR, topicAndHour); long dataSize = fs.getContentSummary(folder).getLength(); metrics.dataSizeByTopic.put(topicAndHour, dataSize); metrics.totalDataSize += dataSize; List<Path> sourcePaths = new ArrayList<Path>(); sourcePaths.add(folder); Path destPath = new Path(outputDir, folderHour.toString(hourFormatter)); jobProps.put(CamusHourlySweeper.INPUT_PATHS, pathListToCommaSeperated(sourcePaths)); jobProps.put(CamusHourlySweeper.DEST_PATH, destPath.toString()); if (!fs.exists(destPath)) { LOG.info(topic + " dest dir " + destPath.toString() + " doesn't exist. Processing."); return jobProps; } else if (sourceDirHasOutliers(fs, sourcePaths, destPath)) { LOG.info("found outliers for topic " + topic + ". Will add outliers to " + destPath.toString()); this.outlierProperties.add(jobProps); return null; } else { LOG.info(topic + " dest dir " + destPath.toString() + " already exists. Skipping."); return null; } }</code><technical_language>create empty Properties new Properties(). single parameter is for default</technical_language>

Target:
private Properties createJobProps(String topic, Path folder, DateTime folderHour, Path outputDir, FileSystem fs, CamusSweeperMetrics metrics) throws IOException { Properties jobProps = new Properties(); jobProps.putAll(props); jobProps.put("topic", topic); String topicAndHour = topic + ":" + folderHour.toString(hourFormatter); jobProps.put(CamusHourlySweeper.TOPIC_AND_HOUR, topicAndHour); long dataSize = fs.getContentSummary(folder).getLength(); metrics.recordDataSizeByTopic(topicAndHour, dataSize); metrics.addToTotalDataSize(dataSize); List<Path> sourcePaths = new ArrayList<Path>(); sourcePaths.add(folder); Path destPath = new Path(outputDir, folderHour.toString(hourFormatter)); jobProps.put(CamusHourlySweeper.INPUT_PATHS, pathListToCommaSeperated(sourcePaths)); jobProps.put(CamusHourlySweeper.DEST_PATH, destPath.toString()); if (!fs.exists(destPath)) { LOG.info(topic + " dest dir " + destPath.toString() + " doesn't exist. Processing."); return jobProps; } else if (sourceDirHasOutliers(fs, sourcePaths, destPath)) { LOG.info("found outliers for topic " + topic + ". Will add outliers to " + destPath.toString()); this.outlierProperties.add(jobProps); return null; } else { LOG.info(topic + " dest dir " + destPath.toString() + " already exists. Skipping."); return null; } }
Source:
<code>public void deleteMultipleKeysWithQueryParam() throws Exception { putAll(); <START> assertThat(customerRegion.size()).isEqualTo(60); <END> assertThat(customerRegion.containsKey("2")).isTrue(); assertThat(customerRegion.containsKey("3")).isTrue(); assertThat(customerRegion.containsKey("4")).isTrue(); assertThat(customerRegion.containsKey("5")).isTrue(); mockMvc.perform(delete("/v1/customers?keys=2,3,4,5") .with(POST_PROCESSOR)) .andExpect(status().isOk()); assertThat(customerRegion.size()).isEqualTo(60 - 4); assertThat(customerRegion.containsKey("2")).isFalse(); assertThat(customerRegion.containsKey("3")).isFalse(); assertThat(customerRegion.containsKey("4")).isFalse(); assertThat(customerRegion.containsKey("5")).isFalse(); }</code><technical_language>I AssertJ's Map assertions regions: assertThat(customerRegion) .hasSize(60) .containsKeys("2", "3", "4", "5"); This assertion failures more helpful</technical_language>

Target:
public void deleteMultipleKeysWithQueryParam() throws Exception { putAll(); mockMvc.perform(delete("/v1/customers?keys=2,3,4,5") .with(POST_PROCESSOR)) .andExpect(status().isOk()); assertThat(customerRegion).hasSize(60 - 4); assertThat(customerRegion.containsKey("2")).isFalse(); assertThat(customerRegion.containsKey("3")).isFalse(); assertThat(customerRegion.containsKey("4")).isFalse(); assertThat(customerRegion.containsKey("5")).isFalse(); }
Source:
<code>public int getHoldingIndexForSymbol(String symbol) { boolean positionContainsHolding = false; Holding hold = null; <START> for (Holding h : this.position){ <END> if (h.getStockSymbol().equals(symbol)) { hold = h; positionContainsHolding = true; break; } } if (!positionContainsHolding) { hold = new Holding(symbol, 0); this.position.add(hold); } return position.indexOf(hold); }</code><technical_language>h is descriptive. Change appropriately</technical_language>

Target:
public int getHoldingIndexForSymbol(String symbol) { boolean positionContainsHolding = false; Holding hold = null; for (Holding holding : this.position){ if (holding.getStockSymbol().equals(symbol)) { hold = holding; positionContainsHolding = true; break; } } if (!positionContainsHolding) { hold = new Holding(symbol, 0); this.position.add(hold); } return position.indexOf(hold); }
Source:
<code>public BoundCurveExtrapolator bind(DoubleArray xValues, DoubleArray yValues, BoundCurveInterpolator interpolator) { <START> ArgChecker.isTrue(interpolator instanceof MathBoundCurveInterpolator, <END> "Interpolator must be ImmutableBoundCurveInterpolator"); Interpolator1D interp = ((MathBoundCurveInterpolator) interpolator).getInterpolator(); Interpolator1DDataBundle data = ((MathBoundCurveInterpolator) interpolator).getDataBundle(); ArgChecker.isTrue(interp instanceof ProductPiecewisePolynomialInterpolator1D, "Interpolator must be ProductPiecewisePolynomialInterpolator1D"); ArgChecker.isTrue(data instanceof Interpolator1DPiecewisePoynomialWithExtraKnotsDataBundle, "Interpolator data must be Interpolator1DPiecewisePoynomialWithExtraKnotsDataBundle"); return new Bound( function, (ProductPiecewisePolynomialInterpolator1D) interp, (Interpolator1DPiecewisePoynomialWithExtraKnotsDataBundle) data); }</code><technical_language>type in instanceof check match type in error message</technical_language>

Target:
public BoundCurveExtrapolator bind(DoubleArray xValues, DoubleArray yValues, BoundCurveInterpolator interpolator) { ArgChecker.isTrue(interpolator instanceof StandardBoundCurveInterpolator, "Interpolator must be StandardBoundCurveInterpolator"); Interpolator1D interp = ((StandardBoundCurveInterpolator) interpolator).getInterpolator(); Interpolator1DDataBundle data = ((StandardBoundCurveInterpolator) interpolator).getDataBundle(); ArgChecker.isTrue(interp instanceof ProductPiecewisePolynomialInterpolator1D, "Interpolator must be ProductPiecewisePolynomialInterpolator1D"); ArgChecker.isTrue(data instanceof Interpolator1DPiecewisePoynomialWithExtraKnotsDataBundle, "Interpolator data must be Interpolator1DPiecewisePoynomialWithExtraKnotsDataBundle"); return new Bound( function, (ProductPiecewisePolynomialInterpolator1D) interp, (Interpolator1DPiecewisePoynomialWithExtraKnotsDataBundle) data); }
Source:
<code>public Stream<Tuple> getAllMatches(Object[] parameters) { <START> return matchAll(parameters, notNull(parameters)).stream(); <END> }</code><technical_language>matchAll internally copy entire match set, in case of hybrid matching, this perform expected</technical_language>

Target:
public Stream<Tuple> getAllMatches(Object[] parameters) { return matchAll(parameters, notNull(parameters)); }
Source:
<code>private static String createAllLocationsMessage(List<Location> locations) { if (locations == null) { return "\n"; } StringBuilder sb = new StringBuilder(); for (Location invocation : locations) { <START> sb.append(invocation).append("\n"); <END> } return sb.toString(); }</code><technical_language>infocation -> location</technical_language>

Target:
private static String createAllLocationsMessage(List<Location> locations) { if (locations == null) { return "\n"; } StringBuilder sb = new StringBuilder(); for (Location location : locations) { sb.append(location).append("\n"); } return sb.toString(); }
Source:
<code><START> protected void executeCommand() { <END> VDSReturnValue vdsReturnaValue = Backend.getInstance().getResourceManager() .RunVdsCommand(VDSCommandType.StopRebalanceGlusterVolume, new GlusterVolumeVDSParameters(upServer.getId(), getGlusterVolumeName())); setSucceeded(vdsReturnaValue.getSucceeded()); if (!getSucceeded()) { handleVdsError(AuditLogType.GLUSTER_VOLUME_REBALANCE_STOP_FAILED, vdsReturnaValue.getVdsError() .getMessage()); return; } endStepJob(); clearVolumeTaskAndReleaseLock(); getReturnValue().setActionReturnValue(vdsReturnaValue); }</code><technical_language>runVdsCommand method of superclass</technical_language>

Target:
protected void executeCommand() { VDSReturnValue vdsReturnaValue = runVdsCommand(VDSCommandType.StopRebalanceGlusterVolume, new GlusterVolumeVDSParameters(upServer.getId(), getGlusterVolumeName())); setSucceeded(vdsReturnaValue.getSucceeded()); if (!getSucceeded()) { handleVdsError(AuditLogType.GLUSTER_VOLUME_REBALANCE_STOP_FAILED, vdsReturnaValue.getVdsError() .getMessage()); return; } endStepJob(); clearVolumeTaskAndReleaseLock(); getReturnValue().setActionReturnValue(vdsReturnaValue); }
Source:
<code>public void run() { <START> while (true) { <END> try { this.install(); System.exit(0); } catch (InterruptedException e) { logger.warn("Aborting installation"); System.exit(1); } catch (Exception e) { e.printStackTrace(); logger.warn("Schema installer failed, retry again in " + waitRetry + "seconds."); } } }</code><technical_language>I this end running stopping, of versionUpdateMaxRetries for this cycle (or some new variable)</technical_language>

Target:
public void run() { int retryCounter = 0; while (retryCounter < jobMaxRetries) { try { this.install(); System.exit(0); } catch (InterruptedException e) { logger.warn("Aborting installation"); System.exit(1); } catch (Exception e) { retryCounter++; logger.error("Schema installer failed on retry " + retryCounter + " of " + jobMaxRetries + ", retry again."); if (retryCounter >= jobMaxRetries) { e.printStackTrace(); System.exit(1); } } } }
Source:
<code>private void nullifyInternalProxies() { if (privatemIrsProxy != null) { <START> if (IrsServerWrapper.class.isInstance(privatemIrsProxy)) { <END> XmlRpcUtils.shutDownConnection(((IrsServerWrapper) privatemIrsProxy).getHttpClient()); } else { ((JsonRpcIIrsServer) privatemIrsProxy).close(); } } privatemCurrentIrsHost = null; privatemIrsProxy = null; mCurrentVdsId = null; }</code><technical_language>a part of shared dispose method? do u want reuse code somehow</technical_language>

Target:
private void nullifyInternalProxies() { if (irsProxy != null) { if (IrsServerWrapper.class.isInstance(irsProxy)) { XmlRpcUtils.shutDownConnection(((IrsServerWrapper) irsProxy).getHttpClient()); } else { ((JsonRpcIIrsServer) irsProxy).close(); } } privatemCurrentIrsHost = null; irsProxy = null; mCurrentVdsId = null; }
Source:
<code>public void kill(StreamApplication app) { try { ProcessorGraph processorGraph = getExecutionPlan(app); processorGraph.getProcessorNodes().forEach(processor -> { Config processorConfig = processor.generateConfig(); <START> log.info("Killing processor with config {}", processor.getId(), processorConfig); <END> JobRunner runner = new JobRunner(processorConfig); runner.kill(); }); } catch (Throwable t) { throw new SamzaException("Failed to kill application", t); } }</code><technical_language>need log entire config here. Is more specific log</technical_language>

Target:
public void kill(StreamApplication app) { try { ProcessorGraph processorGraph = getExecutionPlan(app); processorGraph.getProcessorNodes().forEach(processor -> { Config processorConfig = processor.generateConfig(); log.info("Killing processor {}", processor.getId()); JobRunner runner = new JobRunner(processorConfig); runner.kill(); }); } catch (Throwable t) { throw new SamzaException("Failed to kill application", t); } }
Source:
<code>public void testJsonRemove() { assertJsonRemove(is("{\"b\":[2]}"), <START> SqlFunctions.dejsonize("{\"a\": 1, \"b\": [2]}"), <END> "$.a"); }</code><technical_language>Please SqlFunctions.jsonValueExpression(String ...) instead</technical_language>

Target:
public void testJsonRemove() { assertJsonRemove( SqlFunctions.jsonValueExpression("{\"a\": 1, \"b\": [2]}"), new Object[]{"$.a"}, is("{\"b\":[2]}")); assertJsonRemove( SqlFunctions.jsonValueExpression("{\"a\": 1, \"b\": [2]}"), new Object[]{"$.a", "$.b"}, is("{}")); }
Source:
<code>static void instantiateMetaspaceMemoryMetrics(final MetricGroup parentMetricGroup) { final List<MemoryPoolMXBean> memoryPoolMXBeans = ManagementFactory.getMemoryPoolMXBeans() .stream() .filter(bean -> "Metaspace".equals(bean.getName())) .collect(Collectors.toList()); if (memoryPoolMXBeans.isEmpty()) { <START> LOG.warn("No memory pool named 'Metaspace' is present. The '{}' metric group is not going to be instantiated.", METRIC_GROUP_METASPACE_NAME); <END> return; } final MetricGroup metricGroup = parentMetricGroup.addGroup(METRIC_GROUP_METASPACE_NAME); final Iterator<MemoryPoolMXBean> beanIterator = memoryPoolMXBeans.iterator(); final MemoryPoolMXBean firstPool = beanIterator.next(); instantiateMemoryUsageMetrics(metricGroup, firstPool::getUsage); if (beanIterator.hasNext()) { LOG.warn("More than one memory pool named '{}' are present. Only the first pool was used for instantiating the metric.", METRIC_GROUP_METASPACE_NAME); } }</code><technical_language>suggestion LOG.info("Metaspace metrics exposed pool named 'Metaspace' found. This due JVM."); Users typically warning do about, message is cryptic ("what is a metric group? is consequence of instantiated?"</technical_language>

Target:
static void instantiateMetaspaceMemoryMetrics(final MetricGroup parentMetricGroup) { final List<MemoryPoolMXBean> memoryPoolMXBeans = ManagementFactory.getMemoryPoolMXBeans() .stream() .filter(bean -> "Metaspace".equals(bean.getName())) .collect(Collectors.toList()); if (memoryPoolMXBeans.isEmpty()) { LOG.info("The '{}' metrics will not be exposed because no pool named 'Metaspace' could be found. This might be caused by the used JVM.", METRIC_GROUP_METASPACE_NAME); return; } final MetricGroup metricGroup = parentMetricGroup.addGroup(METRIC_GROUP_METASPACE_NAME); final Iterator<MemoryPoolMXBean> beanIterator = memoryPoolMXBeans.iterator(); final MemoryPoolMXBean firstPool = beanIterator.next(); instantiateMemoryUsageMetrics(metricGroup, firstPool::getUsage); if (beanIterator.hasNext()) { LOG.debug("More than one memory pool named 'Metaspace' is present. Only the first pool was used for instantiating the '{}' metrics.", METRIC_GROUP_METASPACE_NAME); } }