auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void onCreate() { super.onCreate(); CrashlyticsCore core = new CrashlyticsCore.Builder() .disabled(BuildConfig.DEBUG) .build(); Fabric.with(this, new Crashlytics.Builder().core(core).build()); if (BuildConfig.DEBUG) { Timber.plant(new Timber.DebugTree()); } <START> Timber.plant(new CrashlyticsTree()); <END> }</code><technical_language>logic want is "Crashlytics devices, not-Crashlytics emulator, DEBUG-vs-RELEASE is a factor". Also, this needs done entry points program; services well. Check AndroidManifest.xml for inspiration, basically onCreate() implementations set Crashlytics. Feel free copy code / copy entire files relicense for Bankdroid if want: <LINK_1> <LINK_0></technical_language>

Target:
public void onCreate() { super.onCreate(); LoggingUtils.createLogger(this); }
Source:
<code><START> public static byte[] readContent(final InputStream inputStream) throws IOException { <END> final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); int read = inputStream.read(); while (read != -1) { byteArrayOutputStream.write(read); read = inputStream.read(); } return byteArrayOutputStream.toByteArray(); }</code><technical_language>Add null-check for inputStream</technical_language>

Target:
public static byte[] readContent(final InputStream inputStream) throws IOException { Assert.requireNonNull(inputStream, "inputStream"); final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); int read = inputStream.read(); while (read != -1) { byteArrayOutputStream.write(read); read = inputStream.read(); } return byteArrayOutputStream.toByteArray(); }
Source:
<code>public static String[] getOptionArguments(final String[] args) { final List<String> temporary = Arrays.asList(args); <START> final int index = temporary.indexOf(BARE_DOUBLE_DASH); <END> if (index == -1) { return args; } else if (index == 0) { return new String[0]; } else { return temporary.subList(0, index).toArray(new String[index]); } }</code><technical_language>late tired I totally this I feel this done in a single pass save conversions checks. iterate array write item a resultant array encounter double dash return result array</technical_language>

Target:
public static String[] getOptionArguments(final String[] args) { final List<String> temporary = new ArrayList<>(args.length); for (int i = 0; i < args.length; i++) { if (BARE_DOUBLE_DASH.equals(args[i])) { break; } temporary.add(args[i]); } return temporary.toArray(new String[temporary.size()]); }
Source:
<code>public String getArticlesPerMonth(@SiteParam Site site, @PathVariable String year, @PathVariable String month, @RequestParam String cursor, @RequestParam String pageNumber, Model model) throws IOException, ParseException { Map<String, ?> searchResult = (Map<String, Map>) articleArchiveServiceImpl .getArticleDoisPerMonth(site, year, month, cursor); model.addAttribute("month", month); model.addAttribute("year", year); model.addAttribute("searchResult", searchResult); model.addAttribute("nextCursorMark", searchResult.get("nextCursorMark")); int pageNumberCount = Integer.parseInt(pageNumber); final int listStartNumber = pageNumberCount * MAXIMUM_SOLR_RESULTS + 1; model.addAttribute("listStart", listStartNumber); final boolean isLastPage = (Double) searchResult.get("numFound") <START> <= listStartNumber + MAXIMUM_SOLR_RESULTS; <END> model.addAttribute("showMoreLink", !isLastPage); pageNumberCount = pageNumberCount + 1; model.addAttribute("pageNumber", pageNumberCount); return site + "/ftl/lockss/dois"; }</code><technical_language>I line 121 change <= < for comparison. suppose max-solr-results = 10, numFound = 61, results show in 7 pages. pageNumber=5 (it is index starting 0), listStartNumber = 5*10+1=51 (it is index starting 1), isLastPage = (61 <= 51+10) = true, is more page this one</technical_language>

Target:
public String getArticlesPerMonth(@SiteParam Site site, @PathVariable String year, @PathVariable String month, @RequestParam String cursor, @RequestParam String pageNumber, Model model) throws IOException, ParseException { Map<String, ?> searchResult = (Map<String, Map>) articleArchiveServiceImpl .getArticleDoisPerMonth(site, year, month, cursor); model.addAttribute("month", month); model.addAttribute("year", year); model.addAttribute("searchResult", searchResult); model.addAttribute("nextCursorMark", searchResult.get("nextCursorMark")); int pageNumberCount = Integer.parseInt(pageNumber); final int listStartNumber = pageNumberCount * MAXIMUM_SOLR_RESULTS + 1; model.addAttribute("listStart", listStartNumber); final boolean isLastPage = (Double) searchResult.get("numFound") < listStartNumber + MAXIMUM_SOLR_RESULTS; model.addAttribute("showMoreLink", !isLastPage); pageNumberCount = pageNumberCount + 1; model.addAttribute("pageNumber", pageNumberCount); return site + "/ftl/lockss/dois"; }
Source:
<code>public DomainShareReliable(String[][] rawHierarchy, String[] encodedValues, int[][] encodedHierarchy) { this.duplicates = new LongObjectOpenHashMap<BigFraction>(); this.shares = new BigFraction[encodedValues.length]; Arrays.fill(shares, NOT_AVAILABLE); @SuppressWarnings("unchecked") ObjectIntOpenHashMap<String>[] maps = new ObjectIntOpenHashMap[rawHierarchy[0].length]; for (int level = 0; level < maps.length; level++) { maps[level] = new ObjectIntOpenHashMap<String>(); } for (int value = 0; value < rawHierarchy.length; value++) { String[] transformation = rawHierarchy[value]; for (int level = 0; level < transformation.length; level++) { ObjectIntOpenHashMap<String> map = maps[level]; String key = transformation[level]; if (!map.containsKey(key)) { map.put(key, 0); } map.put(key, map.get(key) + 1); } } for (int row = 0; row < encodedHierarchy.length; row++) { int[] strategy = encodedHierarchy[row]; for (int level = 0; level < strategy.length; level++){ ObjectIntOpenHashMap<String> map = maps[level]; int value = strategy[level]; String keyString = encodedValues[value]; BigFraction share = new BigFraction(map.get(keyString), rawHierarchy.length); BigFraction stored = shares[value]; if (stored != NOT_AVAILABLE) { <START> if (stored == share) { <END> continue; } if (stored.compareTo(BigFraction.ZERO) >= 0) { shares[value] = shares[value].multiply(BigFraction.MINUS_ONE); } long dkey = (((long) value) << 32) | (level & 0xffffffffL); duplicates.put(dkey, share); } else { shares[value] = share; } } } }</code><technical_language>Please double check. I sure(!), stored.equals(share) for. This compares references</technical_language>

