auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void traverseStacks(Stacks stacks, ArrayList<DownloadRuntime> list, IProgressMonitor monitor) { List<org.jboss.jdf.stacks.model.Runtime> runtimes = stacks.getAvailableRuntimes(); Iterator<org.jboss.jdf.stacks.model.Runtime> i = runtimes.iterator(); org.jboss.jdf.stacks.model.Runtime workingRT = null; monitor.beginTask(Messages.CreateDownloadRuntimes, runtimes.size() * 100); while(i.hasNext()) { workingRT = i.next(); String wtpRT = workingRT.getLabels().getProperty(LABEL_WTP_RUNTIME); <START> String dlUrl = workingRT.getDownloadUrl(); <END> if( wtpRT != null ) { String fileSize = workingRT.getLabels().getProperty(LABEL_FILE_SIZE); String license = workingRT.getLicense(); String id = workingRT.getId(); String legacyId = getLegacyId(id); String effectiveId = legacyId == null ? id : legacyId; String name = workingRT.getName(); String version = workingRT.getVersion(); DownloadRuntime dr = new DownloadRuntime(effectiveId, name, version, dlUrl); dr.setHumanUrl(workingRT.getUrl()); dr.setLicenseURL(license); dr.setSize(fileSize); dr.setProperty(PROP_WTP_RUNTIME, wtpRT); dr.setProperty(LABEL_RUNTIME_CATEGORY, workingRT.getLabels().getProperty(LABEL_RUNTIME_CATEGORY)); dr.setProperty(LABEL_RUNTIME_TYPE, workingRT.getLabels().getProperty(LABEL_RUNTIME_TYPE)); if( legacyId != null ) dr.setProperty(DownloadRuntime.PROPERTY_ALTERNATE_ID, id); list.add(dr); } monitor.worked(100); } monitor.done(); }</code><technical_language>dlUrl set if block</technical_language>

Target:
private void traverseStacks(Stacks stacks, ArrayList<DownloadRuntime> list, IProgressMonitor monitor) { List<org.jboss.jdf.stacks.model.Runtime> runtimes = stacks.getAvailableRuntimes(); Iterator<org.jboss.jdf.stacks.model.Runtime> i = runtimes.iterator(); org.jboss.jdf.stacks.model.Runtime workingRT = null; monitor.beginTask(Messages.CreateDownloadRuntimes, runtimes.size() * 100); while(i.hasNext()) { workingRT = i.next(); String wtpRT = workingRT.getLabels().getProperty(LABEL_WTP_RUNTIME); if( wtpRT != null ) { String fileSize = workingRT.getLabels().getProperty(LABEL_FILE_SIZE); String license = workingRT.getLicense(); String dlUrl = workingRT.getDownloadUrl(); String id = workingRT.getId(); String legacyId = getLegacyId(id); String effectiveId = legacyId == null ? id : legacyId; String name = workingRT.getName(); String version = workingRT.getVersion(); DownloadRuntime dr = new DownloadRuntime(effectiveId, name, version, dlUrl); dr.setHumanUrl(workingRT.getUrl()); dr.setLicenseURL(license); dr.setSize(fileSize); dr.setProperty(PROP_WTP_RUNTIME, wtpRT); dr.setProperty(LABEL_RUNTIME_CATEGORY, workingRT.getLabels().getProperty(LABEL_RUNTIME_CATEGORY)); dr.setProperty(LABEL_RUNTIME_TYPE, workingRT.getLabels().getProperty(LABEL_RUNTIME_TYPE)); if( legacyId != null ) dr.setProperty(DownloadRuntime.PROPERTY_ALTERNATE_ID, id); list.add(dr); } monitor.worked(100); } monitor.done(); }
Source:
<code>protected List<ExecutorDetails> orderExecutors( TopologyDetails td, Collection<ExecutorDetails> unassignedExecutors) { <START> Boolean orderByProximity = (Boolean) td.getConf() <END> .getOrDefault(Config.TOPOLOGY_RAS_SCHEDULE_EXECUTORS_BY_PROXIMITY_NEEDS, false); if (!orderByProximity) { return orderExecutorsDefault(td, unassignedExecutors); } else { LOG.info("{} is set to true", Config.TOPOLOGY_RAS_SCHEDULE_EXECUTORS_BY_PROXIMITY_NEEDS); return orderExecutorsByProximityNeeds(td, unassignedExecutors); } }</code><technical_language>ObjectReader.getBoolean()</technical_language>

Target:
protected List<ExecutorDetails> orderExecutors( TopologyDetails td, Collection<ExecutorDetails> unassignedExecutors) { Boolean orderByProximity = ObjectReader.getBoolean( td.getConf().get(Config.TOPOLOGY_RAS_ORDER_EXECUTORS_BY_PROXIMITY_NEEDS), false); if (!orderByProximity) { return orderExecutorsDefault(td, unassignedExecutors); } else { LOG.info("{} is set to true", Config.TOPOLOGY_RAS_ORDER_EXECUTORS_BY_PROXIMITY_NEEDS); return orderExecutorsByProximityNeeds(td, unassignedExecutors); } }
Source:
<code>public void processExpires() { log.debug("Processing expired sessions"); Query<Key> query = Query.newKeyQueryBuilder().setKind(sessionKind) .setFilter(PropertyFilter.le(SessionMetadata.EXPIRATION_TIME.getValue(), <START> System.currentTimeMillis())) <END> .build(); QueryResults<Key> keys = datastore.run(query); Stream<Key> toDelete = Streams.stream(keys) .parallel() .flatMap(key -> Streams.stream(datastore.run(Query.newKeyQueryBuilder() .setKind(sessionKind) .setFilter(PropertyFilter.hasAncestor(newKey(key.getName()))) .build()))); datastore.delete(toDelete.toArray(Key[]::new)); }</code><technical_language>extract this a Clock interface for testability</technical_language>

