auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private Object exec(Object message) { if (message instanceof List) { return ((List) message).parallelStream().map(this::exec).collect(Collectors.toList()); } if (!(message instanceof Map)) { return invalid(); } Map msg = (Map) message; if (!msg.containsKey("id")) { return fail(null, invalid("Required key `id` missing")); } Object id = msg.get("id"); if (!(id instanceof String || id instanceof Number || id == null)) { return fail(null, invalid("Key `id` not string or number or null")); } if (!msg.containsKey("jsonrpc")) { return fail(id, invalid("Required key `jsonrpc` missing")); } if (!VERSION.equals(msg.get("jsonrpc"))) { return fail(id, invalid("Key `jsonrpc` not equal to `2.0`")); } if (!msg.containsKey("method")) { return fail(id, invalid("Required key `method` missing")); } if (!(msg.get("method") instanceof String)) { return fail(id, invalid("Key `method` not string")); } if (!methods.containsKey(msg.get("method"))) { return fail("id", METHOD_NOT_FOUND); } Object params = msg.get("params"); if (params != null && !(params instanceof List || params instanceof Map)) { return fail(id, invalidParams("Parameters must be a structured value")); } try { return success(id, methods.get(msg.get("method")).apply(params)); } catch (IllegalArgumentException ex) { return fail(id, invalidParams(ex.getMessage())); } catch (Exception ex) { return fail(id, INTERNAL_ERROR); } }

Target:
private Object exec(Object message) { if (!(message instanceof Map)) { return response(null, invalid("message must be a map", message)); } Map msg = (Map) message; if (!msg.containsKey("id")) { return response(null, invalid("required key `id` missing")); } Object id = msg.get("id"); if (!(id instanceof String || id instanceof Number || id == null)) { return response(null, invalid("key `id` not string or number or null", id)); } if (!msg.containsKey(JSONRPC)) { return response(id, invalid("required key `jsonrpc` missing")); } if (!VERSION.equals(msg.get(JSONRPC))) { return response(id, invalid("key `jsonrpc` not equal to `2.0`", msg.get(JSONRPC))); } if (!msg.containsKey(METHOD)) { return response(id, invalid("required key `method` missing")); } if (!(msg.get(METHOD) instanceof String)) { return response(id, invalid("key `method` not string", msg.get(METHOD))); } String method = (String) msg.get(METHOD); if (!methods.containsKey(method)) { return response(id, error(METHOD_NOT_FOUND, String.format("method `%s` not found", method))); } Object params = msg.get("params"); if (params != null && !(params instanceof List || params instanceof Map)) { return response(id, invalidParams("parameters must be a structured value", params)); } try { return response(id, methods.get(method).apply(params)); } catch (RuntimeException e) { return response(id, JsonRpc.error(INTERNAL_ERROR, "Internal Error")); } }
Source:
protected void UpdateDetailsAvailability() { super.UpdateDetailsAvailability(); VDSGroup vdsGroup = (VDSGroup) getSelectedItem(); getClusterServiceModel().setIsAvailable(vdsGroup != null && vdsGroup.supportsGlusterService() && vdsGroup.getcompatibility_version() != null && Version.v3_2.compareTo(vdsGroup.getcompatibility_version()) <= 0); }

Target:
protected void UpdateDetailsAvailability() { super.UpdateDetailsAvailability(); VDSGroup vdsGroup = (VDSGroup) getSelectedItem(); getClusterServiceModel().setIsAvailable(vdsGroup != null && vdsGroup.supportsGlusterService() && Version.v3_2.compareTo(vdsGroup.getcompatibility_version()) <= 0); }
Source:
private void reloadJenkinsConfigurationViaCliAndWait() throws Exception { final CLICommandInvoker.Result result = command .authorizedTo(Jenkins.READ, Jenkins.ADMINISTER).invoke(); assertThat(result, succeededSilently()); boolean sleep = true; while (sleep) { sleep = false; for (Thread t : Thread.getAllStackTraces().keySet()) { if (t.getName().equals("Jenkins config reload thread")) { System.out.println("Reloading thread is active and performing reload operation, sleeping 1s..."); sleep = true; Thread.sleep(1000); break; } } } }

Target:
private void reloadJenkinsConfigurationViaCliAndWait() throws Exception { final CLICommandInvoker.Result result = command .authorizedTo(Jenkins.READ, Jenkins.ADMINISTER).invoke(); assertThat(result, succeededSilently()); while (!(j.jenkins.servletContext.getAttribute("app") instanceof Jenkins)) { System.out.println("Jenkins reload operation is performing, sleeping 1s..."); Thread.sleep(1000); } }
Source:
public void should_not_return_tags_of_foreign_organization() throws IOException { OrganizationDto organization_with_specific_tags = dbTester.organizations().insert(); OrganizationDto myOrganization = dbTester.organizations().insert(); RuleDefinitionDto rule = dbTester.rules().insert(setSystemTags("system1", "system2")); insertMetadata(organization_with_specific_tags, rule, setTags("tag1", "tag2")); indexRules(); SearchResponse result = ws.newRequest() .setParam("facets", "tags") .setParam("f", "tags") .setParam("organization", myOrganization.getKey()) .executeProtobuf(SearchResponse.class); assertThat(result.getRulesList()).extracting(Rule::getKey).containsExactly(rule.getKey().toString()); assertThat(result.getFacets().getFacets(0).getValuesList()) .extracting(v -> tuple(v.getVal(), v.getCount())) .containsExactly( tuple("system1", 1L), tuple("system2", 1L) ); }

Target:
public void should_not_return_tags_of_foreign_organization() throws IOException { OrganizationDto organizationWithSpecificTags = dbTester.organizations().insert(); OrganizationDto myOrganization = dbTester.organizations().insert(); RuleDefinitionDto rule = dbTester.rules().insert(setSystemTags("system1", "system2")); insertMetadata(organizationWithSpecificTags, rule, setTags("tag1", "tag2")); indexRules(); SearchResponse result = ws.newRequest() .setParam("facets", "tags") .setParam("f", "tags") .setParam("organization", myOrganization.getKey()) .executeProtobuf(SearchResponse.class); assertThat(result.getRulesList()).extracting(Rule::getKey).containsExactly(rule.getKey().toString()); assertThat(result.getFacets().getFacets(0).getValuesList()) .extracting(v -> tuple(v.getVal(), v.getCount())) .containsExactly( tuple("system1", 1L), tuple("system2", 1L) ); }
Source:
protected Object doGetValue() { Object value = null; if (source instanceof ShapeImpl) { for (Object child : source.getChildren()) { if (child instanceof DecorationNodeImpl && FLOATING_LABEL.equals(NotationTypesMap.instance.getHumanReadableType((View) child))) { NamedStyle valueStyle = ((View) child).getNamedStyle(styleClass, styleName); if (valueStyle != null) { if (value == null) { value = valueStyle.eGet(styleFeature); } } } } } return value; }