Target:
public DomainShareReliable(String[][] rawHierarchy, String[] encodedValues, int[][] encodedHierarchy) { this.duplicates = new LongObjectOpenHashMap<BigFraction>(); this.shares = new BigFraction[encodedValues.length]; Arrays.fill(shares, NOT_AVAILABLE); @SuppressWarnings("unchecked") ObjectIntOpenHashMap<String>[] maps = new ObjectIntOpenHashMap[rawHierarchy[0].length]; for (int level = 0; level < maps.length; level++) { maps[level] = new ObjectIntOpenHashMap<String>(); } for (int value = 0; value < rawHierarchy.length; value++) { String[] transformation = rawHierarchy[value]; for (int level = 0; level < transformation.length; level++) { ObjectIntOpenHashMap<String> map = maps[level]; String key = transformation[level]; if (!map.containsKey(key)) { map.put(key, 0); } map.put(key, map.get(key) + 1); } } for (int row = 0; row < encodedHierarchy.length; row++) { int[] strategy = encodedHierarchy[row]; for (int level = 0; level < strategy.length; level++){ ObjectIntOpenHashMap<String> map = maps[level]; int value = strategy[level]; String keyString = encodedValues[value]; BigFraction share = new BigFraction(map.get(keyString), rawHierarchy.length); BigFraction stored = shares[value]; if (stored != NOT_AVAILABLE) { if (stored.equals(share)) { continue; } if (stored.compareTo(BigFraction.ZERO) >= 0) { shares[value] = shares[value].multiply(BigFraction.MINUS_ONE); } long dkey = (((long) value) << 32) | (level & 0xffffffffL); duplicates.put(dkey, share); } else { shares[value] = share; } } } }
Source:
<code>protected boolean canDoAction() { if (getVds() == null) { return failCanDoAction(VdcBllMessages.VDS_NOT_EXIST); } if (getVds().getStatus() != VDSStatus.Up) { return failCanDoAction(VdcBllMessages.CANNOT_FORCE_SELECT_SPM_VDS_NOT_UP); } if (getStoragePoolForVds() == null) { return failCanDoAction(VdcBllMessages.CANNOT_FORCE_SELECT_SPM_VDS_NOT_IN_POOL); <START> } <END> if (getVds().getSpmStatus() != VdsSpmStatus.None) { return failCanDoAction(VdcBllMessages.CANNOT_FORCE_SELECT_SPM_VDS_ALREADY_SPM); } if (getVds().getVdsSpmPriority() == BusinessEntitiesDefinitions.HOST_MIN_SPM_PRIORITY) { return failCanDoAction(VdcBllMessages.CANNOT_FORCE_SELECT_SPM_VDS_MARKED_AS_NEVER_SPM); } if (getStoragePoolForVds().getStatus() != StoragePoolStatus.Up) { return failCanDoAction(VdcBllMessages.CANNOT_FORCE_SELECT_SPM_STORAGE_POOL_NOT_UP); } if (isAsyncTasksRunningOnPool(getStoragePoolForVds().getId())) { return failCanDoAction(VdcBllMessages.CANNOT_FORCE_SELECT_SPM_STORAGE_POOL_HAS_RUNNING_TASKS); } return true; }</code><technical_language>Also, this consolidated validation: new StoragePooLValidator(getStoragePoolForVds()).isUp() // checks existance :-)</technical_language>

Target:
protected boolean canDoAction() { if (getVds() == null) { return failCanDoAction(VdcBllMessages.VDS_NOT_EXIST); } if (getVds().getStatus() != VDSStatus.Up) { return failCanDoAction(VdcBllMessages.CANNOT_FORCE_SELECT_SPM_VDS_NOT_UP); } if (getStoragePoolForVds() == null) { return failCanDoAction(VdcBllMessages.CANNOT_FORCE_SELECT_SPM_VDS_NOT_IN_POOL); } if (getVds().getSpmStatus() != VdsSpmStatus.None) { return failCanDoAction(VdcBllMessages.CANNOT_FORCE_SELECT_SPM_VDS_ALREADY_SPM); } if (getVds().getVdsSpmPriority() == BusinessEntitiesDefinitions.HOST_MIN_SPM_PRIORITY) { return failCanDoAction(VdcBllMessages.CANNOT_FORCE_SELECT_SPM_VDS_MARKED_AS_NEVER_SPM); } if (!validate(new StoragePoolValidator(getStoragePoolForVds()).isUp())) { return false; } if (isAsyncTasksRunningOnPool(getStoragePoolForVds().getId())) { return failCanDoAction(VdcBllMessages.CANNOT_FORCE_SELECT_SPM_STORAGE_POOL_HAS_RUNNING_TASKS); } return true; }
Source:
<code>public void delayBeforeNextRetry(PollingStrategyContext pollingStrategyContext) throws InterruptedException { int requestNumber = pollingStrategyContext.getRetriesAttempted(); Double msToWait; if (requestNumber == 0) { <START> msToWait = THOUSAND * Math.min( Math.max(FIRST_POLL_RATIO * expectedRuntimeSeconds, STABLE_POLLING_INTERVAL_SECONDS_MIN), MAX_POLLING_INTERVAL_SECONDS); } else if (requestNumber == 1) { msToWait = THOUSAND * Math.min( Math.max(SECOND_POLL_RATIO * expectedRuntimeSeconds, STABLE_POLLING_INTERVAL_SECONDS_MIN), MAX_POLLING_INTERVAL_SECONDS); <END> } else { msToWait = THOUSAND * Math.max(STABLE_POLLING_INTERVAL_SECONDS_MIN, RANDOM.nextInt(STABLE_POLLING_INTERVAL_SECONDS_MAX)); } LOGGER.info("Polling attempt: {}, Sleeping for: {}ms for request: {}. ExpectedRuntime={}s", requestNumber, msToWait.longValue(), pollingStrategyContext.getOriginalRequest(), expectedRuntimeSeconds); Thread.sleep(msToWait.longValue()); }</code><technical_language>2 calculation change lifecycle of class, I moved constructor stored fields</technical_language>