Target:
public void processExpires() { log.debug("Processing expired sessions"); Query<Key> query = Query.newKeyQueryBuilder().setKind(sessionKind) .setFilter(PropertyFilter.le(SessionMetadata.EXPIRATION_TIME, clock.millis())) .build(); QueryResults<Key> keys = datastore.run(query); Stream<Key> toDelete = Streams.stream(keys) .parallel() .flatMap(key -> Streams.stream(datastore.run(Query.newKeyQueryBuilder() .setKind(sessionKind) .setFilter(PropertyFilter.hasAncestor(newKey(key.getName()))) .build()))); datastore.delete(toDelete.toArray(Key[]::new)); }
Source:
<code>private static String getObjectName(MemberExpressionTree dme) { <START> if (dme.object() != null) { <END> if (dme.object().is(Tree.Kind.DOT_MEMBER_EXPRESSION)) { DotMemberExpressionTree d2 = (DotMemberExpressionTree) dme.object(); return d2.property().name(); } else { return CheckUtils.asString(dme.object()); } } return ""; }</code><technical_language>@ganncamp this null check required [MemberExpression#object()](<LINK_0> is nullable null</technical_language>

Target:
private static String getObjectName(MemberExpressionTree dme) { if (dme.object().is(Tree.Kind.DOT_MEMBER_EXPRESSION)) { DotMemberExpressionTree d2 = (DotMemberExpressionTree) dme.object(); return d2.property().name(); } else { return CheckUtils.asString(dme.object()); } }
Source:
<code>public EndpointsByRange build() { Map<Range<Token>, EndpointsForRange> map = Collections.unmodifiableMap( <START> new HashMap<>( <END> Maps.transformValues(this.map, EndpointsForRange.Builder::build))); return new EndpointsByRange(map); }</code><technical_language>Is cheaper than, ImmutableMap.copyOf()</technical_language>

Target:
public EndpointsByRange build() { return new EndpointsByRange( ImmutableMap.copyOf( Maps.transformValues(this.map, EndpointsForRange.Builder::build))); }
Source:
<code>private static boolean shouldCreateMyHandler(PsiElement element) { if (element instanceof LeafPsiElement) { LeafPsiElement leaf = (LeafPsiElement)element; return leaf.getElementType() == GoTypes.RETURN || leaf.getElementType() == GoTypes.FUNC || isPanicCall(leaf); } <START> else { <END> return false; } }</code><technical_language>A redundant else statement</technical_language>

Target:
private static boolean shouldCreateMyHandler(PsiElement element) { if (element instanceof LeafPsiElement) { LeafPsiElement leaf = (LeafPsiElement)element; return leaf.getElementType() == GoTypes.RETURN || leaf.getElementType() == GoTypes.FUNC || isPanicCall(leaf); } return false; }
Source:
<code>public ResourceGroupStateInfo getStateInfo() { synchronized (root) { return new ResourceGroupStateInfo( id, getState(), DataSize.succinctBytes(softMemoryLimitBytes), DataSize.succinctBytes(cachedMemoryUsageBytes), maxRunningQueries, maxQueuedQueries, runningTimeLimit, queuedTimeLimit, getAggregatedRunningQueriesInfo(), queuedQueries.size() + descendantQueuedQueries, subGroups.values().stream() .map(subGroup -> new ResourceGroupInfo( subGroup.getId(), <START> new DataSize(softMemoryLimitBytes, BYTE), <END> maxRunningQueries, runningTimeLimit, maxQueuedQueries, queuedTimeLimit, getState(), eligibleSubGroups.size(), new DataSize(cachedMemoryUsageBytes, BYTE), runningQueries.size() + descendantRunningQueries, queuedQueries.size() + descendantQueuedQueries)) .collect(toImmutableList())); } }</code><technical_language>succinctBytes</technical_language>

Target:
public ResourceGroupStateInfo getStateInfo() { synchronized (root) { return new ResourceGroupStateInfo( id, getState(), DataSize.succinctBytes(softMemoryLimitBytes), DataSize.succinctBytes(cachedMemoryUsageBytes), maxRunningQueries, maxQueuedQueries, runningTimeLimit, queuedTimeLimit, getAggregatedRunningQueriesInfo(), queuedQueries.size() + descendantQueuedQueries, subGroups.values().stream() .map(subGroup -> new ResourceGroupInfo( subGroup.getId(), DataSize.succinctBytes(softMemoryLimitBytes), maxRunningQueries, runningTimeLimit, maxQueuedQueries, queuedTimeLimit, getState(), eligibleSubGroups.size(), DataSize.succinctBytes(cachedMemoryUsageBytes), runningQueries.size() + descendantRunningQueries, queuedQueries.size() + descendantQueuedQueries)) .collect(toImmutableList())); } }
Source:
<code>public void ensureColumnPresent(Column<T, ?> column, String headerText, boolean present, String width) { if (present) { <START> if (getColumnIndex(column) == -1) { <END> if (width == null) { addColumnWithHtmlHeader(column, headerText); } else { addColumnWithHtmlHeader(column, headerText, width); } } } else if (!present && getColumnIndex(column) != -1) { removeColumn(column); } }</code><technical_language>I guess condition unified so: if (present && getColumnIndex(column) == -1) improve readability a bit here, consideration: boolean columnAttached = getColumnIndex(column) != -1; if (!columnAttached && present) { ... } else if (columnAttached && !present) { ... } Also, please verify this patch in WebAdmin "Events" main tab, clicking "Basic" vs. "Advanced" radio buttons (columns jump retain logical position)</technical_language>

Target:
public void ensureColumnPresent(Column<T, ?> column, String headerText, boolean present, String width) { boolean columnPresent = getColumnIndex(column) != -1; if (present && !columnPresent) { if (width == null) { addColumnWithHtmlHeader(column, headerText); } else { addColumnWithHtmlHeader(column, headerText, width); } } else if (!present && columnPresent) { removeColumn(column); } }
Source:
<code><START> public ConsoleProfileFinished(String id, Location location, Profile profile, String title) { <END> this.setId(id); this.setLocation(location); this.setProfile(profile); this.setTitle(title); }</code><technical_language>Check non-optional fields nonNull in constructor, instances in illegal state</technical_language>

Target:
public ConsoleProfileFinished(String id, Location location, Profile profile, String title) { Objects.requireNonNull(id, "id is require"); Objects.requireNonNull(location, "location is require"); Objects.requireNonNull(profile, "profile is require"); this.id = id; this.location = location; this.profile = profile; this.title = title; }
Source:
<code>public void stop() { <START> if (!state.compareAndSet(State.STARTED, State.STOPPING)) { <END> throw new IllegalStateException(String.format("Expected state [%s] found [%s]", State.STARTED, state.get())); } try { runCallbacks(); } finally { state.compareAndSet(State.STOPPING, State.STOPPED); } }</code><technical_language>Ran a spark bug a days a shutdown hook firing a "clean" shutdown problems. This method needs synchronized else a shutdown hook fired a SIGTERM wait for runCallbacks() finish</technical_language>

Target:
public void stop() { if (!state.compareAndSet(State.STARTED, State.STOPPING)) { State current = state.waitForTransition(State.STOPPING, State.STOPPED, SHUTDOWN_WAIT_TIMEOUT); if (current != State.STOPPED) { throw new IllegalStateException(String.format("Expected state [%s] found [%s]", State.STARTED, current)); } return; } try { runCallbacks(); } finally { state.compareAndSet(State.STOPPING, State.STOPPED); } }
Source:
<code>void shouldBeAbleToUpdateRoles(String acceptHeader) { final String username = "test-user"; final String newPassword = "password"; UserDto user = new UserDto(); user.setEnabled(true); user.setUsername(username); user.setPassword(newPassword); user.setSecurityTokenKey("some-security-token"); user.setRoles(ImmutableSet.of(SystemRole.UI_MANAGER.name())); userService.save(user); UserForm admin = buildUser(username, newPassword); User updatedUser = retrieveUserByName(admin.getUsername()); <START> assertThat(SetUtils.isEqualSet(updatedUser.getRoles() <END> .stream() .map(UserRole::getUserRole) .collect(Collectors.toSet()), ImmutableSet.of(SystemRole.UI_MANAGER.name()))).isTrue(); admin.setRoles(ImmutableSet.of("ADMIN")); mockMvc.contentType(MediaType.APPLICATION_JSON_VALUE) .accept(acceptHeader) .body(admin) .when() .put(getContextBaseUrl() + "/{username}", username) .peek() .then() .statusCode(HttpStatus.OK.value()) .body(containsString(SUCCESSFUL_UPDATE_USER)) .extract() .asString(); updatedUser = retrieveUserByName(admin.getUsername()); assertThat(SetUtils.isEqualSet(updatedUser.getRoles() .stream() .map(UserRole::getUserRole) .collect(Collectors.toSet()), ImmutableSet.of("ADMIN"))).isTrue(); admin.setRoles(ImmutableSet.of(SystemRole.UI_MANAGER.name())); mockMvc.contentType(MediaType.APPLICATION_JSON_VALUE) .accept(acceptHeader) .body(admin) .when() .put(getContextBaseUrl() + "/{username}", username) .then() .statusCode(HttpStatus.OK.value()); }</code><technical_language>@anki2189 change controller interface affect UI. @steve-todorov FLY</technical_language>

Target:
void shouldBeAbleToUpdateRoles(String acceptHeader) { final String username = "test-user"; final String newPassword = "password"; UserDto user = new UserDto(); user.setEnabled(true); user.setUsername(username); user.setPassword(newPassword); user.setSecurityTokenKey("some-security-token"); user.setRoles(ImmutableSet.of(SystemRole.UI_MANAGER.name())); userService.save(user); UserForm admin = buildUser(username, newPassword); User updatedUser = retrieveUserByName(admin.getUsername()); assertThat(SetUtils.isEqualSet(updatedUser.getRoles() .stream() .map(SecurityRole::getRoleName) .collect(Collectors.toSet()), ImmutableSet.of(SystemRole.UI_MANAGER.name()))).isTrue(); admin.setRoles(ImmutableSet.of("ADMIN")); mockMvc.contentType(MediaType.APPLICATION_JSON_VALUE) .accept(acceptHeader) .body(admin) .when() .put(getContextBaseUrl() + "/{username}", username) .peek() .then() .statusCode(HttpStatus.OK.value()) .body(containsString(SUCCESSFUL_UPDATE_USER)) .extract() .asString(); updatedUser = retrieveUserByName(admin.getUsername()); assertThat(SetUtils.isEqualSet(updatedUser.getRoles() .stream() .map(SecurityRole::getRoleName) .collect(Collectors.toSet()), ImmutableSet.of("ADMIN"))).isTrue(); admin.setRoles(ImmutableSet.of(SystemRole.UI_MANAGER.name())); mockMvc.contentType(MediaType.APPLICATION_JSON_VALUE) .accept(acceptHeader) .body(admin) .when() .put(getContextBaseUrl() + "/{username}", username) .then() .statusCode(HttpStatus.OK.value()); }
Source:
<code><START> private void validateMetadata(Map<String,List<String>> metadata, String key, String mapping) { <END> BeanPropertyBindingResult errors = new BeanPropertyBindingResult(key, "contentSettings.metadata"); Pattern regex = Pattern.compile("[a-z0-9_]+"); if (StringUtils.isBlank(key) || StringUtils.isBlank(mapping) || !regex.matcher(key).matches()) { errors.reject("3", null, "contentsettings.metadata.invalid"); throw new ValidationGenericException(errors); } for(String value : mapping.split(",")) { if (!regex.matcher(value).matches()) { errors.reject("3", null, "contentsettings.metadata.invalid"); throw new ValidationGenericException(errors); } } if (metadata.containsKey(key)) { errors.reject("4", null, "contentsettings.metadata.duplicate"); throw new ValidationConflictException(errors); } }</code><technical_language>this unit tests</technical_language>

Target:
public void validateMetadata(Map<String,List<String>> metadata, String key, String mapping) { BeanPropertyBindingResult errors = new BeanPropertyBindingResult(key, "contentSettings.metadata"); Pattern regex = Pattern.compile("[a-z0-9_]+"); if (StringUtils.isBlank(key) || StringUtils.isBlank(mapping) || !regex.matcher(key).matches()) { errors.reject("3", null, "contentsettings.metadata.invalid"); throw new ValidationGenericException(errors); } for(String value : mapping.split(",")) { if (!regex.matcher(value.trim()).matches()) { errors.reject("3", null, "contentsettings.metadata.invalid"); throw new ValidationGenericException(errors); } } if (metadata.containsKey(key)) { errors.reject("4", null, "contentsettings.metadata.duplicate"); throw new ValidationConflictException(errors); } }
Source:
<code>public void enterIdentifier(SwiftParser.IdentifierContext ctx) { String constantName = ctx.getText(); ParserRuleContext constantDecContext = ConstantDecHelper.getConstantDeclaration(ctx); Location location = ListenerUtil.getContextStartLocation(ctx); if (ConstantDecHelper.isGlobal(constantDecContext) || ConstantDecHelper.insideClass(constantDecContext) || ConstantDecHelper.insideStruct(constantDecContext)) { if (!CharFormatUtil.isUpperCamelCase(constantName) && !CharFormatUtil.startsWithAcronym(constantName) && !CharFormatUtil.isLowerCamelCase(constantName)) { printer.error(Rules.CONSTANT_NAMING, Messages.GLOBAL + Messages.CONSTANT + Messages.GLOBAL_CONSTANT_NAMING, location); } } else { <START> if (!CharFormatUtil.startsWithAcronym(constantName) && !CharFormatUtil.isLowerCamelCase(constantName)) { <END> printer.error(Rules.CONSTANT_NAMING, Messages.CONSTANT + Messages.LOWER_CAMEL_CASE, location); } } }</code><technical_language>move thestartsWithAcronym check isLowerCamelCase</technical_language>

Target:
public void enterIdentifier(SwiftParser.IdentifierContext ctx) { String constantName = ctx.getText(); ParserRuleContext constantDecContext = ConstantDecHelper.getConstantDeclaration(ctx); Location location = ListenerUtil.getContextStartLocation(ctx); if (ConstantDecHelper.isGlobal(constantDecContext) || ConstantDecHelper.insideClass(constantDecContext) || ConstantDecHelper.insideStruct(constantDecContext)) { if (!CharFormatUtil.isUpperCamelCase(constantName) && !CharFormatUtil.isLowerCamelCaseOrAcronym(constantName)) { printer.error(Rules.CONSTANT_NAMING, Messages.GLOBAL + Messages.CONSTANT + Messages.GLOBAL_CONSTANT_NAMING, location); } } else { if (!CharFormatUtil.isLowerCamelCaseOrAcronym(constantName)) { printer.error(Rules.CONSTANT_NAMING, Messages.CONSTANT + Messages.LOWER_CAMEL_CASE, location); } } }
Source:
<code>public FilePath createTempDir(final String prefix, final String suffix) throws IOException, InterruptedException { try { return new FilePath(this,act(new SecureFileCallable<String>() { private static final long serialVersionUID = 1L; public String invoke(File dir, VirtualChannel channel) throws IOException { File f = File.createTempFile(prefix, suffix, dir); f.delete(); <START> Files.createTempDirectory(f.toPath(), null); <END> return f.getName(); } })); } catch (IOException e) { throw new IOException("Failed to create a temp directory on "+remote,e); } }</code><technical_language>This function is updated #3161, remove this change a merge conflict</technical_language>

Target:
public FilePath createTempDir(final String prefix, final String suffix) throws IOException, InterruptedException { try { return new FilePath(this,act(new SecureFileCallable<String>() { private static final long serialVersionUID = 1L; public String invoke(File dir, VirtualChannel channel) throws IOException { File f = File.createTempFile(prefix, suffix, dir); f.delete(); f.mkdir(); return f.getName(); } })); } catch (IOException e) { throw new IOException("Failed to create a temp directory on "+remote,e); } }
Source:
<code>public void assertPrettyIdentical(String source) { <START> Assertions.assertEquals(new GherkinPrettyFormatter().format(GherkinParser.parse(source)), source); <END> }</code><technical_language>is a lot this line</technical_language>

Target:
void assertPrettyIdentical(String source) { Messages.GherkinDocument gherkinDocument = GherkinParser.parse(source); Assertions.assertEquals(new GherkinPrettyFormatter().format(gherkinDocument), source); }
Source:
<code>public LogCommand all() throws IOException { Map<String, Ref> refs = getRepository().getRefDatabase().getRefs( <START> Constants.R_REFS); <END> for (Ref ref : refs.values()) { ObjectId objectId = ref.getPeeledObjectId(); if (objectId == null) objectId = ref.getObjectId(); add(objectId); } return this; }</code><technical_language>refs/? getAllRefs() including HEAD</technical_language>

Target:
public LogCommand all() throws IOException { for (Ref ref : getRepository().getAllRefs().values()) { ObjectId objectId = ref.getPeeledObjectId(); if (objectId == null) objectId = ref.getObjectId(); add(objectId); } return this; }
Source:
<code>protected BeanDefinitionBuilder buildBeanDefinition(Element element, ParserContext parserContext) { BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(ReactorPublishSubscribeChannel.class); <START> String s = element.getAttribute("dispatcher"); <END> if (!StringUtils.hasText(s)) { builder.addConstructorArgValue(new ReactorProcessorMessageDispatcher()); } else { builder.addConstructorArgReference(s); } return builder; }</code><technical_language>nitpick - s convey information - in Spring world loooooong variable names :smile:</technical_language>

Target:
protected BeanDefinitionBuilder buildBeanDefinition(Element element, ParserContext parserContext) { BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(ReactorPublishSubscribeChannel.class); String dispatcherBeanName = element.getAttribute("dispatcher"); if (!StringUtils.hasText(dispatcherBeanName)) { builder.addConstructorArgValue(new ReactorProcessorMessageDispatcher()); } else { builder.addConstructorArgReference(dispatcherBeanName); } return builder; }
Source:
<code>public void addChild(TimeGraphEntry entry) { if (!(entry instanceof ResourcesEntry)) { throw new IllegalArgumentException(); } ResourcesEntry rEntry = (ResourcesEntry) entry; int index; for (index = 0; index < getChildren().size(); index++) { ResourcesEntry other = (ResourcesEntry) getChildren().get(index); if (rEntry.compareTo(other) < 0) { break; } } <START> entry.setParent(this); <END> getChildren().add(index, entry); }</code><technical_language>avoid making setParent() public if rEntry instead here</technical_language>

Target:
public void addChild(TimeGraphEntry entry) { if (!(entry instanceof ResourcesEntry)) { throw new IllegalArgumentException(); } ResourcesEntry rEntry = (ResourcesEntry) entry; int index; for (index = 0; index < getChildren().size(); index++) { ResourcesEntry other = (ResourcesEntry) getChildren().get(index); if (rEntry.compareTo(other) < 0) { break; } } rEntry.setParent(this); getChildren().add(index, rEntry); }
Source:
<code>public Client createWithDropwizardClient(PaymentGatewayName gateway, GatewayOperation operation, MetricRegistry metricRegistry) { JerseyClientBuilder defaultClientBuilder = new JerseyClientBuilder(environment) .using(new ApacheConnectorProvider()) .using(conf.getClientConfiguration()) <START> .withProperty(READ_TIMEOUT, (int) getReadTimeout(operation, gateway) <END> .orElse(conf.getCustomJerseyClient().getReadTimeout()).toMilliseconds()) .withProperty(CONNECTION_MANAGER, createConnectionManager( gateway.getName(), operation.getConfigKey(), metricRegistry)); if (System.getProperty(PROXY_HOST_PROPERTY) != null && System.getProperty(PROXY_PORT_PROPERTY) != null) { defaultClientBuilder.withProperty(ClientProperties.PROXY_URI, format("http://%s:%s", System.getProperty(PROXY_HOST_PROPERTY), System.getProperty(PROXY_PORT_PROPERTY)) ); } Client client = defaultClientBuilder.build(gateway.getName()); client.register(RestClientLoggingFilter.class); if (conf.isXrayEnabled()) client.register(XRayHttpClientFilter.class); return client; }</code><technical_language>I encapsulate this .orElse in getReadTimeout function, a bit clearer returning gateway specific timeout a default one. allow get rid of Optional<Duration> return a Duration Alternatively, I suggest leave name conf.getCustomJerseyClient().getReadTimeout()).toMilliseconds() defaultTimeout something. a bit easier follow</technical_language>