Target:
protected Object doGetValue() { Object value = null; if (source instanceof View) { source.getChildren().iterator(); Iterator<?> iterator = source.getChildren().iterator(); while (iterator.hasNext() && value == null) { Object child = (Object) iterator.next(); if (child instanceof DecorationNodeImpl && FLOATING_LABEL.equals(NotationTypesMap.instance.getHumanReadableType((View) child))) { NamedStyle valueStyle = ((View) child).getNamedStyle(styleClass, styleName); if (valueStyle != null) { if (value == null) { value = valueStyle.eGet(styleFeature); } } } } } return value; }
Source:
public boolean checkUnsortedEncodedKeyComponentsEqual(@Nullable Double lhs, @Nullable Double rhs) { return Objects.equals(lhs, rhs); }

Target:
public boolean checkUnsortedEncodedKeyComponentsEqual(@Nullable Double lhs, @Nullable Double rhs) { return DimensionHandlerUtils.nullToZero(lhs).equals(DimensionHandlerUtils.nullToZero(rhs)); }
Source:
public Map<String, Statistic<?, ?>> collectStatistics(Context context, Collection<String> statisticNames) { Map<String, Statistic<?, ?>> statistics = new TreeMap<>(); AbstractExposedStatistics<T> exposedObject = (AbstractExposedStatistics<T>) findExposedObject(context); if (exposedObject != null) { if (statisticNames == null || statisticNames.isEmpty()) { statistics.putAll(exposedObject.queryStatistics()); } else { for (String statisticName : statisticNames) { try { statistics.put(statisticName, exposedObject.queryStatistic(statisticName)); } catch (IllegalArgumentException ignored) { } } } } return statistics; }

Target:
public Map<String, Statistic<?, ?>> collectStatistics(Context context, Collection<String> statisticNames) { Map<String, Statistic<?, ?>> statistics = new TreeMap<>(); AbstractExposedStatistics<T> exposedObject = (AbstractExposedStatistics<T>) findExposedObject(context); if (exposedObject != null) { if (statisticNames == null || statisticNames.isEmpty()) { statistics.putAll(exposedObject.queryStatistics()); } else { for (String statisticName : statisticNames) { Statistic<?, ?> statistic = exposedObject.queryStatistic(statisticName); if (statistic != null) { statistics.put(statisticName, statistic); } } } } return statistics; }
Source:
static void ensureInitialized() { if (sExecutorService == null) { sExecutorService = Executors.newCachedThreadPool(); } }

Target:
public static void ensureInitialized() { if (sExecutorService == null) { sExecutorService = Executors.newCachedThreadPool(); } }
Source:
LedgerMetadataFormat buildProtoFormat(boolean withPassword) { LedgerMetadataFormat.Builder builder = LedgerMetadataFormat.newBuilder(); builder.setQuorumSize(writeQuorumSize).setAckQuorumSize(ackQuorumSize) .setEnsembleSize(ensembleSize).setLength(length) .setState(state).setLastEntryId(lastEntryId); if (storeSystemtimeAsLedgerCreationTime) { builder.setCtime(ctime); } builder.setDigestType(digestType); if (hasPassword && withPassword) { builder.setPassword(ByteString.copyFrom(password)); } if (customMetadata != null) { LedgerMetadataFormat.cMetadataMapEntry.Builder cMetadataBuilder = LedgerMetadataFormat.cMetadataMapEntry.newBuilder(); for (Map.Entry<String, byte[]> entry : customMetadata.entrySet()) { cMetadataBuilder.setKey(entry.getKey()).setValue(ByteString.copyFrom(entry.getValue())); builder.addCustomMetadata(cMetadataBuilder.build()); } } for (Map.Entry<Long, ArrayList<BookieSocketAddress>> entry : ensembles.entrySet()) { LedgerMetadataFormat.Segment.Builder segmentBuilder = LedgerMetadataFormat.Segment.newBuilder(); segmentBuilder.setFirstEntryId(entry.getKey()); for (BookieSocketAddress addr : entry.getValue()) { segmentBuilder.addEnsembleMember(addr.toString()); } builder.addSegment(segmentBuilder.build()); } return builder.build(); }

Target:
LedgerMetadataFormat buildProtoFormat(boolean withPassword) { LedgerMetadataFormat.Builder builder = LedgerMetadataFormat.newBuilder(); builder.setQuorumSize(writeQuorumSize).setAckQuorumSize(ackQuorumSize) .setEnsembleSize(ensembleSize).setLength(length) .setState(state).setLastEntryId(lastEntryId); if (storeSystemtimeAsLedgerCreationTime) { builder.setCtime(ctime); } if (hasPassword) { builder.setDigestType(digestType); if (withPassword) { builder.setPassword(ByteString.copyFrom(password)); } } if (customMetadata != null) { LedgerMetadataFormat.cMetadataMapEntry.Builder cMetadataBuilder = LedgerMetadataFormat.cMetadataMapEntry.newBuilder(); for (Map.Entry<String, byte[]> entry : customMetadata.entrySet()) { cMetadataBuilder.setKey(entry.getKey()).setValue(ByteString.copyFrom(entry.getValue())); builder.addCustomMetadata(cMetadataBuilder.build()); } } for (Map.Entry<Long, ArrayList<BookieSocketAddress>> entry : ensembles.entrySet()) { LedgerMetadataFormat.Segment.Builder segmentBuilder = LedgerMetadataFormat.Segment.newBuilder(); segmentBuilder.setFirstEntryId(entry.getKey()); for (BookieSocketAddress addr : entry.getValue()) { segmentBuilder.addEnsembleMember(addr.toString()); } builder.addSegment(segmentBuilder.build()); } return builder.build(); }
Source:
private Object getService(String clazz, String filter) { BundleContext bundleContext = getBundleContext(); ServiceReference<?>[] ref; try { ref = bundleContext.getServiceReferences(clazz, filter); if (ref.length > 1) throw new InvalidSyntaxException("Multiple service references found", filter); if (ref.length < 1) throw new InvalidSyntaxException("No service references found", filter); return bundleContext.getService(ref[0]); } catch (InvalidSyntaxException e) { LOGGER.error(String.format("Invalid filter: %s", filter)); } catch (NullPointerException e) { LOGGER.debug( String.format("Service Reference for class %s not found. Returning NULL", clazz)); } return null; }