Target:
public void delayBeforeNextRetry(PollingStrategyContext pollingStrategyContext) throws InterruptedException { int requestNumber = pollingStrategyContext.getRetriesAttempted(); long msToWait; if (requestNumber == 0) { msToWait = msToWaitRequest0; } else if (requestNumber == 1) { msToWait = msToWaitRequest1; } else { msToWait = (long) (THOUSAND * Math.max(STABLE_POLLING_INTERVAL_SECONDS_MIN, RANDOM.nextInt(STABLE_POLLING_INTERVAL_SECONDS_MAX))); } LOGGER.info("Polling attempt: {}, Sleeping for: {}ms for request: {}. ExpectedRuntime={}s", requestNumber, msToWait, pollingStrategyContext.getOriginalRequest(), expectedRuntimeSeconds); Thread.sleep(msToWait); }
Source:
<code>public boolean hasCapability(String capability) { <START> if (capability.equals(CAPABILITY_OFFHEAP) && isSubscriptionBasedLicense()) { <END> return true; } else { Long v = getLimit(capability); return v != null && v != 0; } }</code><technical_language>need override this enforcing 'altered' default in getLimit(String) method</technical_language>

Target:
public boolean hasCapability(String capability) { Long v = getLimit(capability); return v != null && v != 0; }
Source:
<code>void onBindFeedViewHolder(StatisticsHolder holder, int position) { DBReader.StatisticsItem statsItem = statisticsData.feeds.get(position - 1); Glide.with(context) .load(statsItem.feed.getImageLocation()) .apply(new RequestOptions() .placeholder(R.color.light_gray) .error(R.color.light_gray) .diskCacheStrategy(ApGlideSettings.AP_DISK_CACHE_STRATEGY) .fitCenter() .dontAnimate()) .into(holder.image); <START> holder.title.setText(statsItem.feed.getTitle()); <END> holder.value.setText(Converter.byteToString(statsItem.totalDownloadSize)); }</code><technical_language>Image title done in parent class</technical_language>

Target:
void onBindFeedViewHolder(StatisticsHolder holder, int position) { DBReader.StatisticsItem statsItem = statisticsData.feeds.get(position - 1); holder.value.setText(Converter.byteToString(statsItem.totalDownloadSize)); }
Source:
<code>default List<T> getItems() { IterableStream<T> iterableStream = this.getElements(); return iterableStream == null <START> ? null <END> : this.getElements().stream().collect(Collectors.toList()); }</code><technical_language>@JonathanGiles Do a guideline return empty collection return null? I noticed this in: <LINK_0> a other places. I personally prefer returning empty collection, items, whereas, do a null check, check for empty if return null</technical_language>

Target:
default List<T> getItems() { IterableStream<T> iterableStream = this.getElements(); return iterableStream == null ? new ArrayList<>() : this.getElements().stream().collect(Collectors.toList()); }
Source:
<code>public ByteBuffer subscriptionUserData(final Set<String> topics) { final TaskManager taskManager = taskManger(); taskManager.handleRebalanceStart(topics); if (usedSubscriptionMetadataVersion <= LATEST_SUPPORTED_VERSION) { return new SubscriptionInfo( usedSubscriptionMetadataVersion, <START> LATEST_SUPPORTED_VERSION + 1, <END> taskManager.processId(), userEndPoint(), taskManager.getTaskLags() ).encode(); } else { return new FutureSubscriptionInfo( usedSubscriptionMetadataVersion, taskManager.processId(), userEndPoint(), taskManager.getTaskLags()) .encode(); } }</code><technical_language>req: this deletion, REBALANCE_PROTOCOL defined line 66 is anymore deleted, too</technical_language>

Target:
public ByteBuffer subscriptionUserData(final Set<String> topics) { final TaskManager taskManager = taskManager(); handleRebalanceStart(topics); if (usedSubscriptionMetadataVersion <= LATEST_SUPPORTED_VERSION) { return new SubscriptionInfo( usedSubscriptionMetadataVersion, LATEST_SUPPORTED_VERSION + 1, taskManager.processId(), userEndPoint(), taskManager.getTaskOffsetSums() ).encode(); } else { return new FutureSubscriptionInfo( usedSubscriptionMetadataVersion, taskManager.processId(), SubscriptionInfo.getActiveTasksFromTaskOffsetSumMap(taskManager.getTaskOffsetSums()), SubscriptionInfo.getStandbyTasksFromTaskOffsetSumMap(taskManager.getTaskOffsetSums()), userEndPoint()) .encode(); } }
Source:
<code>public void testStandingOrderGetSuccess() throws Exception { Response<PaymentCreateResponse> createPaymentResponse = PaymentCreateTest.createStandingOrder(client()); String paymentId = createPaymentResponse.body().getPaymentId(); assertNotNull(paymentId); String clientUserId = Long.toString((new Date()).getTime()); LinkTokenCreateRequest.User user = new LinkTokenCreateRequest.User(clientUserId); Response<LinkTokenCreateResponse> response = client().service() .linkTokenCreate(new LinkTokenCreateRequest(user, "client name", <START> Collections.singletonList("payment_initiation"), Collections.singletonList("US"), "en") <END> .withPaymentInitiation(new LinkTokenCreateRequest.PaymentInitiation(paymentId))) .execute(); assertSuccessResponse(response); Response<PaymentGetResponse> getPaymentResponse = client().service().paymentGet(new PaymentGetRequest(paymentId)) .execute(); assertSuccessResponse(getPaymentResponse); assertNotNull(getPaymentResponse.body().getPaymentId()); assertNotNull(getPaymentResponse.body().getReference()); assertNotNull(getPaymentResponse.body().getAmount()); assertNotNull(getPaymentResponse.body().getSchedule()); assertNotNull(getPaymentResponse.body().getStatus()); assertNotNull(getPaymentResponse.body().getLastStatusUpdate()); assertNotNull(getPaymentResponse.body().getRecipientId()); }</code><technical_language>more sense GB instead of payment initiation is more of a GB product</technical_language>