Target:
public Client createWithDropwizardClient(PaymentGatewayName gateway, GatewayOperation operation, MetricRegistry metricRegistry) { return createWithDropwizardClient(gateway, getReadTimeout(operation, gateway), operation.getConfigKey(), metricRegistry); }
Source:
<code>public <T> AsyncFuture<T> apply( Function<ClusterNode.Group, AsyncFuture<T>> function, BiFunction<T, List<QueryTrace>, T> handleRetryTraceFn ) { final Iterator<ClusterNode.Group> it = groups.iterator(); if (!it.hasNext()) { return async.failed(new RuntimeException("No groups available")); } final RetryPolicy parent = RetryPolicy.timed(30000, RetryPolicy.exponential(100, 5000)); final RetryPolicy iteratorPolicy = clockSource -> { final RetryPolicy.Instance p = parent.apply(clockSource); return () -> { if (it.hasNext()) { return p.next(); } return new RetryPolicy.Decision(false, 0); }; }; return async .retryUntilResolved(() -> { final ClusterNode.Group next = it.next(); return function.apply(next).catchFailed(throwable -> { <START> reporter.reportClusterNodeRPCError(); <END> throw new RuntimeNodeException(next.toString(), throwable.getMessage(), throwable); }).catchCancelled(ignore -> { reporter.reportClusterNodeRPCCancellation(); throw new RuntimeNodeException(next.toString(), "Operation cancelled"); }); }, iteratorPolicy) .directTransform(retryResult -> handleRetryTraceFn.apply(retryResult.getResult(), queryTracesFromRetries(retryResult.getErrors(), retryResult.getBackoffTimings()))); }</code><technical_language>Capitalization rules ignores acronyms, this method reportClusterNodeRpcError(). For reasoning, consider readability of HTTPXMLRPC HttpXmlRpc</technical_language>