Target:
private Object getService(String clazz, String filter) { BundleContext bundleContext = getBundleContext(); ServiceReference<?>[] refs; try { refs = bundleContext.getServiceReferences(clazz, filter); if (refs != null) { if (refs.length > 1) { LOGGER.warn( "More than one service references are found with class: {}, and filter: {}\n" + "Ignoring rest of service references except for the first of the below list:", clazz, filter); Arrays.stream(refs).forEachOrdered(ref -> LOGGER.warn(ref.toString())); } return bundleContext.getService(refs[0]); } } catch (InvalidSyntaxException e) { LOGGER.warn("Invalid filter: {}", filter); } return null; }
Source:
@Override public void bundleChanged( BundleEvent event ) { switch ( event.getType() ) { case BundleEvent.UNINSTALLED: case BundleEvent.INSTALLED: if ( event.getBundle().getSymbolicName().startsWith( COMMON_UI_BUNDLE ) ) { String bundleStr = event.getBundle().getHeaders().get( "Bundle-Name" ) + event.getBundle().getHeaders().get( "Bundle-Version" ); log.info( "Received Bundle event : {}", bundleStr + ( ( event.getType() == BundleEvent.INSTALLED ) ? "Installed" : "Uninstalled" ) ); bundleStateManager.setState( bundleStr, event.getBundle().getState() ); } break; } }

Target:
@Override public void bundleChanged( BundleEvent event ) { switch ( event.getType() ) { case BundleEvent.UNINSTALLED: case BundleEvent.INSTALLED: if ( event.getBundle().getHeaders().get( "Bundle-PlatformPluginName" ) != null ) { String bundleStr = event.getBundle().getHeaders().get( "Bundle-Name" ) + event.getBundle().getHeaders().get( "Bundle-Version" ); log.info( "Received Bundle event : {}", bundleStr + ( ( event.getType() == BundleEvent.INSTALLED ) ? "Installed" : "Uninstalled" ) ); bundleStateManager.setState( bundleStr, event.getType() ); } break; } }
Source:
public int compareTo(SimpleScore other) { if (initScore != other.getInitScore()) { return initScore < other.getInitScore() ? -1 : 1; } else { return Integer.compare(score, other.getScore()); } }

Target:
public int compareTo(SimpleScore other) { if (initScore != other.getInitScore()) { return Integer.compare(initScore, other.getInitScore()); } else { return Integer.compare(score, other.getScore()); } }
Source:
public void setText(String val) { String prevText = getText(); boolean callEvent = !prevText.equals(val); text.set(val != null ? val : ""); linesOfText = null; correctCursor(); if (callEvent) { for (TextChangeEventListener listener : textChangeListeners) { listener.onTextChange(prevText, val); } } }

Target:
public void setText(String val) { String prevText = getText(); boolean callEvent = !prevText.equals(val); text.set(val != null ? val : ""); linesOfText = new String[]{}; correctCursor(); if (callEvent) { for (TextChangeEventListener listener : textChangeListeners) { listener.onTextChange(prevText, val); } } }
Source:
public void testConvertToDataModelTypeWithoutFiles() { uk.ac.ebi.eva.commons.models.converters.data.DBObjectToVariantConverter converter = new uk.ac.ebi.eva.commons.models.converters.data.DBObjectToVariantConverter(); Variant converted = converter.convert(mongoVariant); assertEquals(variant, converted); }

Target:
public void testConvertToDataModelTypeWithoutFiles() { DBObjectToVariantConverter converter = new DBObjectToVariantConverter(); Variant converted = converter.convert(mongoVariant); assertEquals(variant, converted); }
Source:
public static void setForceLogs(String userId, boolean forceLogs) { PreferenceManager.getDefaultSharedPreferences(CommCareApplication.instance()) .edit() .putBoolean(userId + "_" + FORCE_LOGS, forceLogs) .apply(); }

Target:
public static void setForceLogs(String userId, boolean forceLogs) { PreferenceManager.getDefaultSharedPreferences(CommCareApplication.instance()) .edit() .putBoolean(getUserSpecificKey(userId, FORCE_LOGS), forceLogs) .apply(); }
Source:
public void createSnapshotTest_invalidIndex(){ String indexName = "live_xxxxxxxxx"; File snapshot = null; try { snapshot = esIndexAPI.createSnapshot(ESIndexAPI.BACKUP_REPOSITORY, "backup", indexName); assertNull(snapshot); } catch (DotStateException | IllegalArgumentException | IOException e) { e.printStackTrace(); } }

Target:
public void createSnapshotTest_invalidIndex() throws IOException{ String indexName = "live_xxxxxxxxx"; esIndexAPI.createSnapshot(ESIndexAPI.BACKUP_REPOSITORY, "backup", indexName); }
Source:
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView model = new ModelAndView(); PageDTO page = (PageDTO) request.getAttribute(PageHandlerMapping.PAGE_ATTRIBUTE_NAME); assert page != null; model.addObject(MODEL_ATTRIBUTE_NAME, page); model.addObject("pageFields", page.getPageFields()); model.addObject("BLC_PAGE_TYPE", "page"); String plainTextStr = (String) page.getPageFields().get("plainText"); if (!StringUtils.isEmpty(plainTextStr)) { if (Boolean.valueOf(plainTextStr)) { response.setCharacterEncoding("UTF-8"); response.setContentType("text/plain"); } } String templatePath = page.getTemplatePath(); ExtensionResultHolder<String> erh = new ExtensionResultHolder<String>(); Boolean internalValidateFindPreviouslySet = false; ExtensionResultStatusType extResult; try { if (!BroadleafRequestContext.getBroadleafRequestContext().getInternalValidateFind()) { BroadleafRequestContext.getBroadleafRequestContext().setInternalValidateFind(true); internalValidateFindPreviouslySet = true; } extResult = templateOverrideManager.getProxy().getOverrideTemplate(erh, page); } finally { if (internalValidateFindPreviouslySet) { BroadleafRequestContext.getBroadleafRequestContext().setInternalValidateFind(true); } } if (extResult != ExtensionResultStatusType.NOT_HANDLED) { templatePath = erh.getResult(); } model.setViewName(templatePath); addDeepLink(model, deepLinkService, page); return model; }

