auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private static void requestsCheck(SubscriptionContext subscriptionContext) { CallExpression callExpr = (CallExpression) subscriptionContext.syntaxNode(); boolean isVulnerableMethod = ofNullable(callExpr.calleeSymbol()) .map(Symbol::fullyQualifiedName) .filter(requestsMethods::contains) .isPresent(); if (isVulnerableMethod) { Optional<Expression> verifyRhs = searchVerifyAssignment(callExpr) .map(Optional::of) .orElseGet(() -> searchVerifyInKwargs(callExpr)); verifyRhs.ifPresent(rhs -> { if (Expressions.isFalsy(rhs) || isFalsyCollection(rhs)) { subscriptionContext.addIssue( <START> rhs.firstToken(), <END> rhs.lastToken(), "Disabling certificate verification is dangerous."); } }); } }</code><technical_language>I pass tree in this case (i.e. rhs)</technical_language>

Target:
private static void requestsCheck(SubscriptionContext subscriptionContext) { CallExpression callExpr = (CallExpression) subscriptionContext.syntaxNode(); boolean isVulnerableMethod = ofNullable(callExpr.calleeSymbol()) .map(Symbol::fullyQualifiedName) .filter(requestsMethods::contains) .isPresent(); if (isVulnerableMethod) { Optional<List<Expression>> verifyRhs = searchVerifyAssignment(callExpr) .map(Optional::of) .orElseGet(() -> searchVerifyInKwargs(callExpr)); verifyRhs.ifPresent(sensitiveSettingExpressions -> { Expression rhs = sensitiveSettingExpressions.get(sensitiveSettingExpressions.size() - 1); if (Expressions.isFalsy(rhs) || isFalsyCollection(rhs)) { PreciseIssue issue = subscriptionContext.addIssue(rhs, "Disabling certificate verification is dangerous."); for (int i = 0; i < sensitiveSettingExpressions.size() - 1; i++) { issue.secondary(sensitiveSettingExpressions.get(i), "Dictionary is passed here as **kwargs."); } } }); } }
Source:
<code>private void handleScanTimeout(ScanTimeoutException rte) throws IOException { try { currentDelegate.close(); } catch (IOException ioe) { logger.warn("Error closing scanner before reissuing request: ", ioe); } logger.info("The client could not get a response in %d ms. Retrying the scan.", retryOptions.getReadPartialRowTimeoutMillis()); if (timeoutRetryCount == null) { timeoutRetryCount = new AtomicInteger(); } currentErrorBackoff = null; if (timeoutRetryCount.incrementAndGet() <= retryOptions.getMaxScanTimeoutRetries()) { reissueRequest(); } else { <START> rpcMetrics.incrementFailureCount(); <END> throw new BigtableRetriesExhaustedException( "Exhausted streaming retries after too many timeouts", rte); } }</code><technical_language>interesting distinguish unretryable errors retries exhausted..</technical_language>

Target:
private void handleScanTimeout(ScanTimeoutException rte) throws IOException { try { currentDelegate.close(); } catch (IOException ioe) { logger.warn("Error closing scanner before reissuing request: ", ioe); } logger.info("The client could not get a response in %d ms. Retrying the scan.", retryOptions.getReadPartialRowTimeoutMillis()); currentErrorBackoff = null; if (timeoutRetryCount == null) { timeoutRetryCount = new AtomicInteger(); } if (timeoutRetryCount.incrementAndGet() <= retryOptions.getMaxScanTimeoutRetries()) { reissueRequest(); } else { rpcMetrics.incrementRetriesExhastedCounter(); throw new BigtableRetriesExhaustedException( "Exhausted streaming retries after too many timeouts", rte); } }
Source:
<code>public ClientOptions setHeaders(Iterable<Header> headers) { <START> this.headers = Objects.requireNonNull(headers, "'headers' cannot be null."); <END> return this; }</code><technical_language>do prevent null getter return empty list null</technical_language>

Target:
public ClientOptions setHeaders(Iterable<Header> headers) { this.headers = headers; return this; }
Source:
<code>protected void reconnect(Watcher watcher) throws InterruptedException { _zookeeperLock.lock(); try { if (_zk == null) { throw new IllegalStateException("zk client has not been connected or already been closed"); } ZooKeeper prevZk = _zk; try { LOG.debug("Creating new ZookKeeper instance to reconnect to " + _servers + "."); _zk = new ZooKeeper(_servers, _sessionTimeOut, watcher); prevZk.close(); <START> _getChildrenMethod = null; <END> } catch (IOException e) { throw new ZkException("Unable to connect to " + _servers, e); } } finally { _zookeeperLock.unlock(); } }</code><technical_language>if this some race condition issues? For example, reconnect() cleans method here. in other application thread, operation is this object (with reference), NPE</technical_language>

Target:
protected void reconnect(Watcher watcher) throws InterruptedException { _zookeeperLock.lock(); try { if (_zk == null) { throw new IllegalStateException("zk client has not been connected or already been closed"); } ZooKeeper prevZk = _zk; try { LOG.debug("Creating new ZookKeeper instance to reconnect to " + _servers + "."); _zk = new ZooKeeper(_servers, _sessionTimeOut, watcher); prevZk.close(); } catch (IOException e) { throw new ZkException("Unable to connect to " + _servers, e); } } finally { _zookeeperLock.unlock(); } }
Source:
<code>public Default() { <START> this.processor = new MarkdownTxtmark(); <END> }</code><technical_language>@dmzaytsev MarkdownPegdown this change</technical_language>