Target:
public <T> AsyncFuture<T> apply( Function<ClusterNode.Group, AsyncFuture<T>> function, BiFunction<T, List<QueryTrace>, T> handleRetryTraceFn ) { final Iterator<ClusterNode.Group> it = groups.iterator(); if (!it.hasNext()) { return async.failed(new RuntimeException("No groups available")); } final RetryPolicy parent = RetryPolicy.timed(30000, RetryPolicy.exponential(100, 5000)); final RetryPolicy iteratorPolicy = clockSource -> { final RetryPolicy.Instance p = parent.apply(clockSource); return () -> { if (it.hasNext()) { return p.next(); } return new RetryPolicy.Decision(false, 0); }; }; return async .retryUntilResolved(() -> { final ClusterNode.Group next = it.next(); return function.apply(next).catchFailed(throwable -> { reporter.reportClusterNodeRpcError(); throw new RuntimeNodeException(next.toString(), throwable.getMessage(), throwable); }).catchCancelled(ignore -> { reporter.reportClusterNodeRpcCancellation(); throw new RuntimeNodeException(next.toString(), "Operation cancelled"); }); }, iteratorPolicy) .directTransform(retryResult -> handleRetryTraceFn.apply(retryResult.getResult(), queryTracesFromRetries(retryResult.getErrors(), retryResult.getBackoffTimings()))); }
Source:
<code>private void onEvent(final Set<Method> onEventMethods, final Object sink, final Object payload, final IEvent<?> event) { try { for (Method method : onEventMethods) { OnEvent onEvent = method.getAnnotation(OnEvent.class); if (isPayloadApplicableToHandler(onEvent, payload)) { method.invoke(sink, payload); <START> if (onEvent.stop()) { <END> event.stop(); break; } } } } catch (InvocationTargetException e) { throw new IllegalStateException("Failed to invoke @OnEvent method", e); } catch (IllegalAccessException e) { throw new IllegalStateException("Failed to invoke @OnEvent method", e); } }</code><technical_language>This is flexible. I understand this is annotations. method's return type Void. decide do. Wicket's visitors - stop, continue, continueDontGoDeeper</technical_language>