Target:
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView model = new ModelAndView(); PageDTO page = (PageDTO) request.getAttribute(PageHandlerMapping.PAGE_ATTRIBUTE_NAME); assert page != null; model.addObject(MODEL_ATTRIBUTE_NAME, page); model.addObject("pageFields", page.getPageFields()); model.addObject("BLC_PAGE_TYPE", "page"); String plainTextStr = (String) page.getPageFields().get("plainText"); if (!StringUtils.isEmpty(plainTextStr)) { if (Boolean.valueOf(plainTextStr)) { response.setCharacterEncoding("UTF-8"); response.setContentType("text/plain"); } } String templatePath = page.getTemplatePath(); ExtensionResultHolder<String> erh = new ExtensionResultHolder<String>(); Boolean internalValidateFindPreviouslySet = false; ExtensionResultStatusType extResult; try { if (!BroadleafRequestContext.getBroadleafRequestContext().getInternalValidateFind()) { BroadleafRequestContext.getBroadleafRequestContext().setInternalValidateFind(true); internalValidateFindPreviouslySet = true; } extResult = templateOverrideManager.getProxy().getOverrideTemplate(erh, page); } finally { if (internalValidateFindPreviouslySet) { BroadleafRequestContext.getBroadleafRequestContext().setInternalValidateFind(false); } } if (extResult != ExtensionResultStatusType.NOT_HANDLED) { templatePath = erh.getResult(); } model.setViewName(templatePath); addDeepLink(model, deepLinkService, page); return model; }
Source:
public String getErrorMessage() { String message = null; switch(resolvedError) { case AmbryUnavailable: message += "Insufficient DataNodes replied to complete operation " + context + ":" + operationPolicy; break; case BlobDoesNotExist: message += "BlobDoesNotExist to perform the operation " + context + ":" + operationPolicy; break; case BlobDeleted: message += "Cannot perform the operation " + context + ":" + operationPolicy +" as Blob is deleted "; break; case BlobExpired: message += "Cannot perform the operation " + context + ":" + operationPolicy +" as Blob expired "; break; default: message += "Experienced an unexpected internal error for operation " + context + ":" + operationPolicy; } return message; }

Target:
public String getErrorMessage() { String message = null; switch(resolvedError) { case AmbryUnavailable: message += "Insufficient DataNodes replied to complete operation " + context + ":" + operationPolicy + "resulting in AmbryUnavailable"; break; case BlobDoesNotExist: message += "BlobDoesNotExist to perform the operation " + context + ":" + operationPolicy; break; case BlobDeleted: message += "Cannot perform the operation " + context + ":" + operationPolicy +" as Blob is deleted "; break; case BlobExpired: message += "Cannot perform the operation " + context + ":" + operationPolicy +" as Blob expired "; break; default: message += "Experienced an unexpected internal "+ resolvedError +" error for operation " + context + ":" + operationPolicy; } return message; }
Source:
protected void retrieve(@CheckForNull SCMSourceCriteria criteria, @NonNull SCMHeadObserver observer, @CheckForNull SCMHeadEvent<?> event, @NonNull TaskListener listener) throws IOException, InterruptedException { try { List<P4Head> heads = getHeads(listener); for (P4Head head : heads) { if (criteria == null) { SCMRevision revision = getRevision(head, listener); observer.observe(head, revision); } else { String base = head.getPath(); ClientHelper p4 = new ClientHelper(credential, listener, hack, charset); SCMSourceCriteria.Probe probe = new P4Probe(p4, base); if (criteria.isHead(probe, listener)) { SCMRevision revision = getRevision(head, listener); observer.observe(head, revision); } } } } catch (Exception e) { String err = "P4: Unable add streams to observer."; logger.severe(err); listener.error(err); throw new InterruptedException(e.getMessage()); } }

Target:
protected void retrieve(@CheckForNull SCMSourceCriteria criteria, @NonNull SCMHeadObserver observer, @CheckForNull SCMHeadEvent<?> event, @NonNull TaskListener listener) throws IOException, InterruptedException { try { List<P4Head> heads = getHeads(listener); for (P4Head head : heads) { if (criteria == null) { SCMRevision revision = getRevision(head, listener); observer.observe(head, revision); } else { String base = head.getPath(); SCMSourceCriteria.Probe probe = new P4Probe(credential, listener, charset, base); if (criteria.isHead(probe, listener)) { SCMRevision revision = getRevision(head, listener); observer.observe(head, revision); } } checkInterrupt(); } } catch (Exception e) { throw new IOException(e.getMessage()); } }
Source:
public boolean hitEntity(ItemStack stack, LivingEntity target, LivingEntity player) { target.playSound(sound, 1.0F, 1.0F); return super.hitEntity(stack, target, player); }

Target:
public boolean hitEntity(ItemStack stack, LivingEntity target, LivingEntity player) { target.playSound(sound.get(), volume, pitch); return super.hitEntity(stack, target, player); }
Source:
protected void comparePlans(String sql) { comparePlans(sql, null); }

Target:
protected void comparePlans(String sql) { comparePlans(sql, Collections.emptyMap()); }
Source:
public String getAvatarUrl() { if(chatMember == null) { return null; } if (!(chatMember instanceof ChatRoomMemberJabberImpl)) { return null; } ChatRoomMemberJabberImpl memberJabber = ((ChatRoomMemberJabberImpl) this.chatMember); String url; if((url = (String) memberJabber.getData( ChatRoomMemberPresenceExtensionReader .IDENTITY_AVATAR_URL)) != null) { return url; } else if((url = memberJabber.getAvatarUrl()) != null) { return url; } String email; if((email = getEmail()) != null) { return String.format(GRAVARAR_URL_FORMAT, Util.stringToMD5hash(email)); } String avatarId; if((avatarId = (String) memberJabber.getData( ChatRoomMemberPresenceExtensionReader.AVATAR_ID)) != null) { return String.format(MEEPLE_URL_FORMAT, Util.stringToMD5hash(avatarId)); } return null; }