Target:
public Default() { this.processor = new MarkdownPegdown(); }
Source:
<code>public static void withinEntityManager(EntityManagerFactory emf, Consumer<FullTextEntityManager> consumer) { EntityManager entityManager = emf.createEntityManager(); try { FullTextEntityManager fem = Search.getFullTextEntityManager( entityManager ); consumer.accept( fem ); } finally { entityManager.close(); <START> } <END> }</code><technical_language>I handle exceptions more caution. Instead of finally, this be: catch (Throwable t1) { try { entityManager.close(); } catch(Throwable t2) { someLogger.warn("Error while automatically closing entity manager", e); // remove t1.addSuppressed(t2); } throw t1; } entityManager.close(); // exception closing propagate, catch exception</technical_language>

Target:
public static void withinEntityManager(EntityManagerFactory emf, Consumer<FullTextEntityManager> consumer) { EntityManager entityManager = emf.createEntityManager(); try { FullTextEntityManager fem = Search.getFullTextEntityManager( entityManager ); consumer.accept( fem ); } catch (Throwable mainError) { try { entityManager.close(); } catch (Throwable errorOnClose) { mainError.addSuppressed( errorOnClose ); } throw mainError; } entityManager.close(); }
Source:
<code>private Map<String, TemplateProp> listTemplate(DataStore ssStore) { String nfsVersionParam = imageStoreDetailsUtil.getNfsVersion(ssStore.getId()); <START> Integer nfsVersion = (nfsVersionParam != null ? Integer.valueOf(nfsVersionParam) : null); <END> ListTemplateCommand cmd = new ListTemplateCommand(ssStore.getTO(), nfsVersion); EndPoint ep = _epSelector.select(ssStore); Answer answer = null; if (ep == null) { String errMsg = "No remote endpoint to send command, check if host or ssvm is down?"; s_logger.error(errMsg); answer = new Answer(cmd, false, errMsg); } else { answer = ep.sendMessage(cmd); } if (answer != null && answer.getResult()) { ListTemplateAnswer tanswer = (ListTemplateAnswer)answer; return tanswer.getTemplateInfo(); } else { if (s_logger.isDebugEnabled()) { s_logger.debug("can not list template for secondary storage host " + ssStore.getId()); } } return null; }</code><technical_language>Please move nfs version conversion string int a separate method, pattern multiple places</technical_language>

Target:
private Map<String, TemplateProp> listTemplate(DataStore ssStore) { Integer nfsVersion = imageStoreDetailsUtil.getNfsVersion(ssStore.getId()); ListTemplateCommand cmd = new ListTemplateCommand(ssStore.getTO(), nfsVersion); EndPoint ep = _epSelector.select(ssStore); Answer answer = null; if (ep == null) { String errMsg = "No remote endpoint to send command, check if host or ssvm is down?"; s_logger.error(errMsg); answer = new Answer(cmd, false, errMsg); } else { answer = ep.sendMessage(cmd); } if (answer != null && answer.getResult()) { ListTemplateAnswer tanswer = (ListTemplateAnswer)answer; return tanswer.getTemplateInfo(); } else { if (s_logger.isDebugEnabled()) { s_logger.debug("can not list template for secondary storage host " + ssStore.getId()); } } return null; }
Source:
<code>public static void configure( final Environment environment, Configuration config, String tracerName, Stacktraces stacktracePropagation) { Brave brave = DropwizardTracingFilters.registerTracers(environment, config, tracerName); <START> environment.jersey().register(brave); <END> ExceptionMappers.visitExceptionMappers( stacktracePropagation == Stacktraces.PROPAGATE, new ExceptionMappers.Consumer<ExceptionMapper<? extends Throwable>>() { @Override public void accept(ExceptionMapper<? extends Throwable> mapper) { environment.jersey().register(mapper); } }); environment.jersey().register(new OptionalAsNoContentMessageBodyWriter()); }</code><technical_language>wow, this mean</technical_language>

Target:
public static void configure( final Environment environment, Configuration config, String tracerName, Stacktraces stacktracePropagation) { DropwizardTracingFilters.registerTracers(environment, config, tracerName); ExceptionMappers.visitExceptionMappers( stacktracePropagation == Stacktraces.PROPAGATE, new ExceptionMappers.Consumer<ExceptionMapper<? extends Throwable>>() { @Override public void accept(ExceptionMapper<? extends Throwable> mapper) { environment.jersey().register(mapper); } }); environment.jersey().register(new OptionalAsNoContentMessageBodyWriter()); }
Source:
<code>public boolean isBeforeCurrent() { System.out.println("createdAt = " + createdAt); <START> System.out.println("question.getInformation().getCreatedAt() = " + question.getInformation().getCreatedAt()); <END> return createdAt.isBefore(question.getInformation().getCreatedAt()); }</code><technical_language>System.out.println anywhere. If need log something, log4j</technical_language>

Target:
public boolean isBeforeCurrent() { return createdAt.isBefore(question.getInformation().getCreatedAt()); }
Source:
<code>private void authenticateUser(HttpSession session, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { boolean basicAuth = false; try { if (StringUtils.isNotEmpty(request.getParameter(BASIC_AUTH))) { <START> basicAuth = Boolean.parseBoolean(request.getParameter(BASIC_AUTH)); <END> } if (basicAuth && StringUtils.isEmpty(request.getHeader(HEADER_AUTHORIZATION))) { throw new AuthenticationException("Unauthorized"); } if (!containsUserCredentials(basicAuth, request)) { throw new AuthenticationException("Credentials Required"); } try { Credentials userCredentials = getUserCredentials(basicAuth, request); AuthenticationUtils.handleCredentials( session, userCredentials.username, userCredentials.password, userCredentials.profile); request.getRequestDispatcher("/sso-redirect").forward(request, response); } catch (SQLException ex) { log.error("Internal Database Error", ex); throw new AuthenticationException("Internal Database Error", ex); } } catch (AuthenticationException ex) { if (basicAuth) { request.getRequestDispatcher("/basic").forward(request, response); } else { request.getRequestDispatcher("/WEB-INF/login.jsp?msg=" + ex.getMessage()).forward(request, response); } } }</code><technical_language>this in servlet init parameter, is part of application configuration</technical_language>

Target:
private void authenticateUser(HttpSession session, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { boolean needsBasicAuthHandling = enableBasicAuth && !containsUserCredentialsInParams(request.getParameterMap()); try { Credentials userCredentials = getUserCredentials(request); if (userCredentials == null) { throw new AuthenticationException("Credentials Required"); } try { AuthenticationUtils.handleCredentials( session, userCredentials.getUsername(), userCredentials.getPassword(), userCredentials.getProfile()); request.getRequestDispatcher("/sso-redirect").forward(request, response); } catch (SQLException ex) { log.error("Internal Database Error", ex); throw new AuthenticationException("Internal Database Error", ex); } } catch (AuthenticationException ex) { if (needsBasicAuthHandling) { response.sendRedirect(request.getContextPath() + "/basic?" + request.getQueryString()); } else { request.getRequestDispatcher("/WEB-INF/login.jsp?msg=" + ex.getMessage()).forward(request, response); } } }
Source:
<code>public ITmfStateValue increment() throws StateValueTypeException { <START> return TmfStateValue.newValueLong(this.unboxLong() + 1); <END> }</code><technical_language>this.unboxLong()</technical_language>

Target:
public ITmfStateValue increment() throws StateValueTypeException { return TmfStateValue.newValueLong(valueLong + 1); }
Source:
<code>public void testValidCondition() throws Exception { final String query = "structuretype = 1"; <START> final String s = SQLUtil.sanitizeParameter( query ); <END> assertNotNull(s); assertEquals(query, s); }</code><technical_language>this call SQLUtil. sanitizeCondition instead</technical_language>

Target:
public void testValidCondition() throws Exception { final String query = "structuretype = 1"; final String s = SQLUtil.sanitizeCondition( query ); assertNotNull(s); assertEquals(query, s); }
Source:
<code>public void enqueue(Lifespan lifespan, List<SerializedPage> pages) { checkState(partitions.size() == 1, "Expected exactly one partition"); <START> checkState(lifespanCompletionCallback != null, "lifespanCompletionCallback has to be set before starting enqueue data"); <END> enqueue(lifespan, 0, pages); }</code><technical_language>This check is extra</technical_language>

Target:
public void enqueue(Lifespan lifespan, List<SerializedPage> pages) { checkState(partitions.size() == 1, "Expected exactly one partition"); enqueue(lifespan, 0, pages); }
Source:
<code>private Request makeRequest(@Nonnull String type, @Nonnull String sparql, @Nullable String accept) { Request post = httpClient.newRequest(uri); post.method(POST); if <START> (!(timeout.isNegative() || <END> timeout.isZero())) { post.timeout(timeout.toMillis(), MILLISECONDS); } if (accept != null) { post.header("Accept", accept); } final Fields fields = new Fields(); fields.add(type, sparql); final FormContentProvider form = new FormContentProvider(fields, UTF_8); post.content(form); return post; }</code><technical_language>sounds fine me</technical_language>

Target:
private Request makeRequest(@Nonnull String type, @Nonnull String sparql, @Nullable String accept) { Request post = httpClient.newRequest(uri); post.method(POST); if (!timeout.isNegative()) { post.timeout(timeout.toMillis(), MILLISECONDS); } if (accept != null) { post.header("Accept", accept); } final Fields fields = new Fields(); fields.add(type, sparql); final FormContentProvider form = new FormContentProvider(fields, UTF_8); post.content(form); return post; }
Source:
<code>private boolean validatePerson(GluuCustomPerson person) throws Exception { GluuCustomPerson gluuCustomPerson = personService.getPersonByUid(person.getUid()); if (gluuCustomPerson != null){ <START> if(!update){ <END> facesMessages.add(FacesMessage.SEVERITY_ERROR, "Add User failed. Uid already exist: %s", gluuCustomPerson.getUid()); }else{ facesMessages.add(FacesMessage.SEVERITY_ERROR, "Update User failed. Uid already exist: %s", gluuCustomPerson.getUid()); } return false; } gluuCustomPerson = personService.getPersonByEmail(person.getMail()); if (gluuCustomPerson != null){ if(!update){ facesMessages.add(FacesMessage.SEVERITY_ERROR, "Add User failed. Mail id already exist: %s", gluuCustomPerson.getMail()); }else{ facesMessages.add(FacesMessage.SEVERITY_ERROR, "Update User failed. Mail id already exist: %s", gluuCustomPerson.getMail()); } return false; } return true; }</code><technical_language>move messages UpdatePersonAction.java message resources file</technical_language>

Target:
private boolean validatePerson(GluuCustomPerson person) throws Exception { List<GluuCustomPerson> gluuCustomPersons = personService.getPersonsByUid(person.getUid()); if (gluuCustomPersons != null){ if(!update){ facesMessages.add(FacesMessage.SEVERITY_ERROR, "#{msg['UpdatePersonAction.faileAddUserUidExist']} %s", person.getUid()); return false; }else{ if(gluuCustomPersons.size()>0){ for(GluuCustomPerson gluuCustomPerson : gluuCustomPersons){ if(!gluuCustomPerson.getInum().trim().equals(person.getInum())){ facesMessages.add(FacesMessage.SEVERITY_ERROR, "#{msg['UpdatePersonAction.faileUpdateUserUidExist']} %s", person.getUid()); return false; } } } } } gluuCustomPersons = personService.getPersonsByEmail(person.getMail()); if (gluuCustomPersons != null){ if(!update){ facesMessages.add(FacesMessage.SEVERITY_ERROR, "#{msg['UpdatePersonAction.faileAddUserMailidExist']} %s", person.getMail()); return false; }else{ if(gluuCustomPersons.size()>0){ for(GluuCustomPerson gluuCustomPerson : gluuCustomPersons){ if(!gluuCustomPerson.getInum().trim().equals(person.getInum())){ facesMessages.add(FacesMessage.SEVERITY_ERROR, "#{msg['UpdatePersonAction.faileUpdateUserMailidExist']} %s", person.getMail()); return false; } } } } } return true; }
Source:
<code><START> public static synchronized Pair<Set<Range<Token>>, Set<Range<Token>>> getAvailableRanges(String keyspace, IPartitioner partitioner) <END> { String query = "SELECT * FROM system.%s WHERE keyspace_name=?"; UntypedResultSet rs = executeInternal(format(query, AVAILABLE_RANGES_V2), keyspace); Set<Range<Token>> full = new HashSet<>(); Set<Range<Token>> trans = new HashSet<>(); for (UntypedResultSet.Row row : rs) { Optional.ofNullable(row.getSet("full_ranges", BytesType.instance)) .ifPresent(full_ranges -> full_ranges.stream() .map(buf -> byteBufferToRange(buf, partitioner)) .forEach(full::add)); Optional.ofNullable(row.getSet("transient_ranges", BytesType.instance)) .ifPresent(transient_ranges -> transient_ranges.stream() .map(buf -> byteBufferToRange(buf, partitioner)) .forEach(trans::add)); } return Pair.create(full, trans); }</code><technical_language>introduce a concrete class for this concept, of full/transient ranges</technical_language>

Target:
public static synchronized AvailableRanges getAvailableRanges(String keyspace, IPartitioner partitioner) { String query = "SELECT * FROM system.%s WHERE keyspace_name=?"; UntypedResultSet rs = executeInternal(format(query, AVAILABLE_RANGES_V2), keyspace); ImmutableSet.Builder<Range<Token>> full = new ImmutableSet.Builder<>(); ImmutableSet.Builder<Range<Token>> trans = new ImmutableSet.Builder<>(); for (UntypedResultSet.Row row : rs) { Optional.ofNullable(row.getSet("full_ranges", BytesType.instance)) .ifPresent(full_ranges -> full_ranges.stream() .map(buf -> byteBufferToRange(buf, partitioner)) .forEach(full::add)); Optional.ofNullable(row.getSet("transient_ranges", BytesType.instance)) .ifPresent(transient_ranges -> transient_ranges.stream() .map(buf -> byteBufferToRange(buf, partitioner)) .forEach(trans::add)); } return new AvailableRanges(full.build(), trans.build()); }
Source:
<code>private static void handleCounterAspect(ITmfEvent event, ITmfStateSystemBuilder ss, CounterAspect aspect, int rootQuark) { String[] groupIds = aspect.getGroupIds(); int quark = (groupIds.length > 0) ? ss.getQuarkRelativeAndAdd(rootQuark, groupIds) : rootQuark; quark = ss.getQuarkRelativeAndAdd(quark, aspect.getName()); Long eventContent = aspect.resolve(event); ss.modifyAttribute(event.getTimestamp().toNanos(), <START> eventContent == null ? null : eventContent, quark); <END> }</code><technical_language>eventContent, if null null</technical_language>

Target:
private static void handleCounterAspect(ITmfEvent event, ITmfStateSystemBuilder ss, CounterAspect aspect, int rootQuark) { String[] groupIds = aspect.getGroupIds(); int quark = (groupIds.length > 0) ? ss.getQuarkRelativeAndAdd(rootQuark, groupIds) : rootQuark; quark = ss.getQuarkRelativeAndAdd(quark, aspect.getName()); Long eventContent = aspect.resolve(event); ss.modifyAttribute(event.getTimestamp().toNanos(), eventContent, quark); }
Source:
<code>public void close() { workPlanOrchestrator.close(); <START> streamOrchestrator.close(); <END> }</code><technical_language>If orchestrator throws exception closing, get closed. Please a closer instead; org.hibernate.search.backend.elasticsearch.impl.ElasticsearchBackendImpl#close for example</technical_language>

Target:
public void close() { try ( Closer<IOException> closer = new Closer<>() ) { closer.push( ElasticsearchWorkOrchestrator::close, workPlanOrchestrator ); closer.push( ElasticsearchWorkOrchestrator::close, streamOrchestrator ); } catch (IOException e) { throw log.failedToShutdownIndexManager( hibernateSearchIndexName, e, indexingBackendContext.getEventContext() ); } }
Source:
<code>void writeMetadata(BinaryMetadata binMeta) { if (!CU.isPersistenceEnabled(ctx.config())) return; try { File file = new File(workDir, binMeta.typeId() + ".bin"); byte[] marshalled = U.marshal(ctx, binMeta); if (ctx.config() != null && ctx.config().getDataStorageConfiguration() != null && ctx.config().getDataStorageConfiguration().getFileIOFactory() != null) { try (final FileIO out = ctx.config().getDataStorageConfiguration().getFileIOFactory().create(file)) { out.write(marshalled, 0, marshalled.length); } } <START> else { <END> try (FileOutputStream out = new FileOutputStream(file, false)) { out.write(marshalled); } } } catch (Exception e) { U.error(log, "Failed to save metadata for typeId: " + binMeta.typeId() + "; exception was thrown: " + e.getMessage()); ctx.failure().process(new FailureContext(FailureType.CRITICAL_ERROR, e)); } }</code><technical_language>i suppose "else" branching needs</technical_language>

Target:
void writeMetadata(BinaryMetadata binMeta) { if (!CU.isPersistenceEnabled(ctx.config())) return; try { File file = new File(workDir, binMeta.typeId() + ".bin"); byte[] marshalled = U.marshal(ctx, binMeta); try (final FileIO out = fileIOFactory.create(file)) { int left = marshalled.length; while ((left -= out.writeFully(marshalled, 0, Math.min(marshalled.length, left))) > 0) ; out.force(); } } catch (Exception e) { final String msg = "Failed to save metadata for typeId: " + binMeta.typeId() + "; exception was thrown: " + e.getMessage(); U.error(log, msg); ctx.failure().process(new FailureContext(FailureType.CRITICAL_ERROR, e)); throw new IgniteException(msg, e); } }
Source:
<code>public GitUser getUser() throws GitException { User user = EnvironmentContext.getCurrent().getUser(); GitUser gitUser = newDto(GitUser.class); if (user.isTemporary()) { gitUser.setEmail("anonymous@noemail.com"); gitUser.setName("Anonymous"); } else { String name = null; String email = null; try { Map<String, String> preferences = preferenceDao.getPreferences(EnvironmentContext.getCurrent().getUser().getId(), "git.committer.\\w+"); name = preferences.get("git.committer.name"); email = preferences.get("git.committer.email"); } catch (ServerException ignored) { <START> LOG.error(ignored.getLocalizedMessage(), ignored); <END> } gitUser.setName(isNullOrEmpty(name) ? "Anonymous" : name); gitUser.setEmail(isNullOrEmpty(email) ? "anonymous@noemail.com" : email); } return gitUser; }</code><technical_language>is anymore :)</technical_language>

Target:
public GitUser getUser() throws GitException { User user = EnvironmentContext.getCurrent().getUser(); GitUser gitUser = newDto(GitUser.class); if (user.isTemporary()) { gitUser.setEmail("anonymous@noemail.com"); gitUser.setName("Anonymous"); } else { String name = null; String email = null; try { Map<String, String> preferences = preferenceDao.getPreferences(EnvironmentContext.getCurrent().getUser().getId(), "git.committer.\\w+"); name = preferences.get("git.committer.name"); email = preferences.get("git.committer.email"); } catch (ServerException e) { LOG.error(e.getLocalizedMessage(), e); } gitUser.setName(isNullOrEmpty(name) ? "Anonymous" : name); gitUser.setEmail(isNullOrEmpty(email) ? "anonymous@noemail.com" : email); } return gitUser; }
Source:
<code>private static ApiRoleList getRoles(RolesResourceApi rolesResourceApi, String clusterName, String serviceName) { ApiRoleList roles = null; try { if(CM_SERVICE_TYPE.equalsIgnoreCase(serviceName)) { <START> final ApiRoleList roleList = new ApiRoleList(); <END> final ApiRole cmRole = new ApiRole(); cmRole.setName(CM_ROLE_TYPE); cmRole.setType(CM_ROLE_TYPE); roleList.addItemsItem(cmRole); return roleList; } else { roles = rolesResourceApi.readRoles(clusterName, serviceName, "", VIEW_SUMMARY); } } catch (Exception e) { log.failedToAccessServiceRoleConfigs(clusterName, e); } return roles; }</code><technical_language>is ApiRoleList type local variable - roles - re-used initiated here</technical_language>

Target:
private static ApiRoleList getRoles(RolesResourceApi rolesResourceApi, String clusterName, String serviceName) { ApiRoleList roles = null; try { if(CM_SERVICE_TYPE.equalsIgnoreCase(serviceName)) { roles = new ApiRoleList(); final ApiRole cmRole = new ApiRole(); cmRole.setName(CM_ROLE_TYPE); cmRole.setType(CM_ROLE_TYPE); roles.addItemsItem(cmRole); return roles; } else { roles = rolesResourceApi.readRoles(clusterName, serviceName, "", VIEW_SUMMARY); } } catch (Exception e) { log.failedToAccessServiceRoleConfigs(clusterName, e); } return roles; }
Source:
<code>static void sortByInsertionTime(List<RemoteTaskRunnerWorkItem> tasks) { Collections.sort( <START> tasks, new Comparator<RemoteTaskRunnerWorkItem>() <END> { @Override public int compare(RemoteTaskRunnerWorkItem o1, RemoteTaskRunnerWorkItem o2) { return o1.getQueueInsertionTime().compareTo(o2.getQueueInsertionTime()); } } ); }</code><technical_language>If modifying this anyway, some kind of write this more simply Comparator.comparing</technical_language>

Target:
static void sortByInsertionTime(List<RemoteTaskRunnerWorkItem> tasks) { Collections.sort(tasks, Comparator.comparing(RemoteTaskRunnerWorkItem::getQueueInsertionTime)); }
Source:
<code>public void testEntries() throws Exception { <START> final Path p = Mockito.mock(Path.class); <END> final Stream s = Mockito.mock(Stream.class); Mockito.when(context.entries(Mockito.any(), Mockito.anyBoolean())).thenReturn(s); Assert.assertThat(context.entries(p), Matchers.sameInstance(s)); Mockito.verify(context).entries(p, true); }</code><technical_language>variable names (path, entries). assertions verifications clearer</technical_language>

Target:
public void testEntries() throws Exception { final Path path = Mockito.mock(Path.class); final Stream stream = Mockito.mock(Stream.class); Mockito.when(context.entries(Mockito.any(), Mockito.anyBoolean())).thenReturn(stream); Assert.assertThat(context.entries(path), Matchers.sameInstance(stream)); Mockito.verify(context).entries(path, true); }
Source:
<code>HelixPropertyStore<T> getHelixPropertyStore(HelixPropertyStoreConfig storeConfig, List<String> subscribedPaths) { if (storeConfig == null) { throw new IllegalArgumentException("storeConfig cannot be null"); } String storeRootPath = storeConfig.zkClientConnectString + storeConfig.rootPath; MockHelixPropertyStore<T> store = storeKeyToMockStoreMap.get(storeRootPath); if (store == null) { <START> store = new MockHelixPropertyStore<>(); <END> storeKeyToMockStoreMap.put(storeRootPath, store); } return store; }</code><technical_language>a MockHelixPropertyStore for a path</technical_language>

Target:
HelixPropertyStore<T> getHelixPropertyStore(HelixPropertyStoreConfig storeConfig, List<String> subscribedPaths) { if (storeConfig == null) { throw new IllegalArgumentException("storeConfig cannot be null"); } String storeRootPath = storeConfig.zkClientConnectString + storeConfig.rootPath; MockHelixPropertyStore<T> store = storeKeyToMockStoreMap.get(storeRootPath); if (store == null) { store = new MockHelixPropertyStore<>(shouldFailSetOperation, shouldRemoveRecordBeforeNotify); storeKeyToMockStoreMap.put(storeRootPath, store); } return store; }
Source:
<code>public static LocalDate parseDate(String date) { <START> int defaultYear = LocalDate.now(DateTimeZone.UTC).getYear(); <END> int defaultMonth = 01; int defaultDay = 01; int year = Integer.parseInt(date.substring(0, 4)); int month = Integer.parseInt(date.substring(4, 6)); int day = Integer.parseInt(date.substring(6, 8)); if (year == 0) { year = defaultYear; } if (month == 0) { month = defaultMonth; } if (day == 0) { day = defaultDay; } return new LocalDate(year, month, day); }</code><technical_language>assuming Joda stupid dates? ISODateTimeFormat.basicDate() work</technical_language>

Target:
public static LocalDate parseDate(String date) { checkArgument(date.length() == 8, "Input date String should be 8 characters long"); int defaultYear = LocalDate.now(DateTimeZone.UTC).getYear(); int defaultMonth = 01; int defaultDay = 01; int year = Integer.parseInt(date.substring(0, 4)); int month = Integer.parseInt(date.substring(4, 6)); int day = Integer.parseInt(date.substring(6, 8)); if (year == 0) { year = defaultYear; } if (month == 0) { month = defaultMonth; } if (day == 0) { day = defaultDay; } return new LocalDate(year, month, day); }
Source:
<code>public Connector create(String catalogName, Map<String, String> config, ConnectorContext context) { requireNonNull(config, "config is null"); try { Bootstrap app = new Bootstrap( new JsonModule(), new DruidModule(), binder -> { binder.bind(TypeManager.class).toInstance(context.getTypeManager()); binder.bind(FunctionMetadataManager.class).toInstance(context.getFunctionMetadataManager()); binder.bind(RowExpressionService.class).toInstance(context.getRowExpressionService()); <START> binder.bind(LogicalRowExpressions.class).toInstance(new LogicalRowExpressions(context.getRowExpressionService().getDeterminismEvaluator(), context.getStandardFunctionResolution(), context.getFunctionMetadataManager())); <END> binder.bind(StandardFunctionResolution.class).toInstance(context.getStandardFunctionResolution()); }); Injector injector = app .strictConfig() .doNotInitializeLogging() .setRequiredConfigurationProperties(config) .initialize(); return injector.getInstance(DruidConnector.class); } catch (Exception e) { throwIfUnchecked(e); throw new RuntimeException(e); } }</code><technical_language>Kinda weird. LogicalRowExpressions created anytime injected singleton</technical_language>

Target:
public Connector create(String catalogName, Map<String, String> config, ConnectorContext context) { requireNonNull(config, "config is null"); try { Bootstrap app = new Bootstrap( new JsonModule(), new DruidModule(), binder -> { binder.bind(TypeManager.class).toInstance(context.getTypeManager()); binder.bind(FunctionMetadataManager.class).toInstance(context.getFunctionMetadataManager()); binder.bind(RowExpressionService.class).toInstance(context.getRowExpressionService()); binder.bind(StandardFunctionResolution.class).toInstance(context.getStandardFunctionResolution()); }); Injector injector = app .strictConfig() .doNotInitializeLogging() .setRequiredConfigurationProperties(config) .initialize(); return injector.getInstance(DruidConnector.class); } catch (Exception e) { throwIfUnchecked(e); throw new RuntimeException(e); } }
Source:
<code>public static String formatTime(long time, TimeFormat format, Resolution resolution) { <START> if (format == TimeFormat.CALENDAR) { <END> return formatTimeAbs(time, resolution); } else if (format == TimeFormat.NUMBER) { return NumberFormat.getInstance().format(time); } else if (format == TimeFormat.CYCLES) { return NumberFormat.getInstance().format(time) + Messages.Utils_ClockCyclesUnit; } StringBuffer str = new StringBuffer(); long t = time; boolean neg = t < 0; if (neg) { t = -t; str.append('-'); } long sec = t / SEC_IN_NS; str.append(sec); String ns = formatNs(t, resolution); if (!ns.equals("")) { str.append('.'); str.append(ns); } return str.toString(); }</code><technical_language>switcheroo</technical_language>

Target:
public static String formatTime(long time, TimeFormat format, Resolution resolution) { switch (format) { case CALENDAR: return formatTimeAbs(time, resolution); case NUMBER: return NumberFormat.getInstance().format(time); case CYCLES: return NumberFormat.getInstance().format(time) + Messages.Utils_ClockCyclesUnit; case RELATIVE: default: } StringBuffer str = new StringBuffer(); long t = time; boolean neg = t < 0; if (neg) { t = -t; str.append('-'); } long sec = t / SEC_IN_NS; str.append(sec); String ns = formatNs(t, resolution); if (!ns.equals("")) { str.append('.'); str.append(ns); } return str.toString(); }
Source:
<code>public boolean addEdge(final V v1, final V v2, final I i) { final Map<V, I> adjEdges = getEdges(v1); if (adjEdges == null) { throw new NoSuchElementException("No src vertex " + v1); } if (!adjEdges.containsKey(v2)) { adjEdges.put(v2, i); final int inDegree = inDegrees.get(v2); inDegrees.put(v2, inDegree + 1); if (inDegree == 0) { rootVertices.remove(v2); <START> } <END> return true; } else { LOG.log(Level.WARNING, "The edge from {0} to {1} already exists", new Object[]{v1, v2}); return false; } }</code><technical_language>code lines race condition</technical_language>

Target:
public boolean addEdge(final V v1, final V v2, final I i) { final Map<V, I> adjEdges = getEdges(v1); if (adjEdges == null) { throw new NoSuchElementException("No src vertex " + v1); } if (!adjEdges.containsKey(v2)) { numEdges += 1; adjEdges.put(v2, i); final int inDegree = inDegrees.get(v2); inDegrees.put(v2, inDegree + 1); return true; } else { LOG.log(Level.WARNING, "The edge from {0} to {1} already exists", new Object[]{v1, v2}); return false; } }
Source:
<code>public void initialize() { httpFeed = HttpFeed.builder() .entity(entity) .period(1000) <START> .baseUri(Providers.transform(Providers.atomic(url), UrlFunctions.URI_FROM_STRING)) <END> .poll(new HttpPollConfig<Double>(REQUEST_LATENCY_IN_SECONDS_MOST_RECENT) .onSuccess(HttpValueFunctions.latency()) .onError(Functions.constant((Double)null))) .suspended() .build(); }</code><technical_language>for URI.create(url.toString()) probably; added benefit fails fast if null</technical_language>

Target:
protected void initialize() { httpFeed = HttpFeed.builder() .entity(entity) .period(periodMillis) .baseUri(Suppliers.compose(Urls.URI_FROM_STRING, AtomicReferences.supplier(url))) .poll(new HttpPollConfig<Double>(REQUEST_LATENCY_IN_SECONDS_MOST_RECENT) .onSuccess(MathFunctions.divide(HttpValueFunctions.latency(), 1000.0d)) .onError(Functions.constant((Double)null))) .suspended() .build(); }
Source:
<code>public void onMessage(byte[] data, int offset, int length) { try { byte[] messageBytes = Arrays.copyOfRange(data, offset, offset + length); TransportDataMessage dataMessage = new TransportDataMessage(messageBytes); <START> if (dataMessage.getMessageType() == 5) { <END> LinkedHashMap<String, Object> dataMap = new LinkedHashMap<String, Object>(); dataMap.put("logicalTimestampMs", dataMessage.getLogicalTimestampMs()); dataMap.put("data", dataMessage.getData()); TransportChannel channel = channels.get(dataMessage.getChannelName()); if ((channel != null) && (!channel.isClosed())) { StreamMessage streamMessage = new StreamMessage("data", null, objectMapper.writeValueAsString(dataMap)); channel.offer(streamMessage); } else { log.debug("ignoring message. channel not found {}", dataMessage.getChannelName()); } } } catch (JsonProcessingException ex) { log.error("failed to process messages", ex); } }</code><technical_language>enum type</technical_language>

Target:
public void onMessage(byte[] data, int offset, int length) { try { byte[] messageBytes = Arrays.copyOfRange(data, offset, offset + length); TransportDataMessage dataMessage = new TransportDataMessage(messageBytes); if (dataMessage.getKind() == Kind.DATA) { LinkedHashMap<String, Object> dataMap = new LinkedHashMap<String, Object>(); dataMap.put("logicalTimestampMs", dataMessage.getLogicalTimestampMs()); dataMap.put("data", dataMessage.getData()); TransportChannel channel = channels.get(dataMessage.getChannelName()); if ((channel != null) && (!channel.isClosed())) { StreamMessage streamMessage = new StreamMessage("data", null, objectMapper.writeValueAsString(dataMap)); channel.offer(streamMessage); } else { log.debug("ignoring message. channel not found {}", dataMessage.getChannelName()); } } } catch (JsonProcessingException ex) { log.error("failed to process messages", ex); } }
Source:
<code>public ClusterParticipant getClusterParticipant() throws IOException { if (clusterParticipant == null) { clusterParticipant = new ClusterParticipant() { @Override public void participate(List<AmbryHealthReport> ambryHealthReports) { } @Override public void close() { } @Override public boolean setReplicaSealedState(ReplicaId replicaId, boolean isSealed) { return false; } @Override public boolean setReplicaStoppedState(List<ReplicaId> replicaIds, boolean isStopped) { return false; } @Override public List<String> getSealedReplicas() { <START> return new ArrayList<>(); <END> } @Override public List<String> getStoppedReplicas() { return new ArrayList<>(); } }; } return clusterParticipant; }</code><technical_language>minor: return Collections.emptyList() instead</technical_language>

Target:
public ClusterParticipant getClusterParticipant() throws IOException { if (clusterParticipant == null) { clusterParticipant = new ClusterParticipant() { @Override public void participate(List<AmbryHealthReport> ambryHealthReports) { } @Override public void close() { } @Override public boolean setReplicaSealedState(ReplicaId replicaId, boolean isSealed) { return false; } @Override public boolean setReplicaStoppedState(List<ReplicaId> replicaIds, boolean markStop) { return false; } @Override public List<String> getSealedReplicas() { return Collections.emptyList(); } @Override public List<String> getStoppedReplicas() { return Collections.emptyList(); } }; } return clusterParticipant; }
Source:
<code>private static IndexConfig buildNormalizedConfig(String mapName, IndexType indexType, String indexName, List<String> normalizedAttributeNames) { IndexConfig newConfig = new IndexConfig().setType(indexType); StringBuilder nameBuilder = indexName == null <START> ? new StringBuilder(mapName + (indexType == IndexType.SORTED ? "_sorted" : "_hash")) : null; <END> for (String normalizedAttributeName : normalizedAttributeNames) { newConfig.addAttribute(normalizedAttributeName); if (nameBuilder != null) { nameBuilder.append("_").append(normalizedAttributeName); } } if (nameBuilder != null) { indexName = nameBuilder.toString(); } newConfig.setName(indexName); return newConfig; }</code><technical_language>indexType.name()</technical_language>

Target:
private static IndexConfig buildNormalizedConfig(String mapName, IndexType indexType, String indexName, List<String> normalizedAttributeNames) { IndexConfig newConfig = new IndexConfig().setType(indexType); StringBuilder nameBuilder = indexName == null ? new StringBuilder(mapName + "_" + getIndexTypeName(indexType)) : null; for (String normalizedAttributeName : normalizedAttributeNames) { newConfig.addAttribute(normalizedAttributeName); if (nameBuilder != null) { nameBuilder.append("_").append(normalizedAttributeName); } } if (nameBuilder != null) { indexName = nameBuilder.toString(); } newConfig.setName(indexName); return newConfig; }
Source:
<code>private String macroSubs(String s, Map<String, String> macroMapping) { if (s == null) { return null; } StringBuilder ret = new StringBuilder(); StringBuilder macroName = null; int state = STATE_NORMAL; for (final char ch : s.toCharArray()) { switch (state) { case STATE_NORMAL: if (ch == '@') { state = STATE_EXPECT_BRACKET; } else { ret.append(ch); } break; case STATE_EXPECT_BRACKET: if (ch == '{') { state = STATE_EXPECT_NAME; macroName = new StringBuilder(); } else if (ch == '@') { state = STATE_NORMAL; ret.append('@'); } else { state = STATE_NORMAL; ret.append('@'); ret.append(ch); } break; case STATE_EXPECT_NAME: if (ch == '}') { state = STATE_NORMAL; String name = macroName.toString().toLowerCase(Locale.ENGLISH); String value = macroMapping.get(name); if (value == null) { ret.append("@{"); ret.append(name); ret.append("}"); } else { ret.append(value); } macroName = null; } else { macroName.append(ch); } break; default: break; } } switch (state) { case STATE_EXPECT_BRACKET: <START> ret.append('@'); <END> break; case STATE_EXPECT_NAME: ret.append("@{"); ret.append(macroName.toString()); break; default: break; } return ret.toString(); }</code><technical_language>explicit case easier default case</technical_language>

Target:
private String macroSubs(String s, Map<String, String> macroMapping) { if (s == null) { return null; } StringBuilder ret = new StringBuilder(); StringBuilder macroName = null; int state = STATE_NORMAL; for (final char ch : s.toCharArray()) { switch (state) { case STATE_NORMAL: if (ch == '@') { state = STATE_EXPECT_BRACKET; } else { ret.append(ch); } break; case STATE_EXPECT_BRACKET: if (ch == '{') { state = STATE_EXPECT_NAME; macroName = new StringBuilder(); } else if (ch == '@') { state = STATE_NORMAL; ret.append('@'); } else { state = STATE_NORMAL; ret.append('@'); ret.append(ch); } break; case STATE_EXPECT_NAME: if (ch == '}') { state = STATE_NORMAL; String name = macroName.toString().toLowerCase(Locale.ENGLISH); String value = macroMapping.get(name); if (value == null) { ret.append("@{"); ret.append(name); ret.append("}"); } else { ret.append(value); } macroName = null; } else { macroName.append(ch); } break; default: break; } } switch (state) { case STATE_NORMAL: break; case STATE_EXPECT_BRACKET: ret.append('@'); break; case STATE_EXPECT_NAME: ret.append("@{"); ret.append(macroName.toString()); break; default: break; } return ret.toString(); }
Source:
<code>protected ObjectNode prepareExtensionFragment(String entityString) { try { return mapper.readValue(entityString, ObjectNode.class); } catch (IOException e) { <START> LOGGER.warn(e.getMessage()); <END> return null; } }</code><technical_language>Instead of message, log out entire exception get stack trace well</technical_language>

Target:
protected ObjectNode prepareExtensionFragment(String entityString) { try { return mapper.readValue(entityString, ObjectNode.class); } catch (IOException e) { LOGGER.warn("IOException", e); return null; } }
Source:
<code>public static Argument argument(String name, Object value, boolean quoted) { <START> if (value instanceof String) { <END> value = quoted ? String.format("\"%s\"", value) : value; return new Argument(name, value); } else { try { return new Argument(name, JSON_MAPPER.writeValueAsString(value)); } catch (JsonProcessingException exception) { throw new IllegalStateException(String.format("Cannot serialize %s", value), exception); } } }</code><technical_language>argument is a string not, convertable JSON - run JSON parser</technical_language>

Target:
public static Argument argument(String name, Object value, boolean quoted) { if (value instanceof String) { value = quoted ? String.format("\"%s\"", value) : value; return new Argument(name, value); } else { try { return new Argument( name, BASE_MAPPER .configure( JsonGenerator.Feature.QUOTE_FIELD_NAMES, false ) .writeValueAsString(value) ); } catch (JsonProcessingException exception) { throw new IllegalStateException(String.format("Cannot serialize %s", value), exception); } } }
Source:
<code>private void removeRetroactiveResources(SimpleString address) throws Exception { String prefix = server.getConfiguration().getInternalNamingPrefix(); <START> SimpleString internalDivertName = ResourceNames.getRetroactiveResourceName(prefix, address, ResourceNames.DIVERT); <END> if (getBinding(internalDivertName) != null) { server.destroyDivert(internalDivertName); } SimpleString internalQueueName = ResourceNames.getRetroactiveResourceName(prefix, address, ResourceNames.QUEUE); if (server.locateQueue(internalQueueName) != null) { server.destroyQueue(internalQueueName); } SimpleString internalAddressName = ResourceNames.getRetroactiveResourceName(prefix, address, ResourceNames.ADDRESS); if (server.getAddressInfo(internalAddressName) != null) { server.removeAddressInfo(internalAddressName, null); } }</code><technical_language>divert separate address is needed. retro queue original address? separate address message copied simply a message reference existing message. adds more risk in if divert other address dont clean cleanly etc</technical_language>

Target:
private void removeRetroactiveResources(SimpleString address) throws Exception { String prefix = server.getInternalNamingPrefix(); String delimiter = server.getConfiguration().getWildcardConfiguration().getDelimiterString(); SimpleString internalDivertName = ResourceNames.getRetroactiveResourceDivertName(prefix, delimiter, address); if (getBinding(internalDivertName) != null) { server.destroyDivert(internalDivertName); } SimpleString internalAnycastQueueName = ResourceNames.getRetroactiveResourceQueueName(prefix, delimiter, address, RoutingType.ANYCAST); if (server.locateQueue(internalAnycastQueueName) != null) { server.destroyQueue(internalAnycastQueueName); } SimpleString internalMulticastQueueName = ResourceNames.getRetroactiveResourceQueueName(prefix, delimiter, address, RoutingType.MULTICAST); if (server.locateQueue(internalMulticastQueueName) != null) { server.destroyQueue(internalMulticastQueueName); } SimpleString internalAddressName = ResourceNames.getRetroactiveResourceAddressName(prefix, delimiter, address); if (server.getAddressInfo(internalAddressName) != null) { server.removeAddressInfo(internalAddressName, null); } }
Source:
<code>protected void doStop() throws Exception { <START> scheduledExecutorService.shutdown(); <END> super.doStop(); }</code><technical_language>@Gr1f0n6x , please ExecutorServiceManager.shutdownGraceful</technical_language>

Target:
protected void doStop() throws Exception { executorServiceManager.shutdownGraceful(scheduledExecutorService); super.doStop(); }
Source:
<code>protected void executeCommand() { VDSReturnValue vdsReturnaValue = runVdsCommand(VDSCommandType.StopRebalanceGlusterVolume, new GlusterVolumeVDSParameters(upServer.getId(), getGlusterVolumeName())); if (!vdsReturnaValue.getSucceeded()) { handleVdsError(AuditLogType.GLUSTER_VOLUME_REBALANCE_STOP_FAILED, vdsReturnaValue.getVdsError() .getMessage()); <START> return; <END> } endStepJob(); releaseVolumeLock(); setSucceeded(vdsReturnaValue.getSucceeded()); }</code><technical_language>setSucceeded(false) return</technical_language>

Target:
protected void executeCommand() { VDSReturnValue vdsReturnaValue = runVdsCommand(VDSCommandType.StopRebalanceGlusterVolume, new GlusterVolumeVDSParameters(upServer.getId(), getGlusterVolumeName())); if (!vdsReturnaValue.getSucceeded()) { handleVdsError(AuditLogType.GLUSTER_VOLUME_REBALANCE_STOP_FAILED, vdsReturnaValue.getVdsError() .getMessage()); setSucceeded(false); return; } endStepJob(); releaseVolumeLock(); setSucceeded(vdsReturnaValue.getSucceeded()); }
Source:
<code>public void traverseMenu(String... names) { assert names.length > 0 : "traverseMenu called with no arguments"; Platform.runLater(() -> { MenuControl root = TestController.getUI().getMenuControl(); MenuItem current = root.getMenus().stream() .filter(m -> m.getText().equals(names[0])) .findFirst() .orElseThrow(() -> new IllegalArgumentException( String.format("%s is not a valid menu item", names[0]))); for (int i = 1; i < names.length; i++) { final int j = i; if (current instanceof Menu) { current = ((Menu) current).getItems().stream() .filter(m -> m.getText().equals(names[j])) .findFirst() .orElseThrow(() -> new IllegalArgumentException( String.format("%s is not a valid menu item", names[j]))); } else { throw new IllegalArgumentException( String.format("Menu %s is not as nested as arguments require", names[0])); <START> } <END> } current.getOnAction().handle(new ActionEvent()); }); }</code><technical_language>if (!(current instanceof Menu)) move throw statement eliminate else clause</technical_language>

Target:
public void traverseMenu(String... names) { assert names.length > 0 : "traverseMenu called with no arguments"; Platform.runLater(() -> { MenuControl root = TestController.getUI().getMenuControl(); MenuItem current = root.getMenus().stream() .filter(m -> m.getText().equals(names[0])) .findFirst() .orElseThrow(() -> new IllegalArgumentException( String.format("%s is not a valid menu item", names[0]))); for (int i = 1; i < names.length; i++) { final int j = i; if (!(current instanceof Menu)) { throw new IllegalArgumentException( String.format("Menu %s is not as nested as arguments require", names[0])); } current = ((Menu) current).getItems().stream() .filter(m -> m.getText().equals(names[j])) .findFirst() .orElseThrow(() -> new IllegalArgumentException( String.format("%s is not a valid menu item", names[j]))); } current.getOnAction().handle(new ActionEvent()); }); }