Target:
private void onEvent(final Set<Method> onEventMethods, final Object sink, final Object payload, final IEvent<?> event) { try { for (Method method : onEventMethods) { if (canCallListenerInterface(sink, method)) { OnEvent onEvent = method.getAnnotation(OnEvent.class); if (isPayloadApplicableToHandler(onEvent, payload)) { Object result = method.invoke(sink, payload); if (result instanceof Visit<?>) { Visit<?> visit = (Visit<?>) result; if (visit.isDontGoDeeper()) { event.dontBroadcastDeeper(); } else if (visit.isStopped()) { event.stop(); break; } } else if (onEvent.stop()) { event.stop(); break; } } } } } catch (InvocationTargetException e) { throw new IllegalStateException("Failed to invoke @OnEvent method", e); } catch (IllegalAccessException e) { throw new IllegalStateException("Failed to invoke @OnEvent method", e); } }
Source:
<code>public List<RepoImage> getUserRequestForStorageDomainRepoFileList(Guid storageDomainId, ImageFileType imageType, boolean forceRefresh) { <START> List<RepoImage> repoList; <END> if (!isStorageDomainValid(storageDomainId, imageType, forceRefresh)) { throw new VdcBLLException(VdcBllErrors.GetIsoListError); } repoList = getCachedIsoListByDomainId(storageDomainId, imageType); return repoList; }</code><technical_language>need for this variable, return returned call getCachedIsoListByDomainId</technical_language>

Target:
public List<RepoImage> getUserRequestForStorageDomainRepoFileList(Guid storageDomainId, ImageFileType imageType, boolean forceRefresh) { if (!isStorageDomainValid(storageDomainId, imageType, forceRefresh)) { throw new VdcBLLException(VdcBllErrors.GetIsoListError); } return getCachedIsoListByDomainId(storageDomainId, imageType); }
Source:
<code>public void testSelectTagAndPlay() { checkIfSpinnerOnBrickAtPositionShowsString(R.id.brick_when_nfc_spinner, nfcBrickPosition, R.string.brick_when_nfc_default_all); clickSpinnerValueOnBrick(R.id.brick_when_nfc_spinner, nfcBrickPosition, R.string.test_tag_name_1); onView(withId(R.id.button_play)) .perform(click()); Script script = ProjectManager.getInstance().getCurrentScene().getSpriteList().get(0).getScript(0); assertEquals("tag not set", ((WhenNfcBrick) script.getScriptBrick()).getNfcTag().getNfcTagName(), tagDataList.get(0).getNfcTagName()); pressBack(); pressBack(); checkIfSpinnerOnBrickAtPositionShowsString(R.id.brick_when_nfc_spinner, nfcBrickPosition, R.string.test_tag_name_1); clickSpinnerValueOnBrick(R.id.brick_when_nfc_spinner, nfcBrickPosition, R.string.test_tag_name_2); onView(withId(R.id.button_play)) .perform(click()); <START> script = ProjectManager.getInstance().getCurrentScene().getSpriteList().get(0).getScript(0); <END> assertEquals("tag not set", ((WhenNfcBrick) script.getScriptBrick()).getNfcTag().getNfcTagName(), tagDataList.get(1).getNfcTagName()); pressBack(); pressBack(); checkIfSpinnerOnBrickAtPositionShowsString(R.id.brick_when_nfc_spinner, nfcBrickPosition, R.string .test_tag_name_2); }</code><technical_language>get a reference script, do call again? also, save a reference a script initialize in createProject instead of digging for it</technical_language>