Target:
public void testStandingOrderGetSuccess() throws Exception { Response<PaymentCreateResponse> createPaymentResponse = PaymentCreateTest.createStandingOrder(client()); String paymentId = createPaymentResponse.body().getPaymentId(); assertNotNull(paymentId); String clientUserId = Long.toString((new Date()).getTime()); LinkTokenCreateRequest.User user = new LinkTokenCreateRequest.User(clientUserId); Response<LinkTokenCreateResponse> response = client().service() .linkTokenCreate(new LinkTokenCreateRequest(user, "client name", Collections.singletonList("payment_initiation"), Collections.singletonList("GB"), "en") .withPaymentInitiation(new LinkTokenCreateRequest.PaymentInitiation(paymentId))) .execute(); assertSuccessResponse(response); Response<PaymentGetResponse> getPaymentResponse = client().service().paymentGet(new PaymentGetRequest(paymentId)) .execute(); assertSuccessResponse(getPaymentResponse); assertNotNull(getPaymentResponse.body().getPaymentId()); assertNotNull(getPaymentResponse.body().getReference()); assertNotNull(getPaymentResponse.body().getAmount()); assertNotNull(getPaymentResponse.body().getSchedule()); assertNotNull(getPaymentResponse.body().getStatus()); assertNotNull(getPaymentResponse.body().getLastStatusUpdate()); assertNotNull(getPaymentResponse.body().getRecipientId()); }
Source:
<code>private static ExecutorService createSharedExecutor(MetricsManager metricsManager) { return new InstrumentedExecutorService( PTExecutors.newThreadPoolExecutor( CORE_SHARED_EXECUTOR_THREADS, MAX_SHARED_EXECUTOR_THREADS, 5, TimeUnit.SECONDS, new SynchronousQueue<>(), new InstrumentedThreadFactory(new ThreadFactoryBuilder() .setNameFormat("paxos-timestamp-creator-%d") .setDaemon(true) .build(), metricsManager.getRegistry()), <START> new ThreadPoolExecutor.CallerRunsPolicy()), END> metricsManager.getRegistry(), MetricRegistry.name(PaxosLeaderElectionService.class, "paxos-timestamp-creator", "executor")); }</code><technical_language>idea is expect source of overloading is a bad actors hammering, this effectively throttle them</technical_language>

Target:
private static ExecutorService createSharedExecutor(MetricsManager metricsManager) { return new InstrumentedExecutorService( PTExecutors.newThreadPoolExecutor( CORE_SHARED_EXECUTOR_THREADS, MAX_SHARED_EXECUTOR_THREADS, 5, TimeUnit.SECONDS, new SynchronousQueue<>(), new InstrumentedThreadFactory(new ThreadFactoryBuilder() .setNameFormat("paxos-timestamp-creator-%d") .setDaemon(true) .build(), metricsManager.getRegistry()), RejectionTrackingCallerRunsPolicy.createWithSafeLoggableUseCase( metricsManager, PAXOS_SHARED_EXECUTOR)), metricsManager.getRegistry(), MetricRegistry.name(PaxosLeaderElectionService.class, PAXOS_SHARED_EXECUTOR, "executor")); }
Source:
<code>private void deleteCacheIfPossible(final ConnectionSlot slot) throws IOException { final boolean hasMoreConnectionsToPartition = ACQUIRED_SLOTS.stream() .anyMatch(s -> s.getPartition().equals(slot.getPartition()) && s.getClient().equals(slot.getClient()) && s.getEventType().equals(slot.getEventType())); if (!hasMoreConnectionsToPartition) { <START> final String consumerPath = zkPathForConsumer(slot.getClient(), slot.getEventType(), slot.getPartition()); <END> final PathChildrenCache cache = SLOTS_CACHES.getOrDefault(consumerPath, null); if (cache != null) { SLOTS_CACHES.remove(consumerPath); cache.close(); } } }</code><technical_language>For example thread this if block moment another thread acquire connection for slot. node exists in ZK in ACQUIRED_SLOTS . Do is gonna a problem</technical_language>

Target:
private void deleteCacheIfPossible(final ConnectionSlot slot) throws IOException { final boolean hasMoreConnectionsToPartition = ACQUIRED_SLOTS.stream() .anyMatch(s -> s.getPartition().equals(slot.getPartition()) && s.getClient().equals(slot.getClient()) && s.getEventType().equals(slot.getEventType())); if (!hasMoreConnectionsToPartition) { final String consumerPath = zkPathForConsumer(slot.getClient(), slot.getEventType(), slot.getPartition()); final PathChildrenCache cache = SLOTS_CACHES.remove(consumerPath); if (cache != null) { cache.close(); } } }
Source:
<code>public void run() { OperationStatus priorStatus = null; final AtomicBoolean done = new AtomicBoolean(); while(!done.get()) { final CountDownLatch latch = new CountDownLatch(1); final AtomicReference<OperationStatus> foundStatus = new AtomicReference<OperationStatus>(); final OperationCallback cb=new OperationCallback() { public void receivedStatus(OperationStatus val) { if(val.getMessage().length() == 0) { done.set(true); node.authComplete(); getLogger().info("Authenticated to " + node.getSocketAddress()); } else { foundStatus.set(val); } } public void complete() { latch.countDown(); } }; final Operation op = buildOperation(priorStatus, cb); conn.insertOperation(node, op); try { latch.await(); Thread.sleep(100); } catch(InterruptedException e) { Thread.currentThread().interrupt(); if (op != null) { op.cancel("interrupted in the process of authentication" + e); <START> } <END> done.set(true); } priorStatus = foundStatus.get(); if(priorStatus != null) { if(!priorStatus.isSuccess()) { getLogger().warn("Authentication failed to " + node.getSocketAddress()); } } } return; }</code><technical_language>"interruption authentication"</technical_language>

Target:
public void run() { OperationStatus priorStatus = null; final AtomicBoolean done = new AtomicBoolean(); while(!done.get()) { final CountDownLatch latch = new CountDownLatch(1); final AtomicReference<OperationStatus> foundStatus = new AtomicReference<OperationStatus>(); final OperationCallback cb=new OperationCallback() { public void receivedStatus(OperationStatus val) { if(val.getMessage().length() == 0) { done.set(true); node.authComplete(); getLogger().info("Authenticated to " + node.getSocketAddress()); } else { foundStatus.set(val); } } public void complete() { latch.countDown(); } }; final Operation op = buildOperation(priorStatus, cb); conn.insertOperation(node, op); try { latch.await(); Thread.sleep(100); } catch(InterruptedException e) { Thread.currentThread().interrupt(); if (op != null) { op.cancel("interruption to authentication" + e); } done.set(true); } priorStatus = foundStatus.get(); if(priorStatus != null) { if(!priorStatus.isSuccess()) { getLogger().warn("Authentication failed to " + node.getSocketAddress()); } } } return; }
Source:
<code>private SamplerConfiguration getIteratorSamplerConfigurationInternal() { SamplerConfiguration scannerSamplerConfig = getSamplerConfiguration(); if (scannerSamplerConfig != null) { <START> if (iteratorSamplerConfig != null && !new SamplerConfigurationImpl(iteratorSamplerConfig).equals(new SamplerConfigurationImpl(scannerSamplerConfig))) { <END> throw new IllegalStateException("Scanner and iterator sampler configuration differ"); } return scannerSamplerConfig; } return iteratorSamplerConfig; }</code><technical_language>instantiation of objects in equals method broken out of if condition? a lot for a simple equality check easier follow if impls instantiated earlier IMO</technical_language>