Target:
public String getAvatarUrl() { if (chatMember == null) { return null; } if (!(chatMember instanceof ChatRoomMemberJabberImpl)) { return null; } ChatRoomMemberJabberImpl memberJabber = ((ChatRoomMemberJabberImpl) this.chatMember); IdentityPacketExtension ipe = getIdentityExtensionOrNull( memberJabber.getLastPresence()); String url; if (ipe != null && (url = ipe.getUserAvatarUrl()) != null) { return url; } else if ((url = memberJabber.getAvatarUrl()) != null) { return url; } String email; if ((email = getEmail()) != null) { return String.format(GRAVARAR_URL_FORMAT, Util.stringToMD5hash(email)); } AvatarIdPacketExtension avatarIdExtension = getAvatarIdExtensionOrNull( memberJabber.getLastPresence()); String avatarId; if (ipe != null && (avatarId = avatarIdExtension.getAvatarId()) != null) { return String.format(MEEPLE_URL_FORMAT, Util.stringToMD5hash(avatarId)); } else { return String.format(MEEPLE_URL_FORMAT, Util.stringToMD5hash(identifier)); } }
Source:
public List<OpenTransaction> startTransactions(List<? extends PreCommitCondition> conditions) { if (conditions.isEmpty()) { return ImmutableList.of(); } List<StartIdentifiedAtlasDbTransactionResponse> responses = timelockService.startIdentifiedAtlasDbTransactionBatch(conditions.size()); Preconditions.checkState(conditions.size() == responses.size(), "Different number of responses and conditions"); try { long immutableTs = Collections.max(responses.stream() .map(response -> response.immutableTimestamp().getImmutableTimestamp()) .collect(Collectors.toList())); recordImmutableTimestamp(immutableTs); cleaner.punch(responses.get(0).startTimestampAndPartition().timestamp()); return Streams.zip( responses.stream(), conditions.stream(), (response, condition) -> { LockToken immutableTsLock = response.immutableTimestamp().getLock(); Supplier<Long> startTimestampSupplier = Suppliers.ofInstance( response.startTimestampAndPartition().timestamp()); Transaction transaction = createTransaction( immutableTs, startTimestampSupplier, immutableTsLock, condition); return new OpenTransactionImpl(transaction, immutableTsLock); }).collect(Collectors.toList()); } catch (Throwable t) { timelockService.tryUnlock( responses.stream() .map(response -> response.immutableTimestamp().getLock()) .collect(Collectors.toSet())); throw Throwables.rewrapAndThrowUncheckedException(t); } }

Target:
public List<OpenTransaction> startTransactions(List<? extends PreCommitCondition> conditions) { if (conditions.isEmpty()) { return ImmutableList.of(); } List<StartIdentifiedAtlasDbTransactionResponse> responses = timelockService.startIdentifiedAtlasDbTransactionBatch(conditions.size()); Preconditions.checkState(conditions.size() == responses.size(), "Different number of responses and conditions"); try { long immutableTs = responses.stream() .mapToLong(response -> response.immutableTimestamp().getImmutableTimestamp()) .max().getAsLong(); recordImmutableTimestamp(immutableTs); cleaner.punch(responses.get(0).startTimestampAndPartition().timestamp()); return Streams.zip( responses.stream(), conditions.stream(), (response, condition) -> { LockToken immutableTsLock = response.immutableTimestamp().getLock(); Supplier<Long> startTimestampSupplier = Suppliers.ofInstance( response.startTimestampAndPartition().timestamp()); Transaction transaction = createTransaction( immutableTs, startTimestampSupplier, immutableTsLock, condition); return new OpenTransactionImpl(transaction, immutableTsLock); }).collect(Collectors.toList()); } catch (Throwable t) { timelockService.tryUnlock( responses.stream() .map(response -> response.immutableTimestamp().getLock()) .collect(Collectors.toSet())); throw Throwables.rewrapAndThrowUncheckedException(t); } }
Source:
public String marshall(Object input, Map<String, Object> parameters) { try { if (parameters.containsKey(MARSHALLER_PARAMETER_STRICT)) { jsonContext.get().setWrap((boolean) parameters.get(MARSHALLER_PARAMETER_STRICT)); } if (NOT_NULL.equals(parameters.get(FIELDS))) { jsonContext.get().setWriteNull(false); } return marshall(input); } finally { jsonContext.get().reset(); } }

Target:
public String marshall(Object input, Map<String, Object> parameters) { try { if (parameters.containsKey(MARSHALLER_PARAMETER_STRICT)) { jsonContext.get().setWrap(Boolean.parseBoolean((String) parameters.get(MARSHALLER_PARAMETER_STRICT))); } if (NOT_NULL.equals(parameters.get(FIELDS))) { jsonContext.get().setWriteNull(false); } return marshall(input); } finally { jsonContext.get().reset(); } }
Source:
public NewsItem getNewsItemById(Long id) { return newsItemRepository.findById(id) .orElseThrow(() -> new RestException("Not found", 404)); }

Target:
public NewsItem getNewsItemById(Long id) { return newsItemRepository.findById(id) .orElseThrow(() -> new RestException("Not found", HttpServletResponse.SC_NOT_FOUND)); }
Source:
private boolean maybeDrainPendingCall(Call call, long now) { try { Node node = call.nodeProvider.provide(); if (node != null) { log.trace("Assigned to node {}", call, node); call.curNode = node; getOrCreateListValue(callsToSend, node).add(call); return true; } else { log.trace("Unable to assign to a node.", call); return false; } } catch (Throwable t) { log.debug("Unable to choose node for {}", call, t); if (t instanceof RetriableException) { call.retry(call, t); } else { call.fail(now, t); } return true; } }

Target:
private boolean maybeDrainPendingCall(Call call, long now) { try { Node node = call.nodeProvider.provide(); if (node != null) { log.trace("Assigned to node {}", call, node); call.curNode = node; getOrCreateListValue(callsToSend, node).add(call); return true; } else { log.trace("Unable to assign to a node.", call); return false; } } catch (Throwable t) { log.debug("Unable to choose node for {}", call, t); call.retryOrFail(call, t, now); return true; } }
Source:
public Builder id(String id) { this.id = field1; return getSelf(); }

Target:
public Builder id(String id) { this.id = id; return getSelf(); }
Source:
public static HeaderBuffer create(final ReadableByteChannel channel, final long capacity, final int maxPageBytes) throws IOException { if (maxPageBytes < MAX_GET_ELEMENT_SIZE) { throw new IllegalArgumentException("Page size must be at least " + MAX_GET_ELEMENT_SIZE); } HeaderChannelBuffer channelBuffer = new HeaderChannelBuffer(channel, capacity, maxPageBytes); channelBuffer.fill(); if (channelBuffer.capacity <= maxPageBytes) { return new HeaderInMemoryBuffer(channelBuffer.buffer); } return channelBuffer; }