Target:
public void testSelectTagAndPlay() { checkIfSpinnerOnBrickAtPositionShowsString(R.id.brick_when_nfc_spinner, nfcBrickPosition, R.string.brick_when_nfc_default_all); clickSpinnerValueOnBrick(R.id.brick_when_nfc_spinner, nfcBrickPosition, R.string.test_tag_name_1); onView(withId(R.id.button_play)) .perform(click()); assertEquals("Tag not set", ((WhenNfcBrick) scriptUnderTest.getScriptBrick()).getNfcTag().getNfcTagName(), tagDataList.get(0).getNfcTagName()); pressBack(); pressBack(); checkIfSpinnerOnBrickAtPositionShowsString(R.id.brick_when_nfc_spinner, nfcBrickPosition, R.string.test_tag_name_1); clickSpinnerValueOnBrick(R.id.brick_when_nfc_spinner, nfcBrickPosition, R.string.test_tag_name_2); onView(withId(R.id.button_play)) .perform(click()); assertEquals("tag not set", ((WhenNfcBrick) scriptUnderTest.getScriptBrick()).getNfcTag().getNfcTagName(), tagDataList.get(1).getNfcTagName()); pressBack(); pressBack(); checkIfSpinnerOnBrickAtPositionShowsString(R.id.brick_when_nfc_spinner, nfcBrickPosition, R.string .test_tag_name_2); }
Source:
<code>public void logRenamedEntity() { abstract class RenameCommand extends CommandBaseDummy implements RenamedEntityInfoProvider { private static final long serialVersionUID = 1L; protected RenameCommand(VdcActionParametersBase params) { super(params); } } RenameCommand command = Mockito.mock(RenameCommand.class); <START> Mockito.when(command.getEntityOldName()).thenReturn(null); <END> Mockito.when(command.getEntityNewName()).thenReturn(null); Mockito.doCallRealMethod().when(command).logRenamedEntity(); command.logRenamedEntity(); Mockito.when(command.getEntityOldName()).thenReturn("foo"); Mockito.when(command.getEntityNewName()).thenReturn("bar"); command.logRenamedEntity(); Mockito.when(command.getEntityOldName()).thenReturn(null); Mockito.when(command.getEntityNewName()).thenReturn("bar"); command.logRenamedEntity(); Mockito.when(command.getEntityOldName()).thenReturn("foo"); Mockito.when(command.getEntityNewName()).thenReturn(null); command.logRenamedEntity(); }</code><technical_language>consider declaring mockito package static imports commonly tests</technical_language>

Target:
public void logRenamedEntity() { abstract class RenameCommand extends CommandBaseDummy implements RenamedEntityInfoProvider { private static final long serialVersionUID = 1L; protected RenameCommand(VdcActionParametersBase params) { super(params); } } RenameCommand command = mock(RenameCommand.class); when(command.getEntityOldName()).thenReturn(null); when(command.getEntityNewName()).thenReturn(null); doCallRealMethod().when(command).logRenamedEntity(); command.logRenamedEntity(); when(command.getEntityOldName()).thenReturn("foo"); when(command.getEntityNewName()).thenReturn("bar"); command.logRenamedEntity(); when(command.getEntityOldName()).thenReturn(null); when(command.getEntityNewName()).thenReturn("bar"); command.logRenamedEntity(); when(command.getEntityOldName()).thenReturn("foo"); when(command.getEntityNewName()).thenReturn(null); command.logRenamedEntity(); }
Source:
<code>public VideoInfo getPreferredVideoInfo() { if (mobileLow != null && URLUtil.isNetworkUrl(mobileLow.url) && VideoUtil.isValidVideoUrl(mobileLow.url)) { return mobileLow; } if (mobileHigh != null && URLUtil.isNetworkUrl(mobileHigh.url) && VideoUtil.isValidVideoUrl(mobileHigh.url)) { return mobileHigh; } <START> if (fallback != null && URLUtil.isNetworkUrl(fallback.url)) { <END> final boolean isUsingVideoPipeline = new Config(MainApplication.instance()).isUsingVideoPipeline(); if (isUsingVideoPipeline && VideoUtil.isM3U8FormatVideo(fallback.url)) { return fallback; } if (!isUsingVideoPipeline && VideoUtil.isValidVideoUrl(fallback.url)) { return fallback; } } return null; }</code><technical_language>3 if statements verifying essentially things, refactor checks a separate private function</technical_language>

Target:
public VideoInfo getPreferredVideoInfo() { if (isPreferredVideoInfo(mobileLow)) { return mobileLow; } if (isPreferredVideoInfo(mobileHigh)) { return mobileHigh; } if (new Config(MainApplication.instance()).isUsingVideoPipeline()) { if (fallback != null && URLUtil.isNetworkUrl(fallback.url) && VideoUtil.isSupportedVideoFormat(fallback.url, AppConstants.VIDEO_FORMAT_M3U8)) { return fallback; } } else { if (isPreferredVideoInfo(fallback)) { return fallback; } } return null; }
Source:
<code>private void publishPost() { if (!isFinishing() && NetworkUtils.checkConnection(this)) { if (!mPost.isLocalDraft()) { Map<String, Object> properties = new HashMap<>(); Configuration configuration = WordPress.getContext().getResources().getConfiguration(); <START> properties.put("hardware_keyboard", configuration.keyboard != Configuration.KEYBOARD_NOKEYS); <END> AnalyticsUtils.trackWithBlogDetails( AnalyticsTracker.Stat.EDITOR_UPDATED_POST, WordPress.getBlog(mPost.getLocalTableBlogId()), properties ); } if (mPost.getStatusEnum() == PostStatus.DRAFT) { mPost.setPostStatus(PostStatus.toString(PostStatus.PUBLISHED)); } PostUploadService.addPostToUpload(mPost); startService(new Intent(this, PostUploadService.class)); } }</code><technical_language>hardware_keyboard metadata I necessary add properties events</technical_language>