Target:
private SamplerConfiguration getIteratorSamplerConfigurationInternal() { SamplerConfiguration scannerSamplerConfig = getSamplerConfiguration(); if (scannerSamplerConfig != null) { if (iteratorSamplerConfig != null && !iteratorSamplerConfig.equals(scannerSamplerConfig)) { throw new IllegalStateException("Scanner and iterator sampler configuration differ"); } return scannerSamplerConfig; } return iteratorSamplerConfig; }
Source:
<code>private Response logAndReplaceResponse(String url, Response response, Type type, long elapsedTime) throws IOException, ConversionException { log.log(String.format("<--- HTTP %s %s (%sms)", response.getStatus(), url, elapsedTime)); if (logLevel.ordinal() >= LogLevel.HEADERS.ordinal()) { for (Header header : response.getHeaders()) { log.log(header.toString()); } TypedInput body = response.getBody(); if (body != null) { long bodySize = body.length(); if (logLevel.ordinal() >= LogLevel.FULL.ordinal()) { log.log(""); if (!(body instanceof TypedByteArray)) { response = Utils.readBodyToBytesIfNecessary(response); body = response.getBody(); } byte[] bodyBytes = ((TypedByteArray) body).getBytes(); bodySize = bodyBytes.length; if (type == Response.class) { <START> log.log("(not enough type information)"); <END> } else if (converter instanceof LoggingConverter) { LoggingConverter loggingConverter = (LoggingConverter) converter; log.log(loggingConverter.bodyToString(body, type)); } else { log.log("(converter unable to log)"); } } log.log(String.format("<--- END HTTP (%s-byte body)", bodySize)); } else { log.log("<--- END HTTP (empty body)"); } } return response; }</code><technical_language>sledgehammer fly, content-type contract server, is disabled for prod. Ex. Retrofit-BodyType: com.foo.MyClass</technical_language>

Target:
private Response logAndReplaceResponse(String url, Response response, Type type, long elapsedTime) throws IOException, ConversionException { log.log(String.format("<--- HTTP %s %s (%sms)", response.getStatus(), url, elapsedTime)); if (logLevel.ordinal() >= LogLevel.HEADERS.ordinal()) { for (Header header : response.getHeaders()) { log.log(header.toString()); } TypedInput body = response.getBody(); if (body != null) { long bodySize = body.length(); if (logLevel.ordinal() >= LogLevel.FULL.ordinal()) { log.log(""); if (type == Response.class) { log.log("(not enough type information)"); } else if (converter instanceof LoggingConverter) { if (!(body instanceof TypedByteArray)) { response = Utils.readBodyToBytesIfNecessary(response); body = response.getBody(); } byte[] bodyBytes = ((TypedByteArray) body).getBytes(); bodySize = bodyBytes.length; LoggingConverter loggingConverter = (LoggingConverter) converter; log.log(loggingConverter.bodyToLogString(body, type)); } else { log.log("(converter unable to log)"); } } log.log(String.format("<--- END HTTP (%s-byte body)", bodySize)); } else { log.log("<--- END HTTP (empty body)"); } } return response; }
Source:
<code>void initializeLocalUntainted(@Untainted Buffer b) { Buffer local = b; <START> @Untainted Buffer copy = local; <END> }</code><technical_language>More generally, a test expected error good, show expected type is inferred</technical_language>

Target:
void initializeLocalUntainted(@Untainted Buffer b) { Buffer local = b; @Untainted Buffer copy1 = local; @Tainted Buffer copy2 = local; }
Source:
<code>private void updateBackup() { if (getCurrentStorageItem().getRole() == StorageDomainType.ISO || getCurrentStorageItem().getRole() == StorageDomainType.ImportExport) { <START> getBackup().setIsAvailable(false); <END> getBackup().setEntity(false); return; } boolean backupSupported = (Boolean) AsyncDataProvider.getInstance().getConfigValuePreConverted( ConfigValues.BackupSupported, getDataCenter().getSelectedItem().getCompatibilityVersion().toString()); getBackup().setIsAvailable(backupSupported); if (getBackup().getIsAvailable()) { if (isNewStorage()) { getBackup().setEntity(false); } else { getBackup().setEntity(getStorage().isBackup()); } } }</code><technical_language>formatter</technical_language>

Target:
private void updateBackup() { if (getCurrentStorageItem().getRole() == StorageDomainType.ISO || getCurrentStorageItem().getRole() == StorageDomainType.ImportExport) { getBackup().setIsAvailable(false); getBackup().setEntity(false); return; } boolean backupSupported = (Boolean) AsyncDataProvider.getInstance().getConfigValuePreConverted( ConfigurationValues.BackupSupported, getDataCenter().getSelectedItem().getCompatibilityVersion().toString()); getBackup().setIsAvailable(backupSupported); getBackup().setEntity(isNewStorage() ? false : getStorage().isBackup()); }
Source:
<code>private boolean tryLock() throws SQLException { List<Boolean> results = jdbcTemplate.query( "SELECT pg_try_advisory_lock(" + lockNum + ")", new RowMapper<Boolean>() { @Override public Boolean mapRow(ResultSet rs) throws SQLException { <START> return rs.getBoolean(0); <END> } }); return results.size() == 1 && results.get(0); }</code><technical_language>Column indexes 1-based - this is a definite improvement</technical_language>

Target:
private boolean tryLock() throws SQLException { List<Boolean> results = jdbcTemplate.query( "SELECT pg_try_advisory_lock(" + lockNum + ")", new RowMapper<Boolean>() { @Override public Boolean mapRow(ResultSet rs) throws SQLException { return rs.getBoolean(1); } }); return results.size() == 1 && results.get(0); }
Source:
<code>public boolean equals(Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (!(obj instanceof CtfIterator)) { return false; } CtfIterator other = (CtfIterator) obj; if (!NonNullUtils.equalsNullable(fTrace, other.fTrace)) { return false; } if (!NonNullUtils.equalsNullable(fCurLocation, other.fCurLocation)) { return false; } <START> return fCurRank == other.fCurRank; <END> }</code><technical_language>check</technical_language>