Target:
public static HeaderBuffer create(final ReadableByteChannel channel, final long capacity, final int maxPageBytes) throws IOException { if (maxPageBytes < MAX_GET_ELEMENT_SIZE) { throw new IllegalArgumentException("Page size must be at least " + MAX_GET_ELEMENT_SIZE); } if (capacity <= maxPageBytes) { ByteBuffer buf = ByteBuffer.allocate((int) capacity).order(ByteOrder.LITTLE_ENDIAN); IOUtils.readFully(channel, buf); buf.flip(); return new HeaderInMemoryBuffer(buf); } HeaderChannelBuffer channelBuffer = new HeaderChannelBuffer(channel, capacity, maxPageBytes); channelBuffer.fill(); return channelBuffer; }
Source:
@Override public String toDruidExpression( RexNode rexNode, RelDataType rowType, DruidQuery query) { final RexCall call = (RexCall) rexNode; final RexLiteral flag = (RexLiteral) call.getOperands().get(0); final TimeUnitRange calciteUnit = (TimeUnitRange) flag.getValue(); final RexNode arg = call.getOperands().get(1); final String input = DruidExpressions.toDruidExpression(arg, rowType, query); if (input == null) { return null; } final String druidUnit = EXTRACT_UNIT_MAP.get(calciteUnit); if (druidUnit == null) { return null; } final TimeZone tz; if (arg.getType().getSqlTypeName() == SqlTypeName.TIMESTAMP_WITH_LOCAL_TIME_ZONE) { tz = TimeZone.getTimeZone(query.getConnectionConfig().timeZone()); } else { tz = DateTimeUtils.UTC_ZONE; } return DruidExpressions.applyTimeExtract(input, druidUnit, tz); }

Target:
@Override public String toDruidExpression( RexNode rexNode, RelDataType rowType, DruidQuery query) { final RexCall call = (RexCall) rexNode; final RexLiteral flag = (RexLiteral) call.getOperands().get(0); final TimeUnitRange calciteUnit = (TimeUnitRange) flag.getValue(); final RexNode arg = call.getOperands().get(1); final String input = DruidExpressions.toDruidExpression(arg, rowType, query); if (input == null) { return null; } final String druidUnit = EXTRACT_UNIT_MAP.get(calciteUnit); if (druidUnit == null) { return null; } final TimeZone tz = arg.getType().getSqlTypeName() == SqlTypeName.TIMESTAMP_WITH_LOCAL_TIME_ZONE ? TimeZone.getTimeZone(query.getConnectionConfig().timeZone()) : DateTimeUtils.UTC_ZONE; return DruidExpressions.applyTimeExtract(input, druidUnit, tz); }
Source:
public void testgetBiGaussianValue() throws MSDKException { MultiKeyMap<Integer, Triplet> horizontalSlice = objSliceSparseMatrix.getHorizontalSlice(140.1037, 1, 9); BiGaussianSimilarityTest objBiGaussian = new BiGaussianSimilarityTest(); boolean goodPeak = objBiGaussian.execute(horizontalSlice, 1, 9, 140.1037); Assert.assertEquals(true, goodPeak); }

Target:
public void testgetBiGaussianValue() throws MSDKException { MultiKeyMap<Integer, Triplet> horizontalSlice = objSliceSparseMatrix.getHorizontalSlice(140.1037, 1, 9); BiGaussianSimilarityTest objBiGaussian = new BiGaussianSimilarityTest(); boolean goodPeak = objBiGaussian.execute(horizontalSlice, 1, 9, 140.1037); Assert.assertTrue(goodPeak); }
Source:
public static Properties loadProperties(String path){ String propertiesFilePath = System.getProperty(path); M_log.debug("ccm props: " + propertiesFilePath); if (!propertiesFilePath.isEmpty()) { return PropertiesUtilities.getPropertiesObjectFromURL(propertiesFilePath); } M_log.error("File path for (" + path + ") is not provided"); return null; }

Target:
public static Properties loadProperties(String path){ String propertiesFilePath = System.getProperty(path); M_log.debug(path + " : " + propertiesFilePath); if (!propertiesFilePath.isEmpty()) { return PropertiesUtilities.getPropertiesObjectFromURL(propertiesFilePath); } M_log.error("File path for (" + path + ") is not provided"); return null; }
Source:
private List<WebElement> findSummaryElement(int notificationNumber, int groupIndex) { WebElement notifications = getDriver().findElementsByCssSelector(NOTIFICATION_EVENT_SELECTOR).get(notificationNumber); WebElement element = notifications.findElements(cssSelector(TEXT_SELECTOR)).get(groupIndex); return element.findElements(xpath(SUMMARY_SELECTOR)); }

Target:
private List<WebElement> findSummaryElement(int notificationNumber, int groupIndex) { WebElement notifications = findNotifications().get(notificationNumber); WebElement element = notifications.findElements(cssSelector(TEXT_SELECTOR)).get(groupIndex); return element.findElements(xpath(SUMMARY_SELECTOR)); }
Source:
protected void addDragAndDropSupport(final NatTable nattable) { final int operations = DND.DROP_MOVE | DND.DROP_COPY | DND.DROP_DEFAULT; final DropTarget target = new DropTarget(nattable, operations); final LocalTransfer localTransfer = LocalTransfer.getInstance(); final LocalSelectionTransfer localSelectionTransfer = LocalSelectionTransfer.getTransfer(); final Transfer[] types = new Transfer[] { localSelectionTransfer, localTransfer }; target.setTransfer(types); final NatTableDropListener dropListener = createDropListener(); target.addDropListener(dropListener); BooleanValueStyle values = (BooleanValueStyle) table.getTableConfiguration().getNamedStyle(NattablestylePackage.eINSTANCE.getBooleanValueStyle(), NamedStyleConstants.DRAG_ENABLED); if (null != values && values.isBooleanValue()) { natTable.addDragSupport(operations, types, new NatTableDragSourceListener(this, natTable, Collections.singletonList(GridRegion.ROW_HEADER))); } }

Target:
protected void addDragAndDropSupport(final NatTable nattable) { final int operations = DND.DROP_MOVE | DND.DROP_COPY | DND.DROP_DEFAULT; final DropTarget target = new DropTarget(nattable, operations); final LocalTransfer localTransfer = LocalTransfer.getInstance(); final LocalSelectionTransfer localSelectionTransfer = LocalSelectionTransfer.getTransfer(); final Transfer[] types = new Transfer[] { localSelectionTransfer, localTransfer }; target.setTransfer(types); final NatTableDropListener dropListener = createDropListener(); target.addDropListener(dropListener); BooleanValueStyle values = (BooleanValueStyle) table.getNamedStyle(NattablestylePackage.eINSTANCE.getBooleanValueStyle(), NamedStyleConstants.DRAG_ENABLED); if (null == values) { values = (BooleanValueStyle) table.getTableConfiguration().getNamedStyle(NattablestylePackage.eINSTANCE.getBooleanValueStyle(), NamedStyleConstants.DRAG_ENABLED); } if (null != values && values.isBooleanValue()) { natTable.addDragSupport(operations, types, new NatTableDragSourceListener(this, natTable, Collections.singletonList(GridRegion.ROW_HEADER))); } }
Source:
public boolean equals(Object other) { if (!(other instanceof GuestId)) { return false; } GuestId that = (GuestId) other; if (this.getGuestId().equalsIgnoreCase(that.getGuestId())) { EqualsBuilder builder = new EqualsBuilder() .append(this.getAttributes(), that.getAttributes()); return builder.isEquals(); } return false; }