Target:
private void publishPost() { if (!isFinishing() && NetworkUtils.checkConnection(this)) { if (!mPost.isLocalDraft()) { AnalyticsUtils.trackWithBlogDetails( AnalyticsTracker.Stat.EDITOR_UPDATED_POST, WordPress.getBlog(mPost.getLocalTableBlogId()) ); } if (mPost.getStatusEnum() == PostStatus.DRAFT) { mPost.setPostStatus(PostStatus.toString(PostStatus.PUBLISHED)); } PostUploadService.addPostToUpload(mPost); startService(new Intent(this, PostUploadService.class)); } }
Source:
<code>public void testScheduleRequestParameters() { String param_key = "param_key"; String param_value = "param_value"; Date dueOnDate = new Date(); doAnswer(new Answer() { @Override public Void answer(InvocationOnMock invocationOnMock) throws Throwable { assertTrue(invocationOnMock.getArguments()[0].equals(serverTemplateId)); assertTrue(invocationOnMock.getArguments()[1].equals(JOB_TYPE)); assertTrue(invocationOnMock.getArguments()[2].equals(dueOnDate)); final HashMap<String, String> ctxValues = (HashMap) invocationOnMock.getArguments()[3]; assertTrue(ctxValues.get(RequestDataSetConstants.COLUMN_BUSINESSKEY).equals(JOB_NAME)); assertTrue(ctxValues.get(RequestDataSetConstants.COLUMN_RETRIES).equals(String.valueOf(JOB_RETRIES))); assertTrue(ctxValues.get(param_key).equals(String.valueOf(param_value))); return null; } }).when(executorServicesMock).scheduleRequest(anyString(), anyString(), <START> any(Date.class), <END> any(Map.class)); presenter.createJob(JOB_NAME, dueOnDate, JOB_TYPE, JOB_RETRIES, Arrays.asList(new RequestParameterSummary(param_key, param_value))); verify(executorServicesMock).scheduleRequest(anyString(), anyString(), any(Date.class), any(HashMap.class)); }</code><technical_language>arguments correct now, main problem is there. Assertions in answer(...) method work. Try replace assertTrue(invocationOnMock.getArguments()[0].equals(serverTemplateId)); assertTrue(invocationOnMock.getArguments()[0].equals("Fail test")); test pass. Furthermore, code in answer(...) method assert statement is executed all. I exact reason for this behavior, Mockito internals obviously, hunch is do _doAnswer()_ for stubbing a non-void method</technical_language>

Target:
public void testScheduleRequestParameters() { String param_key = "param_key"; String param_value = "param_value"; Date dueOnDate = new Date(); final SoftAssertions softly = new SoftAssertions(); doAnswer(new Answer() { @Override public Void answer(InvocationOnMock invocationOnMock) throws Throwable { softly.assertThat(invocationOnMock.getArguments()[0]).isEqualTo(serverTemplateId); softly.assertThat(invocationOnMock.getArguments()[1]).isEqualTo(JOB_TYPE); softly.assertThat(invocationOnMock.getArguments()[2]).isEqualTo(dueOnDate); final HashMap<String, String> ctxValues = (HashMap) invocationOnMock.getArguments()[3]; softly.assertThat(ctxValues.get(RequestDataSetConstants.COLUMN_BUSINESSKEY).equals(JOB_NAME)); softly.assertThat(ctxValues.get(RequestDataSetConstants.COLUMN_RETRIES).equals(String.valueOf(JOB_RETRIES))); softly.assertThat(ctxValues.get(param_key).equals(String.valueOf(param_value))); return null; } }).when(executorServicesMock).scheduleRequest(anyString(), anyString(), any(Date.class), any(Map.class)); presenter.createJob(JOB_NAME, dueOnDate, JOB_TYPE, JOB_RETRIES, Arrays.asList(new RequestParameterSummary(param_key, param_value))); softly.assertAll(); verify(executorServicesMock).scheduleRequest(anyString(), anyString(), any(Date.class), any(HashMap.class)); }
Source:
<code>public void recreateIndex() { deleteIndex(); final Client client = this.getClient(); final InputStream mappings = Thread.currentThread().getContextClassLoader().getResourceAsStream("mappings.json"); final InputStream index_settings = Thread.currentThread().getContextClassLoader().getResourceAsStream("index_settings.json"); try { <START> String mappingsString = IOUtils.toString(mappings); <END> JSONObject mappingsJSON = new JSONObject(mappingsString); mappingsJSON = addLangsToMapping(mappingsJSON); client.admin().indices().prepareCreate("photon").setSettings(IOUtils.toString(index_settings)).execute().actionGet(); client.admin().indices().preparePutMapping("photon").setType("place").setSource(mappingsJSON.toString()).execute().actionGet(); } catch(IOException e) { log.error("cannot setup index, elastic search config files not readable", e); } }</code><technical_language>I generally prefer in try block line raise</technical_language>

Target:
public void recreateIndex() throws IOException { deleteIndex(); final Client client = this.getClient(); final InputStream mappings = Thread.currentThread().getContextClassLoader().getResourceAsStream("mappings.json"); final InputStream index_settings = Thread.currentThread().getContextClassLoader().getResourceAsStream("index_settings.json"); String mappingsString = IOUtils.toString(mappings); JSONObject mappingsJSON = new JSONObject(mappingsString); mappingsJSON = addLangsToMapping(mappingsJSON); client.admin().indices().prepareCreate("photon").setSettings(IOUtils.toString(index_settings)).execute().actionGet(); client.admin().indices().preparePutMapping("photon").setType("place").setSource(mappingsJSON.toString()).execute().actionGet(); }
Source:
<code>@Override public Pair<RelTraitSet, List<RelTraitSet>> deriveTraits( final RelTraitSet childTraits, final int childId) { assert childId == 0; RelCollation collation = childTraits.getCollation(); if (collation == null || collation == RelCollations.EMPTY || joinType == JoinRelType.FULL || joinType == JoinRelType.RIGHT) { return null; } return Pair.of( getTraitSet().replace(collation), <START> ImmutableList.of(childTraits, right.getTraitSet())); <END> }</code><technical_language>need replace childTraits enumerable convention. hashjoin</technical_language>

Target:
@Override public Pair<RelTraitSet, List<RelTraitSet>> deriveTraits( final RelTraitSet childTraits, final int childId) { assert childId == 0; RelCollation collation = childTraits.getCollation(); if (collation == null || collation == RelCollations.EMPTY) { return null; } RelTraitSet derivedTraits = getTraitSet().replace(collation); return Pair.of( derivedTraits, ImmutableList.of(derivedTraits, right.getTraitSet())); }
Source:
<code>private Set<SignatureAlgorithm> fetchSignatureVerificationAlgorithms(List<JWK> jwks) { if (jwks == null) { return Collections.emptySet(); } <START> return jwks.stream().map(jwk -> { <END> Algorithm algorithm = jwk.getAlgorithm(); if (algorithm != null) { return SignatureAlgorithm.from(algorithm.getName()); } return null; }).filter(Objects::nonNull).collect(Collectors.toSet()); }</code><technical_language>Stream API is a bit slow hard garbage collector in Spring Security - please change this a for loop</technical_language>