Target:
public boolean equals(Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (!(obj instanceof CtfIterator)) { return false; } CtfIterator other = (CtfIterator) obj; if (!equalsNullable(fTrace, other.fTrace)) { return false; } if (!equalsNullable(fCurLocation, other.fCurLocation)) { return false; } if (fCurRank != other.fCurRank) { return false; } return true; }
Source:
<code>void rollback() { if (publishedFullRegistry == null) { return; } try { writeLock.lock(); clear(); <START> copy(publishedFullRegistry, this); <END> modified = false; } finally { writeLock.unlock(); } }</code><technical_language>Here, publishedFullRegistry.readLock needs taken</technical_language>

Target:
void rollback() { if (publishedFullRegistry == null) { return; } writeLock.lock(); try { publishedFullRegistry.readLock.lock(); try { clear(); copy(publishedFullRegistry, this); modified = false; } finally { publishedFullRegistry.readLock.unlock(); } } finally { writeLock.unlock(); } }
Source:
<code>protected void parseService(FBType type) throws TypeImportException, XMLStreamException { String rightInterface = getAttributeValue(LibraryElementTags.RIGHT_INTERFACE_ATTRIBUTE); if (null != rightInterface) { ServiceInterface rightInter = LibraryElementFactory.eINSTANCE.createServiceInterface(); rightInter.setName(rightInterface); type.getService().setRightInterface(rightInter); } else { throw new TypeImportException(Messages.FBTImporter_SERVICE_INTERFACE_RIGHTINTERFACE_EXCEPTION); } String leftInterface = getAttributeValue(LibraryElementTags.LEFT_INTERFACE_ATTRIBUTE); if (null != leftInterface) { ServiceInterface leftInter = LibraryElementFactory.eINSTANCE.createServiceInterface(); leftInter.setName(leftInterface); type.getService().setLeftInterface(leftInter); } else { throw new TypeImportException(Messages.FBTImporter_SERVICE_INTERFACE_LEFTINTERFACE_EXCEPTION); } String comment = getAttributeValue(LibraryElementTags.COMMENT_ATTRIBUTE); if (null != comment) { type.setComment(comment); } <START> processChildren(LibraryElementTags.SERVICE_ELEMENT, name -> { if (name.equals(LibraryElementTags.SERVICE_SEQUENCE_ELEMENT)) { <END> parseServiceSequence(type); return true; } return false; }); }</code><technical_language>call equals constant</technical_language>

Target:
protected void parseService(FBType type) throws TypeImportException, XMLStreamException { String rightInterface = getAttributeValue(LibraryElementTags.RIGHT_INTERFACE_ATTRIBUTE); if (null != rightInterface) { ServiceInterface rightInter = LibraryElementFactory.eINSTANCE.createServiceInterface(); rightInter.setName(rightInterface); type.getService().setRightInterface(rightInter); } else { throw new TypeImportException(Messages.FBTImporter_SERVICE_INTERFACE_RIGHTINTERFACE_EXCEPTION); } String leftInterface = getAttributeValue(LibraryElementTags.LEFT_INTERFACE_ATTRIBUTE); if (null != leftInterface) { ServiceInterface leftInter = LibraryElementFactory.eINSTANCE.createServiceInterface(); leftInter.setName(leftInterface); type.getService().setLeftInterface(leftInter); } else { throw new TypeImportException(Messages.FBTImporter_SERVICE_INTERFACE_LEFTINTERFACE_EXCEPTION); } String comment = getAttributeValue(LibraryElementTags.COMMENT_ATTRIBUTE); if (null != comment) { type.setComment(comment); } processChildren(LibraryElementTags.SERVICE_ELEMENT, name -> { if (LibraryElementTags.SERVICE_SEQUENCE_ELEMENT.equals(name)) { parseServiceSequence(type); return true; } return false; }); }
Source:
<code>public void testCanAssign() throws Exception { VariableDeclarationFragment[] targets= createVariables(); StringBuilder errors= new StringBuilder(); for (VariableDeclarationFragment targetk : targets) { for (VariableDeclarationFragment targetn : targets) { <START> VariableDeclarationFragment f1= targetk; VariableDeclarationFragment f2= targetn; <END> String line= f2.getName().getIdentifier() + "= " + f1.getName().getIdentifier(); StringBuilder buf= new StringBuilder(); buf.append("package test1;\n"); buf.append("public class F<T, U extends Number> extends E<T, U> {\n"); buf.append(" void foo() {\n"); buf.append(" ").append(line).append(";\n"); buf.append(" }\n"); buf.append("}\n"); char[] content= buf.toString().toCharArray(); ASTParser parser= ASTParser.newParser(IASTSharedValues.SHARED_AST_LEVEL); parser.setSource(content); parser.setResolveBindings(true); parser.setProject(fJProject1); parser.setUnitName("F.java"); CompilationUnit astRoot= (CompilationUnit) parser.createAST(null); IProblem[] problems= astRoot.getProblems(); ITypeBinding b1= f1.resolveBinding().getType(); assertNotNull(b1); ITypeBinding b2= f2.resolveBinding().getType(); assertNotNull(b2); boolean res2= TypeRules.canAssign(b1, b2); if (res2 != (problems.length == 0)) { errors.append(line).append('\n'); } } } assertTrue(errors.toString(), errors.length() == 0); }</code><technical_language>loop var other occurances</technical_language>