Target:
public boolean equals(Object other) { if (!(other instanceof GuestId)) { return false; } GuestId that = (GuestId) other; if (this.getGuestId().equalsIgnoreCase(that.getGuestId()) && this.getAttributes().equals(that.getAttributes())) { return true; } return false; }
Source:
protected static String sanitize(String namespace) { Pattern DOT_OR_WHITESPACE = Pattern.compile("[\\s]+|[.]+"); return DOT_OR_WHITESPACE.matcher(namespace).replaceAll("_"); }

Target:
private static String sanitize(String namespace) { return DOT_OR_WHITESPACE.matcher(namespace).replaceAll("_"); }
Source:
public void testErrorChannel() throws Exception { final DirectChannel requestChannel = new DirectChannel(); requestChannel.subscribe(new AbstractReplyProducingMessageHandler() { @Override protected Object handleRequestMessage(Message<?> requestMessage) { throw new RuntimeException(); } }); final DirectChannel errorChannel = new DirectChannel(); errorChannel.subscribe(new AbstractReplyProducingMessageHandler() { @Override protected Object handleRequestMessage(Message<?> requestMessage) { return new Target("failed"); } }); final QueueChannel replyChannel = new QueueChannel(); final ContentEnricher enricher = new ContentEnricher(); enricher.setRequestChannel(requestChannel); enricher.setErrorChannel(errorChannel); SpelExpressionParser parser = new SpelExpressionParser(); Map<String, Expression> propertyExpressions = new HashMap<String, Expression>(); propertyExpressions.put("name", parser.parseExpression("payload.name + ' target'")); enricher.setPropertyExpressions(propertyExpressions); enricher.setBeanFactory(mock(BeanFactory.class)); enricher.afterPropertiesSet(); final Target target = new Target("replace me"); Message<?> requestMessage = MessageBuilder.withPayload(target).setReplyChannel(replyChannel).build(); enricher.handleMessage(requestMessage); Message<?> reply = replyChannel.receive(0); Target result = (Target) reply.getPayload(); assertEquals("failed target", result.getName()); }

Target:
public void testErrorChannel() throws Exception { final DirectChannel requestChannel = new DirectChannel(); requestChannel.subscribe(new AbstractReplyProducingMessageHandler() { @Override protected Object handleRequestMessage(Message<?> requestMessage) { throw new RuntimeException(); } }); final DirectChannel errorChannel = new DirectChannel(); errorChannel.subscribe(new AbstractReplyProducingMessageHandler() { @Override protected Object handleRequestMessage(Message<?> requestMessage) { return new Target("failed"); } }); final QueueChannel replyChannel = new QueueChannel(); final ContentEnricher enricher = new ContentEnricher(); enricher.setRequestChannel(requestChannel); enricher.setErrorChannel(errorChannel); SpelExpressionParser parser = new SpelExpressionParser(); Map<String, Expression> propertyExpressions = new HashMap<String, Expression>(); propertyExpressions.put("name", parser.parseExpression("payload.name + ' target'")); enricher.setPropertyExpressions(propertyExpressions); enricher.setBeanFactory(mock(BeanFactory.class)); enricher.afterPropertiesSet(); final Target target = new Target("replace me"); Message<?> requestMessage = MessageBuilder.withPayload(target).setReplyChannel(replyChannel).build(); enricher.handleMessage(requestMessage); Message<?> reply = replyChannel.receive(10000); Target result = (Target) reply.getPayload(); assertEquals("failed target", result.getName()); }
Source:
private <S extends Message, A extends AggregatePart<I, S, ?>> AggregatePartRepository<I, A> getRepository(Class<S> stateClass) { @SuppressWarnings("unchecked") final AggregatePartRepository<I, A> cached = (AggregatePartRepository<I, A>) partsAccess.get(stateClass); if (cached != null) { return cached; } final AggregatePartRepository<I, A> repo = lookup(stateClass); partsAccess.put(stateClass, repo); return repo; }

Target:
AggregatePartRepository<I, A> getRepository(Class<S> stateClass) { @SuppressWarnings("unchecked") final AggregatePartRepository<I, A> cached = (AggregatePartRepository<I, A>) partsAccess.get(stateClass); if (cached != null) { return cached; } final AggregatePartRepository<I, A> repo = lookup(stateClass); partsAccess.put(stateClass, repo); return repo; }
Source:
public void createCheckRun() throws Exception { GHCheckRun checkRun = gitHub.getRepository("jglick/github-api-test") .createCheckRun("foo", "4a929d464a2fae7ee899ce603250f7dab304bc4b") .withStatus(GHCheckRun.Status.COMPLETED) .withConclusion(GHCheckRun.Conclusion.SUCCESS) .withDetailsURL("<LINK_0>") .withExternalID("whatever") .withStartedAt(new Date(999_999_000)) .withCompletedAt(new Date(999_999_999)) .withOutput("Some Title", "what happened…") .withAnnotation("stuff.txt", 1, GHCheckRun.AnnotationLevel.NOTICE, "hello to you too") .withTitle("Look here") .done() .withImage("Unikitty", "<LINK_1>") .withCaption("Princess Unikitty") .done() .done() .withAction("Help", "what I need help with", "doit") .create(); assertEquals("completed", checkRun.getStatus()); assertEquals(1, checkRun.getOutput().getAnnotationsCount()); assertEquals(535049329, checkRun.id); }