Target:
private Set<SignatureAlgorithm> fetchSignatureVerificationAlgorithms(List<JWK> jwks) { if (jwks == null) { return Collections.emptySet(); } Set<SignatureAlgorithm> algorithms = new HashSet<>(); for (JWK jwk : jwks) { Algorithm algorithm = jwk.getAlgorithm(); if (algorithm != null) { SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.from(algorithm.getName()); if (signatureAlgorithm != null) { algorithms.add(signatureAlgorithm); } } } return algorithms; }
Source:
<code>public void init() throws IdentityOAuth2Exception { super.init(); Thread thread = Thread.currentThread(); ClassLoader loader = thread.getContextClassLoader(); thread.setContextClassLoader(this.getClass().getClassLoader()); try { DefaultBootstrap.bootstrap(); } catch (ConfigurationException e) { <START> log.error(e); <END> throw new IdentityOAuth2Exception("Error in bootstrapping the OpenSAML2 library"); } finally { thread.setContextClassLoader(loader); } profileValidator = new SAMLSignatureProfileValidator(); }</code><technical_language>add a message</technical_language>

Target:
public void init() throws IdentityOAuth2Exception { super.init(); Thread thread = Thread.currentThread(); ClassLoader loader = thread.getContextClassLoader(); thread.setContextClassLoader(this.getClass().getClassLoader()); try { DefaultBootstrap.bootstrap(); } catch (ConfigurationException e) { log.error("Error in bootstrapping the OpenSAML2 library", e); throw new IdentityOAuth2Exception("Error in bootstrapping the OpenSAML2 library"); } finally { thread.setContextClassLoader(loader); } profileValidator = new SAMLSignatureProfileValidator(); }
Source:
<code>public boolean equals(Object o) { <START> if (!(o instanceof CustomMethods)) { <END> return false; } CustomMethods other = (CustomMethods) o; return other.name.equals(name); }</code><technical_language>checking for equal identity - passed object null</technical_language>

Target:
public boolean equals(Object o) { if (this == o) return true; if (o == null || !(o instanceof CustomMethods)) return false; CustomMethods that = (CustomMethods) o; return name != null ? name.equals(that.name) : that.name == null; }
Source:
<code>public void configure() { super.configure(); final HTTPClientPolicy httpClientPolicy = getHTTPClientPolicy(); final BindingProvider bindingProvider = (BindingProvider) getPort(); httpClientPolicy.setConnection(null); if (hasKeepAliveForConnection()) { httpClientPolicy.setConnection(ConnectionType.KEEP_ALIVE); } bindingProvider.getRequestContext().remove(NhincConstants.CUSTOM_HTTP_HEADERS); HashMap<String, String> httpHeaders = getCustomHeaders(); <START> if (httpHeaders != null && !httpHeaders.isEmpty()) { <END> bindingProvider.getRequestContext().put(NhincConstants.CUSTOM_HTTP_HEADERS, httpHeaders); } }</code><technical_language>MapUtil check for empty</technical_language>

Target:
public void configure() { super.configure(); final HTTPClientPolicy httpClientPolicy = getHTTPClientPolicy(); final BindingProvider bindingProvider = (BindingProvider) getPort(); httpClientPolicy.setConnection(null); if (hasKeepAliveForConnection()) { httpClientPolicy.setConnection(ConnectionType.KEEP_ALIVE); } bindingProvider.getRequestContext().remove(NhincConstants.CUSTOM_HTTP_HEADERS); HashMap<String, String> httpHeaders = getCustomHeaders(); if (MapUtils.isNotEmpty(httpHeaders)) { bindingProvider.getRequestContext().put(NhincConstants.CUSTOM_HTTP_HEADERS, httpHeaders); } }
Source:
<code>private LauncherDiscoveryListener getLauncherDiscoveryListener(ConfigurationParameters configurationParameters) { LauncherDiscoveryListener defaultDiscoveryListener = configurationParameters.get( DEFAULT_DISCOVERY_LISTENER_CONFIGURATION_PROPERTY_NAME) .map(value -> LauncherDiscoveryListeners.fromConfigurationParameter( <START> DEFAULT_DISCOVERY_LISTENER_CONFIGURATION_PROPERTY_NAME, value)) .orElseGet(LauncherDiscoveryListeners::abortOnFailure); List<LauncherDiscoveryListener> serviceLoaderListeners = configurationParameters.getBoolean( DISCOVERY_LISTENERS_AUTODETECTION_ENABLED_PROPERTY_NAME).filter(p -> p).map( p -> StreamSupport.stream( new ServiceLoaderLauncherDiscoveryListenerRegistry().loadListeners().spliterator(), false).collect( Collectors.<LauncherDiscoveryListener> toList())).orElse(Collections.emptyList()); if (discoveryListeners.isEmpty() && serviceLoaderListeners.isEmpty()) { return defaultDiscoveryListener; } if (discoveryListeners.contains(defaultDiscoveryListener) && serviceLoaderListeners.isEmpty()) { return LauncherDiscoveryListeners.composite(discoveryListeners); } List<LauncherDiscoveryListener> allDiscoveryListeners = new ArrayList<>(discoveryListeners); allDiscoveryListeners.addAll(serviceLoaderListeners); if (!allDiscoveryListeners.contains(defaultDiscoveryListener)) { allDiscoveryListeners.add(defaultDiscoveryListener); } return LauncherDiscoveryListeners.composite(allDiscoveryListeners); <END> }</code><technical_language>I this optimization is necessary. get rid of if</technical_language>

Target:
private LauncherDiscoveryListener getLauncherDiscoveryListener(ConfigurationParameters configurationParameters) { LauncherDiscoveryListener defaultDiscoveryListener = configurationParameters.get( DEFAULT_DISCOVERY_LISTENER_CONFIGURATION_PROPERTY_NAME) .map(value -> LauncherDiscoveryListeners.fromConfigurationParameter( DEFAULT_DISCOVERY_LISTENER_CONFIGURATION_PROPERTY_NAME, value)) .orElseGet(LauncherDiscoveryListeners::abortOnFailure); if (discoveryListeners.isEmpty()) { return defaultDiscoveryListener; } if (discoveryListeners.contains(defaultDiscoveryListener)) { return LauncherDiscoveryListeners.composite(discoveryListeners); } List<LauncherDiscoveryListener> allDiscoveryListeners = new ArrayList<>(discoveryListeners.size() + 1); allDiscoveryListeners.addAll(discoveryListeners); allDiscoveryListeners.add(defaultDiscoveryListener); return LauncherDiscoveryListeners.composite(allDiscoveryListeners); }