Target:
public void testCanAssign() throws Exception { VariableDeclarationFragment[] targets= createVariables(); StringBuilder errors= new StringBuilder(); for (VariableDeclarationFragment f1 : targets) { for (VariableDeclarationFragment f2 : targets) { String line= f2.getName().getIdentifier() + "= " + f1.getName().getIdentifier(); StringBuilder buf= new StringBuilder(); buf.append("package test1;\n"); buf.append("public class F<T, U extends Number> extends E<T, U> {\n"); buf.append(" void foo() {\n"); buf.append(" ").append(line).append(";\n"); buf.append(" }\n"); buf.append("}\n"); char[] content= buf.toString().toCharArray(); ASTParser parser= ASTParser.newParser(IASTSharedValues.SHARED_AST_LEVEL); parser.setSource(content); parser.setResolveBindings(true); parser.setProject(fJProject1); parser.setUnitName("F.java"); CompilationUnit astRoot= (CompilationUnit) parser.createAST(null); IProblem[] problems= astRoot.getProblems(); ITypeBinding b1= f1.resolveBinding().getType(); assertNotNull(b1); ITypeBinding b2= f2.resolveBinding().getType(); assertNotNull(b2); boolean res2= TypeRules.canAssign(b1, b2); if (res2 != (problems.length == 0)) { errors.append(line).append('\n'); } } } assertTrue(errors.toString(), errors.length() == 0); }
Source:
<code>private String buildUpdateScript(final String content) { Validate.notNull(content); final StringWriter raw = new StringWriter(); final PrintWriter script = new PrintWriter(raw); final StringBuilder sb = new StringBuilder(); final StringBuilder cb = new StringBuilder(); sb.append(":syntax => :scss"); for (final String require : requires) { script.println(" require '" + require + "' "); } for (int i = 0; i < content.length(); i++) { <START> cb.append(String.format("\\u%04x", content.codePointAt(i))); <END> } final String scriptAsString = String.format("result = Sass::Engine.new(\"%s\", {%s}).render", cb.toString(), sb.toString()); LOG.debug("scriptAsString: {}", scriptAsString); script.println(scriptAsString); script.flush(); return raw.toString(); }</code><technical_language>Also, a test-case proves problem helpful</technical_language>

Target:
private String buildUpdateScript(final String content) { Validate.notNull(content); final StringWriter raw = new StringWriter(); final PrintWriter script = new PrintWriter(raw); final StringBuilder sb = new StringBuilder(); final StringBuilder cb = new StringBuilder(); sb.append(":syntax => :scss"); for (final String require : requires) { script.println(" require '" + require + "' "); } final int BACKSLASH = 0x5c; for (int i = 0; i < content.length(); i++) { final int code = content.codePointAt(i); if (code < 0x80) { if (code == BACKSLASH) { cb.append("\\"); } cb.append(content.charAt(i)); } else { cb.append(String.format("\\u%04x", code)); } } final String scriptAsString = String.format("result = Sass::Engine.new(\"%s\", {%s}).render", cb.toString().replace("\"", "\\\"").replace("#", "\\#"), sb.toString()); LOG.debug("scriptAsString: {}", scriptAsString); script.println(scriptAsString); script.flush(); return raw.toString(); }
Source:
<code>public RuntimeInfo getRuntimeInfo(ExecutionEngine engine, ComponentProperties properties, ConnectorTopology connectorTopology) { <START> assertEngineCompatibility(engine); <END> assertConnectorTopologyCompatibility(connectorTopology); return getRuntimeInfo(GoogleDriveConnectionDefinition.SOURCE_CLASS); }</code><technical_language>"return this.getRuntimeInfo(engine, connectorTopology, GoogleDriveConnectionDefinition.SOURCE_CLASS)" avoid code redundance. (ok lines...)</technical_language>

Target:
public RuntimeInfo getRuntimeInfo(ExecutionEngine engine, ComponentProperties properties, ConnectorTopology connectorTopology) { return this.getRuntimeInfo(engine, connectorTopology, GoogleDriveConnectionDefinition.SOURCE_CLASS); }
Source:
<code><START> public SeekableStreamDataSourceMetadata getCurrentCheckPoint() <END> { return checkpointMetadata; }</code><technical_language>this is for Jackson, private get rid of @Deprecated if want</technical_language>

Target:
private SeekableStreamDataSourceMetadata getCurrentCheckPoint() { return checkpointMetadata; }
Source:
<code>MockStore( Cursors cursors ) { <START> super( cursors, null ); END> }</code><technical_language>Forgotten left intentionally</technical_language>

Target:
MockStore( Cursors cursors ) { super( cursors, mock( TxStateHolder.class ) ); }
Source:
<code>public CompletableFuture<Void> close() { CompletableFuture<Void> future = new CompletableFuture<>(); threadContext.execute(() -> { clusterMembershipService.removeListener(membershipEventListener); primaryElection.removeListener(primaryElectionListener); role.close(); <START> future.complete(null); <END> }); return future; }</code><technical_language>I consider wrapping completing future in a finally block ensure set, imagine close of role is refactored throws exception.</technical_language>

Target:
public CompletableFuture<Void> close() { CompletableFuture<Void> future = new CompletableFuture<>(); threadContext.execute(() -> { try { clusterMembershipService.removeListener(membershipEventListener); primaryElection.removeListener(primaryElectionListener); role.close(); } finally { future.complete(null); } }); return future; }
Source:
<code>public Invocations getInvocations() { return new Invocations.Builder() .invocation().methods(GET).path("/v2/protobuf").handleWith(this::getSchemasNames) <START> .invocation().methods(PUT, POST).path("/v2/protobuf/{schemaName}").handleWith(this::addOrEditSchema) <END> .invocation().methods(GET).path("/v2/protobuf/{schemaName}").handleWith(this::getSchema) .invocation().method(DELETE).path("/v2/protobuf/{schemaName}").handleWith(this::deleteSchema) .create(); }</code><technical_language>PUT POST behaviours: POST return CONFLICT if entity name exists, while PUT replace entity. a CacheResource handles methods: <LINK_0> discern verbs, support PUT</technical_language>

Target:
public Invocations getInvocations() { return new Invocations.Builder() .invocation().methods(GET).path("/v2/schemas").handleWith(this::getSchemasNames) .invocation().methods(POST).path("/v2/schemas/{schemaName}").handleWith(r -> createOrReplace(r,true)) .invocation().methods(PUT).path("/v2/schemas/{schemaName}").handleWith(r -> createOrReplace(r,false)) .invocation().methods(GET).path("/v2/schemas/{schemaName}").handleWith(this::getSchema) .invocation().method(DELETE).path("/v2/schemas/{schemaName}").handleWith(this::deleteSchema) .create(); }
Source:
<code>public BluetoothGattService buildBatteryService() { BluetoothGattCharacteristic batteryCharacteristic = <START> new BluetoothGattCharacteristic(BATTERY_LEVEL_UUID, BATTERY_LEVEL_PROPERTIES, <END> BATTERY_LEVEL_PERMISSIONS); batteryCharacteristic.setValue(BATTERY_LEVEL_SAMPLE); BluetoothGattService batteryService = new BluetoothGattService(BATTERY_SERVICE_UUID, BATTERY_SERVICE_TYPE); batteryService.addCharacteristic(batteryCharacteristic); return batteryService; }</code><technical_language>I PROPERTIES written out defined constants top of class. UUIDs sense constants top of class standardized unreadable values</technical_language>