Target:
public void createCheckRun() throws Exception { GHCheckRun checkRun = gitHub.getRepository("jglick/github-api-test") .createCheckRun("foo", "4a929d464a2fae7ee899ce603250f7dab304bc4b") .withStatus(GHCheckRun.Status.COMPLETED) .withConclusion(GHCheckRun.Conclusion.SUCCESS) .withDetailsURL("<LINK_0>") .withExternalID("whatever") .withStartedAt(new Date(999_999_000)) .withCompletedAt(new Date(999_999_999)) .add(new GHCheckRunBuilder.Output("Some Title", "what happened…") .add(new GHCheckRunBuilder.Annotation("stuff.txt", 1, GHCheckRun.AnnotationLevel.NOTICE, "hello to you too").withTitle("Look here")) .add(new GHCheckRunBuilder.Image("Unikitty", "<LINK_1>") .withCaption("Princess Unikitty"))) .add(new GHCheckRunBuilder.Action("Help", "what I need help with", "doit")) .create(); assertEquals("completed", checkRun.getStatus()); assertEquals(1, checkRun.getOutput().getAnnotationsCount()); assertEquals(546384586, checkRun.id); }
Source:
public Mono<Response<Secret>> restoreSecretWithResponse(byte[] backup) { return withContext(context -> restoreSecret(backup, context)); }

Target:
public Mono<Response<Secret>> restoreSecretWithResponse(byte[] backup) { return withContext(context -> restoreSecretWithResponse(backup, context)); }
Source:
public void verifyBmpProcessing() { final InetSocketAddress bgpTelemetryAddress = stack.opennms().getNetworkProtocolAddress(NetworkProtocol.BMP); final String node = "<node type=\"A\" label=\"TestNode\" foreignSource=\"SmokeTests\" foreignId=\"TestNode\">" + "<labelSource>H</labelSource>" + "<sysContact>Me</sysContact>" + "<sysDescription>PDP-8</sysDescription>" + "<sysLocation>German DevJam 2020</sysLocation>" + "<sysName>TestNode</sysName>" + "<sysObjectId>.1.3.6.1.4.1.8072.3.2.255</sysObjectId>" + "<createTime>2020-02-25T13:20:00.123-04:00</createTime>" + "<lastCapsdPoll>2020-02-25T13:21:00.456-04:00</lastCapsdPoll>" + "</node>"; given().body(node) .basePath("/opennms/rest/nodes") .contentType(ContentType.XML).post() .then().assertThat() .statusCode(201); final String ipInterface = "<ipInterface isManaged=\"M\" snmpPrimary=\"P\">" + "<ipAddress>" + getLocalAddress() + "</ipAddress>" + "<hostName>test-machine1.local</hostName>" + "</ipInterface>"; given().body(ipInterface) .basePath("/opennms/rest/nodes/SmokeTests:TestNode/ipinterfaces") .contentType(ContentType.XML).post() .then().assertThat() .statusCode(201); await().atMost(1, MINUTES).pollDelay(0, SECONDS).pollInterval(5, SECONDS) .until(() -> { sendBmpTelemetryMessage(bgpTelemetryAddress); return matchRrdFileFromNodeResource("SmokeTests:TestNode"); }); }

Target:
public void verifyBmpProcessing() { final InetSocketAddress bgpTelemetryAddress = stack.opennms().getNetworkProtocolAddress(NetworkProtocol.BMP); final String node = "<node type=\"A\" label=\"TestNode\" foreignSource=\"SmokeTests\" foreignId=\"TestNode\">" + "<labelSource>H</labelSource>" + "<sysContact>Me</sysContact>" + "<sysDescription>Black Ops 4</sysDescription>" + "<sysLocation>German DevJam 2020</sysLocation>" + "<sysName>TestNode</sysName>" + "<sysObjectId>.1.3.6.1.4.1.8072.3.2.255</sysObjectId>" + "<createTime>2020-02-25T13:20:00.123-04:00</createTime>" + "<lastCapsdPoll>2020-02-25T13:21:00.456-04:00</lastCapsdPoll>" + "</node>"; given().body(node) .basePath("/opennms/rest/nodes") .contentType(ContentType.XML).post() .then().assertThat() .statusCode(201); final String ipInterface = "<ipInterface isManaged=\"M\" snmpPrimary=\"P\">" + "<ipAddress>" + getLocalAddress() + "</ipAddress>" + "<hostName>test-machine1.local</hostName>" + "</ipInterface>"; given().body(ipInterface) .basePath("/opennms/rest/nodes/SmokeTests:TestNode/ipinterfaces") .contentType(ContentType.XML).post() .then().assertThat() .statusCode(201); await().atMost(1, MINUTES).pollDelay(0, SECONDS).pollInterval(5, SECONDS) .until(() -> { sendBmpTelemetryMessage(bgpTelemetryAddress); return matchRrdFileFromNodeResource("SmokeTests:TestNode"); }); }
Source:
private boolean vmUsesScsiReservation() { List<VmDevice> vmManagedDevices = DbFacade.getInstance().getVmDeviceDao().getVmDeviceByVmId(getVmId()); if (vmManagedDevices != null && !vmManagedDevices.isEmpty()) { for (VmDevice device : vmManagedDevices) { if (device.isScsiReservationUsed()) { return true; } } } return false; }

Target:
private boolean vmUsesScsiReservation() { List<VmDevice> devices = DbFacade.getInstance().getVmDeviceDao().getVmDeviceByVmId(getVmId()); if (devices != null) { for (VmDevice device : devices) { if (device.isScsiReservationUsed()) { return true; } } } return false; }
Source:
private void setupBackPressureCheckTimer(final Map<String, Object> topologyConf) { Set<Integer> nonLocalTasks = Sets.difference(workerState.getTaskToComponent().keySet(), new HashSet<>(workerState.getLocalTaskIds())); if (nonLocalTasks.isEmpty()) { LOG.info("BackPressure change checking is disabled as there is only one worker"); return; } final Long bpCheckIntervalMs = ObjectReader.getLong(topologyConf.get(Config.TOPOLOGY_BACKPRESSURE_CHECK_MILLIS)); workerState.backPressureCheckTimer.scheduleRecurringMs(bpCheckIntervalMs, bpCheckIntervalMs, () -> workerState.refreshBackPressureStatus()); LOG.info("BackPressure status change checking will be performed every millis", bpCheckIntervalMs); }

Target:
private void setupBackPressureCheckTimer(final Map<String, Object> topologyConf) { if (workerState.isSingleWorker()) { LOG.info("BackPressure change checking is disabled as there is only one worker"); return; } final Long bpCheckIntervalMs = ObjectReader.getLong(topologyConf.get(Config.TOPOLOGY_BACKPRESSURE_CHECK_MILLIS)); workerState.backPressureCheckTimer.scheduleRecurringMs(bpCheckIntervalMs, bpCheckIntervalMs, () -> workerState.refreshBackPressureStatus()); LOG.info("BackPressure status change checking will be performed every millis", bpCheckIntervalMs); }