Target:
public BluetoothGattService buildBatteryService() { BluetoothGattCharacteristic batteryCharacteristic = new BluetoothGattCharacteristic(BATTERY_LEVEL_UUID, BluetoothGattCharacteristic.PROPERTY_READ | BluetoothGattCharacteristic.PROPERTY_NOTIFY, BluetoothGattCharacteristic.PERMISSION_READ); batteryCharacteristic.setValue( 50, BluetoothGattCharacteristic.FORMAT_UINT8, 0); BluetoothGattService batteryService = new BluetoothGattService(BATTERY_SERVICE_UUID, BluetoothGattService.SERVICE_TYPE_PRIMARY); batteryService.addCharacteristic(batteryCharacteristic); return batteryService; }
Source:
<code>public void apply(DebugConfiguration debugConfiguration) { if (debuggerManager.getActiveDebugger() != null) { dialogFactory.createMessageDialog(localizationConstants.connectToRemote(), localizationConstants.debuggerAlreadyConnected(), null).show(); return; } <START> final Debugger debugger = debuggerManager.getDebugger(debugConfiguration.getType().getId()); <END> if (debugger != null) { debuggerManager.setActiveDebugger(debugger); Map<String, String> connectionProperties = new HashMap<>(2 + debugConfiguration.getConnectionProperties().size()); connectionProperties.put("HOST", debugConfiguration.getHost()); connectionProperties.put("PORT", String.valueOf(debugConfiguration.getPort())); connectionProperties.putAll(debugConfiguration.getConnectionProperties()); debugger.connect(connectionProperties).catchError(new Operation<PromiseError>() { @Override public void apply(PromiseError arg) throws OperationException { debuggerManager.setActiveDebugger(null); } }); } }</code><technical_language>Add checking for null here. pass null debugConfiguration</technical_language>

Target:
public void apply(DebugConfiguration debugConfiguration) { if (debugConfiguration == null) { return; } if (debuggerManager.getActiveDebugger() != null) { dialogFactory.createMessageDialog(localizationConstants.connectToRemote(), localizationConstants.debuggerAlreadyConnected(), null).show(); return; } final Debugger debugger = debuggerManager.getDebugger(debugConfiguration.getType().getId()); if (debugger != null) { debuggerManager.setActiveDebugger(debugger); Map<String, String> connectionProperties = new HashMap<>(2 + debugConfiguration.getConnectionProperties().size()); connectionProperties.put("HOST", debugConfiguration.getHost()); connectionProperties.put("PORT", String.valueOf(debugConfiguration.getPort())); connectionProperties.putAll(debugConfiguration.getConnectionProperties()); debugger.connect(connectionProperties).catchError(new Operation<PromiseError>() { @Override public void apply(PromiseError arg) throws OperationException { debuggerManager.setActiveDebugger(null); } }); } }
Source:
<code>public ClientHttpResponse execute() throws IOException { if (this.response == null) { <START> LOGGER.warn("Attempting to load cached URI before actual caching: " + this.originalRequest.getURI()); <END> } else { LOGGER.debug("Loading cached URI resource " + this.originalRequest.getURI()); } return this.response; }</code><technical_language>If request failed, is this.reponse null? Is warning appropriate</technical_language>

Target:
public ClientHttpResponse execute() throws IOException { if (!HttpRequestCache.this.cached) { LOGGER.warn("Attempting to load cached URI before actual caching: " + this.originalRequest.getURI()); } else if (this.response == null) { LOGGER.warn("Attempting to load cached URI from failed request: " + this.originalRequest.getURI()); } else { LOGGER.debug("Loading cached URI resource " + this.originalRequest.getURI()); } return this.response; }
Source:
<code>public boolean requiresTransaction() { <START> return tokens.stream().filter(t -> t.requiresTransaction()).findAny().isPresent(); <END> }</code><technical_language>pre-compute this instead? tokens immutable set in constructor</technical_language>

Target:
public boolean requiresTransaction() { return requiresTransaction; }
Source:
<code>public void fallBackToUnsupported() { BlockStrategies strategies = new BlockStrategies(Sets.newHashSet(BlockType.PARAGRAPH)); List<BlockType> unsupportedBlockTypes = ImmutableList.of(BlockType.TABLE, BlockType.TABLE_ROW, BlockType.BULLETED_LIST, BlockType.NUMERIC_LIST, BlockType.DEFINITION_LIST); for (BlockType blockType : unsupportedBlockTypes) { BlockStrategy strategy = strategies.getStrategy(blockType, new Attributes()); assertNotNull(strategy); <START> assertTrue(UnsupportedBlockStrategy.class.equals(strategy.getClass()) || NoOpBlockStrategy.class.equals(strategy.getClass())); <END> } }</code><technical_language>prefer more specific assertions for block types. Consider separate tests, for unsupported block types result in UnsupportedBlockStrategy, for block types result in NoOpBlockStrategy</technical_language>

Target:
public void fallBackToUnsupported() { BlockStrategies strategies = new BlockStrategies(Sets.newHashSet(BlockType.PARAGRAPH)); BlockStrategy strategy = strategies.getStrategy(BlockType.TABLE_ROW, new Attributes()); assertNotNull(strategy); assertTrue(UnsupportedBlockStrategy.class.equals(strategy.getClass())); }
Source:
<code>public void registerPublisher(Function<NodeEngine, MetricsPublisher> registerFunction) { <START> MetricsPublisher publisher = registerFunction.apply(nodeEngine); <END> publishers.add(publisher); }</code><technical_language>this function called if metrics enabled</technical_language>

Target:
public void registerPublisher(Function<NodeEngine, MetricsPublisher> registerFunction) { if (config.isEnabled()) { MetricsPublisher publisher = registerFunction.apply(nodeEngine); publishers.add(publisher); scheduleMetricsCollectorIfNeeded(); } else { logger.fine(String.format("Custom publisher is not registered with function %s as the metrics system is disabled", registerFunction)); } }