    /**
     * List QueryLogic types that are currently available
     *
     * @HTTP 200 Success
     * @return datawave.webservice.result.QueryLogicResponse
     * @RequestHeader X-ProxiedEntitiesChain use when proxying request for user, by specifying a chain of DNs of the identities to proxy
     * @RequestHeader X-ProxiedIssuersChain required when using X-ProxiedEntitiesChain, specify one issuer DN per subject DN listed in X-ProxiedEntitiesChain
     * @ResponseHeader X-OperationTimeInMS time spent on the server performing the operation, does not account for network or result serialization
     */
    @Path("/listQueryLogic")
    @Produces({"application/xml", "text/xml", "application/json", "text/yaml", "text/x-yaml", "application/x-yaml", "text/html"})
    @GET
    @Interceptors({ResponseInterceptor.class})
    @Override
    @Timed(name = "dw.query.listQueryLogic", absolute = true)
    public QueryLogicResponse listQueryLogic() {
        QueryLogicResponse response = new QueryLogicResponse();
        List<QueryLogic<?>> logicList = queryLogicFactory.getQueryLogicList();
        List<QueryLogicDescription> logicConfigurationList = new ArrayList<>();

        // reference query necessary to avoid NPEs in getting the Transformer and BaseResponse
        Query q = new QueryImpl();
        Date now = new Date();
        q.setExpirationDate(now);
        q.setQuery("test");
        q.setQueryAuthorizations("ALL");
        ResultsPage emptyList = new ResultsPage();

        for (QueryLogic<?> l : logicList) {
            try {
                QueryLogicDescription d = new QueryLogicDescription(l.getLogicName());
                d.setAuditType(l.getAuditType(null).toString());
                d.setLogicDescription(l.getLogicDescription());

                Set<String> optionalQueryParameters = l.getOptionalQueryParameters();
                if (optionalQueryParameters != null) {
                    d.setSupportedParams(new ArrayList<>(optionalQueryParameters));
                }
                Set<String> requiredQueryParameters = l.getRequiredQueryParameters();
                if (requiredQueryParameters != null) {
                    d.setRequiredParams(new ArrayList<>(requiredQueryParameters));
                }
                Set<String> exampleQueries = l.getExampleQueries();
                if (exampleQueries != null) {
                    d.setExampleQueries(new ArrayList<>(exampleQueries));
                }
                Set<String> requiredRoles = l.getRoleManager().getRequiredRoles();
                if (requiredRoles != null) {
                    List<String> requiredRolesList = new ArrayList<>();
                    requiredRolesList.addAll(l.getRoleManager().getRequiredRoles());
                    d.setRequiredRoles(requiredRolesList);
                }
                q.setQueryLogicName(l.getLogicName());
                try {
                    QueryLogicTransformer t = l.getTransformer(q);
                    BaseResponse refResponse = t.createResponse(emptyList);
                    d.setResponseClass(refResponse.getClass().getCanonicalName());
                } catch (RuntimeException e) {
                    QueryException qe = new QueryException(DatawaveErrorCode.QUERY_TRANSFORM_ERROR, e);
                    log.error(qe);
                    response.addException(qe);
                    d.setResponseClass("unknown");
                }

                List<String> querySyntax = new ArrayList<>();
                try {
                    Method m = l.getClass().getMethod("getQuerySyntaxParsers");
                    Object result = m.invoke(l);
                    if (result instanceof Map<?,?>) {
                        Map<?,?> map = (Map<?,?>) result;
                        for (Object o : map.keySet())
                            querySyntax.add(o.toString());
                    }
                } catch (Exception e) {
                    log.warn("Unable to get query syntax for query logic: " + l.getClass().getCanonicalName());
                }
                if (querySyntax.isEmpty()) {
                    querySyntax.add("CUSTOM");
                }
                d.setQuerySyntax(querySyntax);

                logicConfigurationList.add(d);
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        }
        Collections.sort(logicConfigurationList, Comparator.comparing(QueryLogicDescription::getName));
        response.setQueryLogicList(logicConfigurationList);

        return response;
    }

    /**
     * List QueryLogic types that are currently available
     *
     * @HTTP 200 Success
     * @return datawave.webservice.result.QueryLogicResponse
     * @RequestHeader X-ProxiedEntitiesChain use when proxying request for user, by specifying a chain of DNs of the identities to proxy
     * @RequestHeader X-ProxiedIssuersChain required when using X-ProxiedEntitiesChain, specify one issuer DN per subject DN listed in X-ProxiedEntitiesChain
     * @ResponseHeader X-OperationTimeInMS time spent on the server performing the operation, does not account for network or result serialization
     */
    @Path("/listQueryLogic")
    @Produces({"application/xml", "text/xml", "application/json", "text/yaml", "text/x-yaml", "application/x-yaml", "text/html"})
    @GET
    @Interceptors({ResponseInterceptor.class})
    @Override
    @Timed(name = "dw.query.listQueryLogic", absolute = true)
    public QueryLogicResponse listQueryLogic() {
        QueryLogicResponse response = new QueryLogicResponse();
        List<QueryLogic<?>> logicList = queryLogicFactory.getQueryLogicList();
        List<QueryLogicDescription> logicConfigurationList = new ArrayList<>();

        // reference query necessary to avoid NPEs in getting the Transformer and BaseResponse
        Query q = new QueryImpl();
        Date now = new Date();
        q.setExpirationDate(now);
        q.setQuery("test");
        q.setQueryAuthorizations("ALL");
        ResultsPage emptyList = new ResultsPage();

        for (QueryLogic<?> l : logicList) {
            try {
                QueryLogicDescription d = new QueryLogicDescription(l.getLogicName());
                d.setAuditType(l.getAuditType(null).toString());
                d.setLogicDescription(l.getLogicDescription());

                Set<String> optionalQueryParameters = l.getOptionalQueryParameters();
                if (optionalQueryParameters != null) {
                    d.setSupportedParams(new ArrayList<>(optionalQueryParameters));
                }
                Set<String> requiredQueryParameters = l.getRequiredQueryParameters();
                if (requiredQueryParameters != null) {
                    d.setRequiredParams(new ArrayList<>(requiredQueryParameters));
                }
                Set<String> exampleQueries = l.getExampleQueries();
                if (exampleQueries != null) {
                    d.setExampleQueries(new ArrayList<>(exampleQueries));
                }
                Set<String> requiredRoles = l.getRoleManager().getRequiredRoles();
                if (requiredRoles != null) {
                    List<String> requiredRolesList = new ArrayList<>();
                    requiredRolesList.addAll(l.getRoleManager().getRequiredRoles());
                    d.setRequiredRoles(requiredRolesList);
                }
                q.setQueryLogicName(l.getLogicName());
                try {
                    QueryLogicTransformer t = l.getTransformer(q);
                    BaseResponse refResponse = t.createResponse(emptyList);
                    d.setResponseClass(refResponse.getClass().getCanonicalName());
                } catch (RuntimeException e) {
                    QueryException qe = new QueryException(DatawaveErrorCode.QUERY_TRANSFORM_ERROR, e);
                    log.error(qe);
                    response.addException(qe);
                    d.setResponseClass("unknown");
                }

                List<String> querySyntax = new ArrayList<>();
                try {
                    Method m = l.getClass().getMethod("getQuerySyntaxParsers");
                    Object result = m.invoke(l);
                    if (result instanceof Map<?,?>) {
                        Map<?,?> map = (Map<?,?>) result;
                        for (Object o : map.keySet())
                            querySyntax.add(o.toString());
                    }
                } catch (Exception e) {
                    log.warn("Unable to get query syntax for query logic: " + l.getClass().getCanonicalName());
                }
                if (querySyntax.isEmpty()) {
                    querySyntax.add("CUSTOM");
                }
                d.setQuerySyntax(querySyntax);

                logicConfigurationList.add(d);
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        }
        Collections.sort(logicConfigurationList, new Comparator<QueryLogicDescription>() {
            @Override
            public int compare(QueryLogicDescription ql1, QueryLogicDescription ql2) {
                return ql1.getName().compareTo(ql2.getName());
            }
        });
        response.setQueryLogicList(logicConfigurationList);

        return response;
    }

Replace Anonymous With Lambda datawave.webservice.query.runner.QueryExecutorBean.listQueryLogic.sort.new Comparator<QueryLogicDescription> with QueryLogicDescription::getName in method public listQueryLogic() : QueryLogicResponse from class datawave.webservice.query.runner.QueryExecutorBean


    /**
     * Attempt to async close a query using the executor. If the executor can't accommodate the close then the query will be closed in-line
     *
     * @param queryId
     *            non-null queryId
     */
    private void asyncClose(String queryId) {
        if (queryId != null) {
            final Principal p = ctx.getCallerPrincipal();
            final String closeQueryId = queryId;
            try {
                executor.submit(() -> {
                    close(closeQueryId, p);
                });
            } catch (RejectedExecutionException e) {
                // log only
                log.warn("close query rejected by executor id=" + closeQueryId + " principal=" + p, e);
                // do it the old (slow way)
                close(queryId);
            }
        }
    }

    /**
     * Attempt to async close a query using the executor. If the executor can't accommodate the close then the query will be closed in-line
     *
     * @param queryId
     *            non-null queryId
     */
    private void asyncClose(String queryId) {
        if (queryId != null) {
            final Principal p = ctx.getCallerPrincipal();
            final String closeQueryId = queryId;
            try {
                executor.submit(new Runnable() {
                    @Override
                    public void run() {
                        close(closeQueryId, p);
                    }
                });
            } catch (RejectedExecutionException e) {
                // log only
                log.warn("close query rejected by executor id=" + closeQueryId + " principal=" + p, e);
                // do it the old (slow way)
                close(queryId);
            }
        }
    }

Replace Anonymous With Lambda datawave.webservice.query.runner.QueryExecutorBean.asyncClose.submit.new Runnable with () -> {close(closeQueryId,p); in method private asyncClose(queryId String) : void from class datawave.webservice.query.runner.QueryExecutorBean


    public ResultsPage next() throws Exception {
        // update AbstractRunningQuery.lastUsed
        touch();
        long pageStartTime = System.currentTimeMillis();
        List<Object> resultList = new ArrayList<>();
        boolean hitPageByteTrigger = false;
        boolean hitPageTimeTrigger = false;
        try {
            addNDC();
            int currentPageCount = 0;
            long currentPageBytes = 0;

            // test for any exceptions prior to loop as hasNext() would likely be false;
            testForUncaughtException(resultList.size());

            while (!this.finished && ((future != null) || this.iter.hasNext())) {
                // if we are canceled, then break out
                if (this.canceled) {
                    log.info("Query has been cancelled, aborting query.next call");
                    this.getMetric().setLifecycle(QueryMetric.Lifecycle.CANCELLED);
                    break;
                }
                // if the number of results has reached out page size, then break out
                if (currentPageCount >= this.settings.getPagesize()) {
                    log.info("Query requested page size had been reached, aborting query.next call");
                    break;
                }
                // if the logic had a max page size and we have reached that, then break out
                if (this.logic.getMaxPageSize() > 0 && currentPageCount >= this.logic.getMaxPageSize()) {
                    log.info("Query logic max page size has been reached, aborting query.next call");
                    break;
                }
                // if the logic had a page byte trigger and we have readed that, then break out
                if (this.logic.getPageByteTrigger() > 0 && currentPageBytes >= this.logic.getPageByteTrigger()) {
                    log.info("Query logic max page byte trigger has been reached, aborting query.next call");
                    hitPageByteTrigger = true;
                    break;
                }
                // if the logic had a max rows to scan (across all pages) and we have reached that, then break out
                if (this.logic.getMaxRowsToScan() > 0 && scanned >= this.logic.getMaxRowsToScan()) {
                    log.info("Query logic max rows to scan has been reached, aborting query.next call");
                    break;
                }
                // if the logic had a max num results (across all pages) and we have reached that, then break out
                if (this.logic.getMaxResults() > 0 && numResults >= this.logic.getMaxResults()) {
                    log.info("Query logic max results has been reached, aborting query.next call");
                    this.getMetric().setLifecycle(QueryMetric.Lifecycle.MAXRESULTS);
                    break;
                }
                // if we are the specified amount on the way to timing out on this call and we have results,
                // determine whether we are on track to having enough results
                // use the pagestart time for the time in call since we only care about the execution time of
                // this page.
                long pageTimeInCall = (System.currentTimeMillis() - pageStartTime);

                int maxPageSize = Math.min(this.settings.getPagesize(), this.logic.getMaxPageSize());
                if (timing != null && currentPageCount > 0 && timing.shouldReturnPartialResults(currentPageCount, maxPageSize, pageTimeInCall)) {
                    log.info("Query logic max expire before page is full, returning existing results " + currentPageCount + " " + maxPageSize + " "
                                    + pageTimeInCall + " " + timing.toString());
                    hitPageTimeTrigger = true;
                    break;
                }
                scanned++;

                Object o = null;
                if (executor != null) {
                    if (future == null) {
                        future = executor.submit(() -> iter.next());
                    }
                    try {
                        o = future.get(1, TimeUnit.MINUTES);
                        future = null;
                    } catch (InterruptedException ie) {
                        // in this case we were most likely cancelled, no longer waiting
                        future = null;
                    } catch (ExecutionException ee) {
                        // in this case we need to pass up the exception
                        future = null;
                        throw ee;
                    } catch (TimeoutException te) {
                        // in this case we are still waiting on our future....simply continue
                    }
                } else {
                    o = iter.next();
                }
                // if not still waiting on a future, then process the result (or lack thereof)
                if (future == null) {
                    if (null == o) {
                        log.debug("Null result encountered, no more results");
                        this.finished = true;
                        break;
                    }
                    resultList.add(o);
                    if (this.logic.getPageByteTrigger() > 0) {
                        currentPageBytes += ObjectSizeOf.Sizer.getObjectSize(o);
                    }
                    currentPageCount++;
                    numResults++;
                }

                testForUncaughtException(resultList.size());
            }

            // if the last hasNext() call failed, then we would catch the exception here
            testForUncaughtException(resultList.size());

            // Update the metric
            long now = System.currentTimeMillis();
            this.getMetric().addPageTime(currentPageCount, now - pageStartTime, pageStartTime, now);
            this.lastPageNumber++;
            if (resultList.size() > 0) {
                this.getMetric().setLifecycle(QueryMetric.Lifecycle.RESULTS);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            this.getMetric().setError(e);
            throw e;
        } finally {
            // update AbstractRunningQuery.lastUsed in case this operation took a long time
            touch();
            removeNDC();

            if (this.queryMetrics != null) {
                try {
                    if (iter.getTransformer() instanceof WritesQueryMetrics) {
                        ((WritesQueryMetrics) iter.getTransformer()).writeQueryMetrics(this.getMetric());
                    }
                    this.queryMetrics.updateMetric(this.getMetric());
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }
            }
        }
        if (resultList.isEmpty()) {
            return new ResultsPage();
        } else {
            return new ResultsPage(resultList, ((hitPageByteTrigger || hitPageTimeTrigger) ? ResultsPage.Status.PARTIAL : ResultsPage.Status.COMPLETE));
        }
    }

    public ResultsPage next() throws Exception {
        // update AbstractRunningQuery.lastUsed
        touch();
        long pageStartTime = System.currentTimeMillis();
        List<Object> resultList = new ArrayList<>();
        boolean hitPageByteTrigger = false;
        boolean hitPageTimeTrigger = false;
        try {
            addNDC();
            int currentPageCount = 0;
            long currentPageBytes = 0;

            // test for any exceptions prior to loop as hasNext() would likely be false;
            testForUncaughtException(resultList.size());

            while (!this.finished && ((future != null) || this.iter.hasNext())) {
                // if we are canceled, then break out
                if (this.canceled) {
                    log.info("Query has been cancelled, aborting query.next call");
                    this.getMetric().setLifecycle(QueryMetric.Lifecycle.CANCELLED);
                    break;
                }
                // if the number of results has reached out page size, then break out
                if (currentPageCount >= this.settings.getPagesize()) {
                    log.info("Query requested page size had been reached, aborting query.next call");
                    break;
                }
                // if the logic had a max page size and we have reached that, then break out
                if (this.logic.getMaxPageSize() > 0 && currentPageCount >= this.logic.getMaxPageSize()) {
                    log.info("Query logic max page size has been reached, aborting query.next call");
                    break;
                }
                // if the logic had a page byte trigger and we have readed that, then break out
                if (this.logic.getPageByteTrigger() > 0 && currentPageBytes >= this.logic.getPageByteTrigger()) {
                    log.info("Query logic max page byte trigger has been reached, aborting query.next call");
                    hitPageByteTrigger = true;
                    break;
                }
                // if the logic had a max rows to scan (across all pages) and we have reached that, then break out
                if (this.logic.getMaxRowsToScan() > 0 && scanned >= this.logic.getMaxRowsToScan()) {
                    log.info("Query logic max rows to scan has been reached, aborting query.next call");
                    break;
                }
                // if the logic had a max num results (across all pages) and we have reached that, then break out
                if (this.logic.getMaxResults() > 0 && numResults >= this.logic.getMaxResults()) {
                    log.info("Query logic max results has been reached, aborting query.next call");
                    this.getMetric().setLifecycle(QueryMetric.Lifecycle.MAXRESULTS);
                    break;
                }
                // if we are the specified amount on the way to timing out on this call and we have results,
                // determine whether we are on track to having enough results
                // use the pagestart time for the time in call since we only care about the execution time of
                // this page.
                long pageTimeInCall = (System.currentTimeMillis() - pageStartTime);

                int maxPageSize = Math.min(this.settings.getPagesize(), this.logic.getMaxPageSize());
                if (timing != null && currentPageCount > 0 && timing.shouldReturnPartialResults(currentPageCount, maxPageSize, pageTimeInCall)) {
                    log.info("Query logic max expire before page is full, returning existing results " + currentPageCount + " " + maxPageSize + " "
                                    + pageTimeInCall + " " + timing.toString());
                    hitPageTimeTrigger = true;
                    break;
                }
                scanned++;

                Object o = null;
                if (executor != null) {
                    if (future == null) {
                        future = executor.submit(new Callable<Object>() {
                            @Override
                            public Object call() throws Exception {
                                return iter.next();
                            }
                        });
                    }
                    try {
                        o = future.get(1, TimeUnit.MINUTES);
                        future = null;
                    } catch (InterruptedException ie) {
                        // in this case we were most likely cancelled, no longer waiting
                        future = null;
                    } catch (ExecutionException ee) {
                        // in this case we need to pass up the exception
                        future = null;
                        throw ee;
                    } catch (TimeoutException te) {
                        // in this case we are still waiting on our future....simply continue
                    }
                } else {
                    o = iter.next();
                }
                // if not still waiting on a future, then process the result (or lack thereof)
                if (future == null) {
                    if (null == o) {
                        log.debug("Null result encountered, no more results");
                        this.finished = true;
                        break;
                    }
                    resultList.add(o);
                    if (this.logic.getPageByteTrigger() > 0) {
                        currentPageBytes += ObjectSizeOf.Sizer.getObjectSize(o);
                    }
                    currentPageCount++;
                    numResults++;
                }

                testForUncaughtException(resultList.size());
            }

            // if the last hasNext() call failed, then we would catch the exception here
            testForUncaughtException(resultList.size());

            // Update the metric
            long now = System.currentTimeMillis();
            this.getMetric().addPageTime(currentPageCount, now - pageStartTime, pageStartTime, now);
            this.lastPageNumber++;
            if (resultList.size() > 0) {
                this.getMetric().setLifecycle(QueryMetric.Lifecycle.RESULTS);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            this.getMetric().setError(e);
            throw e;
        } finally {
            // update AbstractRunningQuery.lastUsed in case this operation took a long time
            touch();
            removeNDC();

            if (this.queryMetrics != null) {
                try {
                    if (iter.getTransformer() instanceof WritesQueryMetrics) {
                        ((WritesQueryMetrics) iter.getTransformer()).writeQueryMetrics(this.getMetric());
                    }
                    this.queryMetrics.updateMetric(this.getMetric());
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }
            }
        }
        if (resultList.isEmpty()) {
            return new ResultsPage();
        } else {
            return new ResultsPage(resultList, ((hitPageByteTrigger || hitPageTimeTrigger) ? ResultsPage.Status.PARTIAL : ResultsPage.Status.COMPLETE));
        }
    }

Replace Anonymous With Lambda datawave.webservice.query.runner.RunningQuery.next.submit.new Callable<Object> with () -> iter.next() in method public next() : ResultsPage from class datawave.webservice.query.runner.RunningQuery


    @SuppressWarnings("unchecked")
    @Test(timeout = 5000)
    public void testCloseActuallyCloses() throws Exception {
        QueryImpl q = createNewQuery();

        final MultivaluedMap<String,String> queryParameters = createNewQueryParameterMap();

        final Thread createQuery = new Thread(() -> {
            try {
                bean.createQuery("EventQueryLogic", queryParameters);
            } catch (Exception e) {
                // ok if we fail the call
                        log.debug("createQuery terminated with " + e);
                    }
                });

        final Throwable[] createQueryException = {null};
        createQuery.setUncaughtExceptionHandler((t, e) -> createQueryException[0] = e);

        @SuppressWarnings("rawtypes")
        QueryLogic logic = createMock(BaseQueryLogic.class);

        DatawaveUser user = new DatawaveUser(SubjectIssuerDNPair.of(userDN, "<CN=MY_CA, OU=MY_SUBDIVISION, OU=MY_DIVISION, O=ORG, C=US>"), UserType.USER,
                        Arrays.asList(auths), null, null, 0L);
        DatawavePrincipal principal = new DatawavePrincipal(Collections.singletonList(user));
        principal.getShortName();
        String[] dns = principal.getDNs();
        Arrays.sort(dns);
        List<String> dnList = Arrays.asList(dns);

        InMemoryInstance instance = new InMemoryInstance();
        Connector c = instance.getConnector("root", new PasswordToken(""));

        MultivaluedMap<String,String> optionalParameters = createNewQueryParameters(q, queryParameters);
        // QueryParameters qp = new QueryParametersImpl();
        // qp.validate(queryParameters);
        // MultivaluedMap<String,String> optionalParameters = qp.getUnknownParameters(queryParameters);
        // optionalParameters.putSingle(AuditParameters.USER_DN, principal.getUserDN().subjectDN());
        // optionalParameters.putSingle(AuditParameters.QUERY_SECURITY_MARKING_COLVIZ, q.getColumnVisibility());
        // optionalParameters.putSingle("logicClass", queryLogicName);

        PowerMock.resetAll();
        EasyMock.expect(ctx.getCallerPrincipal()).andReturn(principal).anyTimes();
        EasyMock.expect(logic.getAuditType(null)).andReturn(AuditType.NONE);
        EasyMock.expect(persister.create(principal.getUserDN().subjectDN(), dnList, Whitebox.getInternalState(bean, SecurityMarking.class), queryLogicName,
                        Whitebox.getInternalState(bean, QueryParameters.class), optionalParameters)).andReturn(q);
        persister.remove(q);
        EasyMock.expect(connectionFactory.getTrackingMap((StackTraceElement[]) anyObject())).andReturn(Maps.<String,String> newHashMap()).anyTimes();

        BaseQueryMetric metric = new QueryMetricFactoryImpl().createMetric();
        q.populateMetric(metric);
        EasyMock.expectLastCall();
        metric.setQueryType(RunningQuery.class.getSimpleName());
        metric.setLifecycle(Lifecycle.DEFINED);
        System.out.println(metric.toString());

        Set<Prediction> predictions = new HashSet<Prediction>();
        predictions.add(new Prediction("source", 1));
        EasyMock.expect(predictor.predict(metric)).andReturn(predictions);

        connectionRequestBean.requestBegin(q.getId().toString());
        EasyMock.expectLastCall();
        EasyMock.expect(connectionFactory.getConnection(eq("connPool1"), (AccumuloConnectionFactory.Priority) anyObject(), (Map<String,String>) anyObject()))
                        .andReturn(c).anyTimes();
        connectionRequestBean.requestEnd(q.getId().toString());
        EasyMock.expectLastCall();
        connectionFactory.returnConnection(c);
        EasyMock.expectLastCall();

        EasyMock.expect(queryLogicFactory.getQueryLogic(queryLogicName, principal)).andReturn(logic);
        EasyMock.expect(logic.getRequiredQueryParameters()).andReturn(Collections.emptySet());
        EasyMock.expect(logic.getConnectionPriority()).andReturn(AccumuloConnectionFactory.Priority.NORMAL).atLeastOnce();
        EasyMock.expect(logic.getMaxPageSize()).andReturn(0);
        EasyMock.expect(logic.getAuditType(q)).andReturn(AuditType.NONE);
        EasyMock.expect(logic.getConnPoolName()).andReturn("connPool1");

        EasyMock.expect(connectionRequestBean.cancelConnectionRequest(q.getId().toString(), principal)).andReturn(false);
        connectionFactory.returnConnection(EasyMock.isA(Connector.class));

        final AtomicBoolean initializeLooping = new AtomicBoolean(false);

        // During initialize, mark that we get here, and then sleep
        final IAnswer<GenericQueryConfiguration> initializeAnswer = () -> {
            initializeLooping.set(true);
            try {
                while (true) {
                    Thread.sleep(1000);
                    log.debug("Initialize: woke up");
                }
            } catch (InterruptedException e) {
                throw new QueryException("EXPECTED EXCEPTION: initialize interrupted");
            }
        };

        EasyMock.expect(logic.initialize(anyObject(Connector.class), anyObject(Query.class), anyObject(Set.class))).andAnswer(initializeAnswer);
        EasyMock.expect(logic.getCollectQueryMetrics()).andReturn(Boolean.FALSE);

        // On close, interrupt the thread to simulate the ScannerFactory cleaning up
        final IAnswer<Object> closeAnswer = () -> {
            if (null != createQuery) {
                log.debug("createQuery thread is not null. interrupting");
                createQuery.interrupt();
            } else {
                log.debug("createQuery thread is null. not interrupting");
            }
            return null;
        };

        logic.close();
        EasyMock.expectLastCall().andAnswer(closeAnswer).anyTimes();

        // Make the QueryLogic mock not threadsafe, otherwise it will be blocked infinitely
        // trying to get the lock on the infinite loop
        EasyMock.makeThreadSafe(logic, false);

        metrics.updateMetric(EasyMock.isA(QueryMetric.class));

        PowerMock.replayAll();
        try {
            createQuery.start();

            // Wait for the create call to get to initialize
            while (!initializeLooping.get()) {
                if (!createQuery.isAlive() && !initializeLooping.get()) {
                    Assert.fail("createQuery thread died before reaching initialize: " + createQueryException[0]);
                }
                Thread.sleep(50);
            }

            // initialize has not completed yet so it will not appear in the cache
            Object cachedRunningQuery = cache.get(q.getId().toString());
            Assert.assertNull(cachedRunningQuery);
            Pair<QueryLogic<?>,Connector> pair = qlCache.poll(q.getId().toString());
            Assert.assertNotNull(pair);
            Assert.assertEquals(logic, pair.getFirst());
            Assert.assertEquals(c, pair.getSecond());

            // Have to add these back because poll was destructive
            qlCache.add(q.getId().toString(), principal.getShortName(), pair.getFirst(), pair.getSecond());

            // Call close
            bean.close(q.getId().toString());

            // Make sure that it's gone from the qlCache
            pair = qlCache.poll(q.getId().toString());
            Assert.assertNull("Still found an entry in the qlCache: " + pair, pair);

            // Should have already joined by now, but just to be sure
            createQuery.join();
        } finally {
            if (null != createQuery && createQuery.isAlive()) {
                createQuery.interrupt();
            }
        }
    }

    @SuppressWarnings("unchecked")
    @Test(timeout = 5000)
    public void testCloseActuallyCloses() throws Exception {
        QueryImpl q = createNewQuery();

        final MultivaluedMap<String,String> queryParameters = createNewQueryParameterMap();

        final Thread createQuery = new Thread(() -> {
            try {
                bean.createQuery("EventQueryLogic", queryParameters);
            } catch (Exception e) {
                // ok if we fail the call
                        log.debug("createQuery terminated with " + e);
                    }
                });

        final Throwable[] createQueryException = {null};
        createQuery.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
            @Override
            public void uncaughtException(Thread t, Throwable e) {
                createQueryException[0] = e;
            }
        });

        @SuppressWarnings("rawtypes")
        QueryLogic logic = createMock(BaseQueryLogic.class);

        DatawaveUser user = new DatawaveUser(SubjectIssuerDNPair.of(userDN, "<CN=MY_CA, OU=MY_SUBDIVISION, OU=MY_DIVISION, O=ORG, C=US>"), UserType.USER,
                        Arrays.asList(auths), null, null, 0L);
        DatawavePrincipal principal = new DatawavePrincipal(Collections.singletonList(user));
        principal.getShortName();
        String[] dns = principal.getDNs();
        Arrays.sort(dns);
        List<String> dnList = Arrays.asList(dns);

        InMemoryInstance instance = new InMemoryInstance();
        Connector c = instance.getConnector("root", new PasswordToken(""));

        MultivaluedMap<String,String> optionalParameters = createNewQueryParameters(q, queryParameters);
        // QueryParameters qp = new QueryParametersImpl();
        // qp.validate(queryParameters);
        // MultivaluedMap<String,String> optionalParameters = qp.getUnknownParameters(queryParameters);
        // optionalParameters.putSingle(AuditParameters.USER_DN, principal.getUserDN().subjectDN());
        // optionalParameters.putSingle(AuditParameters.QUERY_SECURITY_MARKING_COLVIZ, q.getColumnVisibility());
        // optionalParameters.putSingle("logicClass", queryLogicName);

        PowerMock.resetAll();
        EasyMock.expect(ctx.getCallerPrincipal()).andReturn(principal).anyTimes();
        EasyMock.expect(logic.getAuditType(null)).andReturn(AuditType.NONE);
        EasyMock.expect(persister.create(principal.getUserDN().subjectDN(), dnList, Whitebox.getInternalState(bean, SecurityMarking.class), queryLogicName,
                        Whitebox.getInternalState(bean, QueryParameters.class), optionalParameters)).andReturn(q);
        persister.remove(q);
        EasyMock.expect(connectionFactory.getTrackingMap((StackTraceElement[]) anyObject())).andReturn(Maps.<String,String> newHashMap()).anyTimes();

        BaseQueryMetric metric = new QueryMetricFactoryImpl().createMetric();
        q.populateMetric(metric);
        EasyMock.expectLastCall();
        metric.setQueryType(RunningQuery.class.getSimpleName());
        metric.setLifecycle(Lifecycle.DEFINED);
        System.out.println(metric.toString());

        Set<Prediction> predictions = new HashSet<Prediction>();
        predictions.add(new Prediction("source", 1));
        EasyMock.expect(predictor.predict(metric)).andReturn(predictions);

        connectionRequestBean.requestBegin(q.getId().toString());
        EasyMock.expectLastCall();
        EasyMock.expect(connectionFactory.getConnection(eq("connPool1"), (AccumuloConnectionFactory.Priority) anyObject(), (Map<String,String>) anyObject()))
                        .andReturn(c).anyTimes();
        connectionRequestBean.requestEnd(q.getId().toString());
        EasyMock.expectLastCall();
        connectionFactory.returnConnection(c);
        EasyMock.expectLastCall();

        EasyMock.expect(queryLogicFactory.getQueryLogic(queryLogicName, principal)).andReturn(logic);
        EasyMock.expect(logic.getRequiredQueryParameters()).andReturn(Collections.emptySet());
        EasyMock.expect(logic.getConnectionPriority()).andReturn(AccumuloConnectionFactory.Priority.NORMAL).atLeastOnce();
        EasyMock.expect(logic.getMaxPageSize()).andReturn(0);
        EasyMock.expect(logic.getAuditType(q)).andReturn(AuditType.NONE);
        EasyMock.expect(logic.getConnPoolName()).andReturn("connPool1");

        EasyMock.expect(connectionRequestBean.cancelConnectionRequest(q.getId().toString(), principal)).andReturn(false);
        connectionFactory.returnConnection(EasyMock.isA(Connector.class));

        final AtomicBoolean initializeLooping = new AtomicBoolean(false);

        // During initialize, mark that we get here, and then sleep
        final IAnswer<GenericQueryConfiguration> initializeAnswer = () -> {
            initializeLooping.set(true);
            try {
                while (true) {
                    Thread.sleep(1000);
                    log.debug("Initialize: woke up");
                }
            } catch (InterruptedException e) {
                throw new QueryException("EXPECTED EXCEPTION: initialize interrupted");
            }
        };

        EasyMock.expect(logic.initialize(anyObject(Connector.class), anyObject(Query.class), anyObject(Set.class))).andAnswer(initializeAnswer);
        EasyMock.expect(logic.getCollectQueryMetrics()).andReturn(Boolean.FALSE);

        // On close, interrupt the thread to simulate the ScannerFactory cleaning up
        final IAnswer<Object> closeAnswer = () -> {
            if (null != createQuery) {
                log.debug("createQuery thread is not null. interrupting");
                createQuery.interrupt();
            } else {
                log.debug("createQuery thread is null. not interrupting");
            }
            return null;
        };

        logic.close();
        EasyMock.expectLastCall().andAnswer(closeAnswer).anyTimes();

        // Make the QueryLogic mock not threadsafe, otherwise it will be blocked infinitely
        // trying to get the lock on the infinite loop
        EasyMock.makeThreadSafe(logic, false);

        metrics.updateMetric(EasyMock.isA(QueryMetric.class));

        PowerMock.replayAll();
        try {
            createQuery.start();

            // Wait for the create call to get to initialize
            while (!initializeLooping.get()) {
                if (!createQuery.isAlive() && !initializeLooping.get()) {
                    Assert.fail("createQuery thread died before reaching initialize: " + createQueryException[0]);
                }
                Thread.sleep(50);
            }

            // initialize has not completed yet so it will not appear in the cache
            Object cachedRunningQuery = cache.get(q.getId().toString());
            Assert.assertNull(cachedRunningQuery);
            Pair<QueryLogic<?>,Connector> pair = qlCache.poll(q.getId().toString());
            Assert.assertNotNull(pair);
            Assert.assertEquals(logic, pair.getFirst());
            Assert.assertEquals(c, pair.getSecond());

            // Have to add these back because poll was destructive
            qlCache.add(q.getId().toString(), principal.getShortName(), pair.getFirst(), pair.getSecond());

            // Call close
            bean.close(q.getId().toString());

            // Make sure that it's gone from the qlCache
            pair = qlCache.poll(q.getId().toString());
            Assert.assertNull("Still found an entry in the qlCache: " + pair, pair);

            // Should have already joined by now, but just to be sure
            createQuery.join();
        } finally {
            if (null != createQuery && createQuery.isAlive()) {
                createQuery.interrupt();
            }
        }
    }

Replace Anonymous With Lambda datawave.webservice.query.runner.QueryExecutorBeanTest.testCloseActuallyCloses.setUncaughtExceptionHandler.new Thread.UncaughtExceptionHandler with (t, e) -> createQueryException[0]=e in method public testCloseActuallyCloses() : void from class datawave.webservice.query.runner.QueryExecutorBeanTest


    @Test(expected = IllegalArgumentException.class)
    public void emptyUserDNTest() {
        Map<String,List<String>> params = new HashMap<>(this.params);
        params.put(AuditParameters.USER_DN, new ArrayList<>());

        new AuditParameters().validate(params);
    }

    @Test(expected = IllegalArgumentException.class)
    public void emptyUserDNTest() {
        Map<String,List<String>> params = new HashMap<>(this.params);
        params.put(AuditParameters.USER_DN, new ArrayList<String>());

        new AuditParameters().validate(params);
    }

Replace Generic With Diamond ArrayList<String> with ArrayList<> in method public emptyUserDNTest() : void from class datawave.webservice.common.audit.AuditParametersTest


    @Test(expected = IllegalArgumentException.class)
    public void emptyQueryStringTest() {
        Map<String,List<String>> params = new HashMap<>(this.params);
        params.put(AuditParameters.QUERY_STRING, new ArrayList<>());

        new AuditParameters().validate(params);
    }

    @Test(expected = IllegalArgumentException.class)
    public void emptyQueryStringTest() {
        Map<String,List<String>> params = new HashMap<>(this.params);
        params.put(AuditParameters.QUERY_STRING, new ArrayList<String>());

        new AuditParameters().validate(params);
    }

Replace Generic With Diamond ArrayList<String> with ArrayList<> in method public emptyQueryStringTest() : void from class datawave.webservice.common.audit.AuditParametersTest


    @Test(expected = IllegalArgumentException.class)
    public void emptyAuthsTest() {
        Map<String,List<String>> params = new HashMap<>(this.params);
        params.put(AuditParameters.QUERY_AUTHORIZATIONS, new ArrayList<>());

        new AuditParameters().validate(params);
    }

    @Test(expected = IllegalArgumentException.class)
    public void emptyAuthsTest() {
        Map<String,List<String>> params = new HashMap<>(this.params);
        params.put(AuditParameters.QUERY_AUTHORIZATIONS, new ArrayList<String>());

        new AuditParameters().validate(params);
    }

Replace Generic With Diamond ArrayList<String> with ArrayList<> in method public emptyAuthsTest() : void from class datawave.webservice.common.audit.AuditParametersTest


    @Test(expected = IllegalArgumentException.class)
    public void emptyAuditTypeTest() {
        Map<String,List<String>> params = new HashMap<>(this.params);
        params.put(AuditParameters.QUERY_AUDIT_TYPE, new ArrayList<>());

        new AuditParameters().validate(params);
    }

    @Test(expected = IllegalArgumentException.class)
    public void emptyAuditTypeTest() {
        Map<String,List<String>> params = new HashMap<>(this.params);
        params.put(AuditParameters.QUERY_AUDIT_TYPE, new ArrayList<String>());

        new AuditParameters().validate(params);
    }

Replace Generic With Diamond ArrayList<String> with ArrayList<> in method public emptyAuditTypeTest() : void from class datawave.webservice.common.audit.AuditParametersTest


    @Test(expected = IllegalArgumentException.class)
    public void emptyColVizTest() {
        Map<String,List<String>> params = new HashMap<>(this.params);
        params.put(AuditParameters.QUERY_SECURITY_MARKING_COLVIZ, new ArrayList<>());

        new AuditParameters().validate(params);
    }

    @Test(expected = IllegalArgumentException.class)
    public void emptyColVizTest() {
        Map<String,List<String>> params = new HashMap<>(this.params);
        params.put(AuditParameters.QUERY_SECURITY_MARKING_COLVIZ, new ArrayList<String>());

        new AuditParameters().validate(params);
    }

Replace Generic With Diamond ArrayList<String> with ArrayList<> in method public emptyColVizTest() : void from class datawave.webservice.common.audit.AuditParametersTest


    @Override
    public Iterable<OffsetList<T>> offsets() {
        return () -> {
            final Iterator<Map.Entry<String,List<T>>> entries = offsetsMap.entrySet().iterator();
            final OffsetList<T> offsets = new OffsetList<>();
            return new Iterator<OffsetList<T>>() {
                @Override
                public boolean hasNext() {
                    return entries.hasNext();
                }

                @Override
                public OffsetList next() {
                    Map.Entry<String,List<T>> entry = entries.next();
                    offsets.offsets = entry.getValue();
                    offsets.termAndZone = new TermAndZone(entry.getKey());
                    return offsets;
                }

                @Override
                public void remove() {
                    entries.remove();
                }
            };
        };
    }

    @Override
    public Iterable<OffsetList> offsets() {
        return new Iterable<OffsetList>() {
            @Override
            public Iterator<OffsetList> iterator() {
                final Iterator<Map.Entry<String,int[]>> entries = offsetsMap.entrySet().iterator();
                final OffsetList offsets = new OffsetList();
                return new Iterator<OffsetList>() {

                    @Override
                    public boolean hasNext() {
                        return entries.hasNext();
                    }

                    @Override
                    public OffsetList next() {
                        Map.Entry<String,int[]> entry = entries.next();
                        offsets.offsets = entry.getValue();
                        offsets.termAndZone = new TermAndZone(entry.getKey());
                        return offsets;
                    }

                    @Override
                    public void remove() {
                        entries.remove();
                    }
                };
            }
        };
    }

Replace Anonymous With Lambda datawave.ingest.mapreduce.handler.shard.content.BoundedOffsetQueue.offsets.new Iterable<OffsetList> with () -> {final Iterator<Map.Entry<String,List<T>>> entries=offsetsMap.entrySet().iterator(); in method public offsets() : Iterable<OffsetList<T>> from class datawave.ingest.mapreduce.handler.shard.content.BoundedOffsetQueue


    /**
     * Let clients ask what fields we are currently tracking.
     */
    public Set<String> fields() {
        if (this.offsetsPerField.isEmpty()) {
            return Collections.<String> emptySet();
        } else {
            Set<String> fields = new HashSet<>();
            for (Zone zone : this.offsetsPerField.keySet()) {
                fields.add(zone.getZone());
            }
            return fields;
        }
    }

    /**
     * Let clients ask what fields we are currently tracking.
     */
    public Set<String> fields() {
        if (this.offsetsPerField.isEmpty()) {
            return Collections.<String> emptySet();
        } else {
            Set<String> fields = new HashSet<String>();
            for (Zone zone : this.offsetsPerField.keySet()) {
                fields.add(zone.getZone());
            }
            return fields;
        }
    }

Replace Generic With Diamond HashSet<String> with HashSet<> in method public fields() : Set<String> from class datawave.query.jexl.functions.TermFrequencyList


    /**
     * Let clients ask what event ids we are currently tracking.
     */
    public Set<String> eventIds() {
        if (this.offsetsPerField.isEmpty()) {
            return Collections.<String> emptySet();
        } else {
            Set<String> eventIds = new HashSet<>();
            for (Zone zone : this.offsetsPerField.keySet()) {
                eventIds.add(zone.getEventId());
            }
            return eventIds;
        }
    }

    /**
     * Let clients ask what event ids we are currently tracking.
     */
    public Set<String> eventIds() {
        if (this.offsetsPerField.isEmpty()) {
            return Collections.<String> emptySet();
        } else {
            Set<String> eventIds = new HashSet<String>();
            for (Zone zone : this.offsetsPerField.keySet()) {
                eventIds.add(zone.getEventId());
            }
            return eventIds;
        }
    }

Replace Generic With Diamond HashSet<String> with HashSet<> in method public eventIds() : Set<String> from class datawave.query.jexl.functions.TermFrequencyList


    public Iterator<Map<String, Object>> keyedIterator() throws Exception{
        return new TableIterator<>(this, true, false, true, false);
    }

    public Iterator<Map<String, Object>> keyedIterator() throws Exception{
        return new TableIterator<Map<String, Object>>(this, true, false, true, false);
    }

Replace Generic With Diamond TableIterator<Map<String,Object>> with TableIterator<> in method public keyedIterator() : Iterator<Map<String,Object>> from class io.frictionlessdata.tableschema.Table


    public Iterator<Map<String, Object>> keyedIterator(boolean extended, boolean cast, boolean relations) throws Exception{
        return new TableIterator<>(this, true, extended, cast, relations);
    }

    public Iterator<Map<String, Object>> keyedIterator(boolean extended, boolean cast, boolean relations) throws Exception{
        return new TableIterator<Map<String, Object>>(this, true, extended, cast, relations);
    }

Replace Generic With Diamond TableIterator<Map<String,Object>> with TableIterator<> in method public keyedIterator(extended boolean, cast boolean, relations boolean) : Iterator<Map<String,Object>> from class io.frictionlessdata.tableschema.Table


    public Iterator<Object[]> iterator() throws Exception{
       return new TableIterator<>(this, false, false, true, false);
    }

    public Iterator<Object[]> iterator() throws Exception{
       return new TableIterator<Object[]>(this);
    }

Replace Generic With Diamond TableIterator<Object[]> with TableIterator<> in method public iterator() : Iterator<Object[]> from class io.frictionlessdata.tableschema.Table


    public Iterator<Object[]> iterator(boolean keyed, boolean extended, boolean cast, boolean relations) throws Exception{
       return new TableIterator<>(this, keyed, extended, cast, relations);
    }

    public Iterator<Object[]> iterator(boolean keyed, boolean extended, boolean cast, boolean relations) throws Exception{
       return new TableIterator<Object[]>(this, keyed, extended, cast, relations);
    }

Replace Generic With Diamond TableIterator<Object[]> with TableIterator<> in method public iterator(keyed boolean, extended boolean, cast boolean, relations boolean) : Iterator<Object[]> from class io.frictionlessdata.tableschema.Table


    /**
     * We use a map to keep track the inferred type counts for each field.
     * Once we are done inferring, we settle for the type with that was inferred the most for the same field.
     * @param map
     * @return
     */
    private TreeMap<String, Integer> sortMapByValue(Map<String, Integer> map){
        Comparator<String> comparator = new MapValueComparator(map);
        TreeMap<String, Integer> result = new TreeMap<>(comparator);
        result.putAll(map);

        return result;
    }

    /**
     * We use a map to keep track the inferred type counts for each field.
     * Once we are done inferring, we settle for the type with that was inferred the most for the same field.
     * @param map
     * @return
     */
    private TreeMap<String, Integer> sortMapByValue(Map<String, Integer> map){
        Comparator<String> comparator = new MapValueComparator(map);
        TreeMap<String, Integer> result = new TreeMap<String, Integer>(comparator);
        result.putAll(map);

        return result;
    }

Replace Generic With Diamond TreeMap<String,Integer> with TreeMap<> in method private sortMapByValue(map Map<String,Integer>) : TreeMap<String,Integer> from class io.frictionlessdata.tableschema.TypeInferrer


        /**
         * Attempts to get the public key for verification of the signature using the configured {@link
         * ICertificateFinder}.
         *
         * {@inheritDoc}
         */
        @Override
		public KeySelectorResult select(final KeyInfo keyInfo, final KeySelector.Purpose purpose,
        								final AlgorithmMethod method, final XMLCryptoContext context)
    																					throws KeySelectorException {
        	this.certificate = clientConfig.getCertificateFinder().findCertificate(keyInfo, method, context);
        	if (this.certificate == null)
        		throw new KeySelectorException("No (usable) Certificate found!");
        	else
                return () -> certificate.getPublicKey();
        }

        /**
         * Attempts to get the public key for verification of the signature using the configured {@link
         * ICertificateFinder}.
         *
         * {@inheritDoc}
         */
        @Override
		public KeySelectorResult select(final KeyInfo keyInfo, final KeySelector.Purpose purpose,
        								final AlgorithmMethod method, final XMLCryptoContext context)
    																					throws KeySelectorException {
        	this.certificate = clientConfig.getCertificateFinder().findCertificate(keyInfo, method, context);
        	if (this.certificate == null)
        		throw new KeySelectorException("No (usable) Certificate found!");
        	else
                return new KeySelectorResult() {
        											@Override
        											public Key getKey() {
    								                            return certificate.getPublicKey();
    								                };
                    							};
        }

Replace Anonymous With Lambda org.holodeckb2b.bdxr.smp.client.impl.SMPResultReader.CertificateKeySelector.select.new KeySelectorResult with () -> certificate.getPublicKey() in method public select(keyInfo KeyInfo, purpose KeySelector.Purpose, method AlgorithmMethod, context XMLCryptoContext) : KeySelectorResult from class org.holodeckb2b.bdxr.smp.client.impl.SMPResultReader.CertificateKeySelector


	@Test
	void testUntrustedSignedXML() throws Exception {
		Path respDoc = TestUtils.getTestResource("signed_result.xml");
		ServiceMetadataImpl smd = new ServiceMetadataImpl(new IdentifierImpl("P_ID_1"), null, null, null);

		SMPClientConfig cfg = new SMPClientConfig();
		cfg.addProcessor(new MockResultProcessor(TEST_XML_NS, respDoc, smd));
		cfg.setTrustValidator((X509Certificate certificate) -> false);

		try (FileInputStream fis = new FileInputStream(respDoc.toFile())) {
			SMPQueryException ex = assertThrows(SMPQueryException.class,
																() -> new SMPResultReader(cfg).handleResponse(fis));
			assertTrue(ex.getMessage().contains("not trusted"));
		}
	}

	@Test
	void testUntrustedSignedXML() throws Exception {
		Path respDoc = TestUtils.getTestResource("signed_result.xml");
		ServiceMetadataImpl smd = new ServiceMetadataImpl(new IdentifierImpl("P_ID_1"), null, null, null);

		SMPClientConfig cfg = new SMPClientConfig();
		cfg.addProcessor(new MockResultProcessor(TEST_XML_NS, respDoc, smd));
		cfg.setTrustValidator(new ITrustValidator() {
			@Override
			public boolean isTrusted(X509Certificate certificate) throws SMPQueryException {
				return false;
			}
		});

		try (FileInputStream fis = new FileInputStream(respDoc.toFile())) {
			SMPQueryException ex = assertThrows(SMPQueryException.class,
																() -> new SMPResultReader(cfg).handleResponse(fis));
			assertTrue(ex.getMessage().contains("not trusted"));
		}
	}

Replace Anonymous With Lambda org.holodeckb2b.bdxr.smp.client.impl.SMPResultReaderTest.testUntrustedSignedXML.setTrustValidator.new ITrustValidator with (certificate) -> false in method package testUntrustedSignedXML() : void from class org.holodeckb2b.bdxr.smp.client.impl.SMPResultReaderTest


	public void run () {
		try (RocksDBWrapper database = new RocksDBWrapper(true, transactionsDatabaseDirectory)) {
			this.progress.start("Searching mappings...");
			this.findMapping(database);
			this.progress.done();
		} catch (IOException | ClassNotFoundException | InterruptedException | RocksDBException e) {
			throw new RuntimeException(e);
		}
	}

	public void run () {
		try {
			this.progress.start("Searching mappings...");
			this.findMapping();
			this.close();
			this.progress.done();
		} catch (IOException | ClassNotFoundException | InterruptedException e) {
			throw new RuntimeException(e);
		}
	}

Try With Resources try(RocksDBWrapper database=new RocksDBWrapper(true,transactionsDatabaseDirectory)) in method public run() : void from class it.unimi.dsi.law.FindMapping


	@Override
	public void run () {
		while (!this.stop) {
			try (WriteBatch wb = this.wbQueue.poll()) {
				if (wb == null) {
					continue;
				}

				this.digest(wb);
			} catch (RocksDBException e) {
				throw new RuntimeException(e);
			}
		}
	}

	@Override
	public void run () {
		while (true) {
			try {
				WriteBatch wb = this.wbQueue.poll();

				if (wb == null && this.stop) {
					this.progress.logger.info("No more writes to perform on the database");
					break;
				}

                if (wb == null) {
                    continue;
                }

				this.mappings.db.write(new WriteOptions(), wb);
				this.progress.logger.info("New write batch completed");
			} catch (RocksDBException e) {
				throw new RuntimeException(e);
			}
		}
	}

Try With Resources try(WriteBatch wb=this.wbQueue.poll()) in method public run() : void from class it.unimi.dsi.law.DBWriter


    public static Address transactionOutputToAddress(TransactionOutput to, NetworkParameters np) {
        try {
            Script script = to.getScriptPubKey();

            if (script.getScriptType() == null) {
                // No public keys are contained in this script.
                return null;
            }

            return script.getToAddress(np, true);
        } catch (IllegalArgumentException | ScriptException e) {
            // Non-standard address
            return null;
        }
    }

    public static Address transactionOutputToAddress(TransactionOutput to, NetworkParameters np) {
        try {
            Script script = to.getScriptPubKey();

            if (script.getScriptType() == null) {
                // No public keys are contained in this script.
                return null;
            }

            return script.getToAddress(np, true);
        } catch (IllegalArgumentException e) {
            // Non-standard address
            return null;
        } catch (ScriptException e) {
            // Address malformed

            System.out.println(to.getParentTransaction().getTxId());
            throw e;
        }
    }

Merge Catch [catch(IllegalArgumentException e), catch(ScriptException e)] to catch(IllegalArgumentException|ScriptException e) in method public transactionOutputToAddress(to TransactionOutput, np NetworkParameters) : Address from class it.unimi.dsi.law.CustomBlockchainIterator


    /**
     * Method used to observe which player chose which wizard
     * @return An HashMap containing the nickname of the Player and the Wizard chosen
     */
    public HashMap<String, WizardType> getPlayersWizardType(){
        HashMap<String, WizardType> result = new HashMap<>();
        for(Player player : players){
            result.put(player.getNickname(), player.getWizardType());
        }
        return result;
    }

    /**
     * Method used to observe which player chose which wizard
     * @return An HashMap containing the nickname of the Player and the Wizard chosen
     */
    public HashMap<String, WizardType> getPlayersWizardType(){
        HashMap<String, WizardType> result = new HashMap<String, WizardType>();
        for(Player player : players){
            result.put(player.getNickname(), player.getWizardType());
        }
        return result;
    }

Replace Generic With Diamond HashMap<String,WizardType> with HashMap<> in method public getPlayersWizardType() : HashMap<String,WizardType> from class it.polimi.ingsw.GameModel.Game


        /**
         * Method used to observe which player chose which wizard
         * @return An HashMap containing the nickname of the Player and the Wizard chosen
         */
        public HashMap<String, WizardType> getPlayersWizardType(){
            HashMap<String, WizardType> result = new HashMap<>();
            for(Player player : players){
                result.put(player.getNickname(), player.getWizardType());
            }
            return  result;
        }

        /**
         * Method used to observe which player chose which wizard
         * @return An HashMap containing the nickname of the Player and the Wizard chosen
         */
        public HashMap<String, WizardType> getPlayersWizardType(){
            HashMap<String, WizardType> result = new HashMap<String, WizardType>();
            for(Player player : players){
                result.put(player.getNickname(), player.getWizardType());
            }
            return  result;
        }


    /**
     * Test that counting influence works when IslandGroup contains multiple IslandTiles
     */
    @Test
    void countInfluence() {
        IslandGroup islandGroup = new IslandGroup(true);
        List<IslandTile> islandTiles = new ArrayList<>();
        islandTiles.add(new IslandTile(null, false, null));
        islandTiles.add(new IslandTile(null, false, null));
        islandTiles.get(0).placePawn(new Student(Color.PINK, null));
        islandTiles.get(0).placePawn(new Student(Color.PINK, null));
        islandTiles.get(0).placePawn(new Student(Color.PINK, null));
        islandTiles.get(0).placePawn(new Student(Color.PINK, null));
        islandTiles.get(0).placePawn(new Student(Color.RED, null));
        islandTiles.get(0).placePawn(new Student(Color.RED, null));
        islandTiles.get(0).placePawn(new Student(Color.RED, null));
        islandTiles.get(1).placePawn(new Student(Color.PINK, null));
        islandTiles.get(1).placePawn(new Student(Color.PINK, null));
        islandTiles.get(1).placePawn(new Student(Color.PINK, null));
        islandGroup.addIslandTilesAfter(islandTiles);
        assertTrue(islandGroup.countInfluence(Color.PINK) == 7 && islandGroup.countInfluence(Color.RED) == 3 && islandGroup.countInfluence(Color.BLUE) == 0);
    }

    /**
     * Test that counting influence works when IslandGroup contains multiple IslandTiles
     */
    @Test
    void countInfluence() {
        IslandGroup islandGroup = new IslandGroup(true);
        List<IslandTile> islandTiles = new ArrayList<IslandTile>();
        islandTiles.add(new IslandTile(null, false, null));
        islandTiles.add(new IslandTile(null, false, null));
        islandTiles.get(0).placePawn(new Student(Color.PINK, null));
        islandTiles.get(0).placePawn(new Student(Color.PINK, null));
        islandTiles.get(0).placePawn(new Student(Color.PINK, null));
        islandTiles.get(0).placePawn(new Student(Color.PINK, null));
        islandTiles.get(0).placePawn(new Student(Color.RED, null));
        islandTiles.get(0).placePawn(new Student(Color.RED, null));
        islandTiles.get(0).placePawn(new Student(Color.RED, null));
        islandTiles.get(1).placePawn(new Student(Color.PINK, null));
        islandTiles.get(1).placePawn(new Student(Color.PINK, null));
        islandTiles.get(1).placePawn(new Student(Color.PINK, null));
        islandGroup.addIslandTilesAfter(islandTiles);
        assertTrue(islandGroup.countInfluence(Color.PINK) == 7 && islandGroup.countInfluence(Color.RED) == 3 && islandGroup.countInfluence(Color.BLUE) == 0);
    }

Replace Generic With Diamond ArrayList<IslandTile> with ArrayList<> in method package countInfluence() : void from class it.polimi.ingsw.GameModel.Board.Archipelago.IslandGroupTest


    /**
     * Adds IslandTile to an IslandGroup and tests if methods returns true
     */
    @Test
    void hasIslandTile() {
        IslandGroup islandGroup = new IslandGroup(true);
        List<IslandTile> islandTiles = new ArrayList<>();
        islandTiles.add(new IslandTile(null, false,null ));
        islandGroup.addIslandTilesBefore(islandTiles);
        assertTrue(islandGroup.hasIslandTile(islandTiles.get(0)));
    }

    /**
     * Adds IslandTile to an IslandGroup and tests if methods returns true
     */
    @Test
    void hasIslandTile() {
        IslandGroup islandGroup = new IslandGroup(true);
        List<IslandTile> islandTiles = new ArrayList<IslandTile>();
        islandTiles.add(new IslandTile(null, false,null ));
        islandGroup.addIslandTilesBefore(islandTiles);
        assertTrue(islandGroup.hasIslandTile(islandTiles.get(0)));
    }

Replace Generic With Diamond ArrayList<IslandTile> with ArrayList<> in method package hasIslandTile() : void from class it.polimi.ingsw.GameModel.Board.Archipelago.IslandGroupTest


    /**
     * Tests that exception is thrown if inconsistent teams in a 3 player game
     */
    @Test
    void createException3Players() {
        Bag bag = new Bag();
        bag.fillRemaining();
        GameConfig gameConfig = new GameConfig(3);
        gameConfig.getPlayerConfig().setBag(bag);

        HashMap<String, TowerColor> teamConfiguration = new LinkedHashMap<>();
        teamConfiguration.put("Simo", TowerColor.BLACK);
        teamConfiguration.put("Greg", TowerColor.GREY);
        teamConfiguration.put("Pirovano", TowerColor.BLACK);
        teamConfiguration.put("Ceruti", TowerColor.GREY);
        TeamManager teamManager = new TeamManager();

        assertThrows(IllegalArgumentException.class, () -> teamManager.create(gameConfig, teamConfiguration));

    }

    /**
     * Tests that exception is thrown if inconsistent teams in a 3 player game
     */
    @Test
    void createException3Players() {
        Bag bag = new Bag();
        bag.fillRemaining();
        GameConfig gameConfig = new GameConfig(3);
        gameConfig.getPlayerConfig().setBag(bag);

        HashMap<String, TowerColor> teamConfiguration = new LinkedHashMap<String, TowerColor>();
        teamConfiguration.put("Simo", TowerColor.BLACK);
        teamConfiguration.put("Greg", TowerColor.GREY);
        teamConfiguration.put("Pirovano", TowerColor.BLACK);
        teamConfiguration.put("Ceruti", TowerColor.GREY);
        TeamManager teamManager = new TeamManager();

        assertThrows(IllegalArgumentException.class, () -> teamManager.create(gameConfig, teamConfiguration));

    }

Replace Generic With Diamond LinkedHashMap<String,TowerColor> with LinkedHashMap<> in method package createException3Players() : void from class it.polimi.ingsw.GameModel.Board.Player.TeamManagerTest


    /**
     * Tests that exception is thrown if inconsistent teams in a 4 player game
     */
    @Test
    void createException4Players() {
        Bag bag = new Bag();
        bag.fillRemaining();
        GameConfig gameConfig = new GameConfig(4);
        gameConfig.getPlayerConfig().setBag(bag);

        HashMap<String, TowerColor> teamConfiguration = new LinkedHashMap<>();
        teamConfiguration.put("Simo", TowerColor.BLACK);
        teamConfiguration.put("Greg", TowerColor.BLACK);
        teamConfiguration.put("Pirovano", TowerColor.BLACK);
        teamConfiguration.put("Ceruti", TowerColor.WHITE);
        TeamManager teamManager = new TeamManager();

        assertThrows(IllegalArgumentException.class, () -> teamManager.create(gameConfig, teamConfiguration));

    }

    /**
     * Tests that exception is thrown if inconsistent teams in a 4 player game
     */
    @Test
    void createException4Players() {
        Bag bag = new Bag();
        bag.fillRemaining();
        GameConfig gameConfig = new GameConfig(4);
        gameConfig.getPlayerConfig().setBag(bag);

        HashMap<String, TowerColor> teamConfiguration = new LinkedHashMap<String, TowerColor>();
        teamConfiguration.put("Simo", TowerColor.BLACK);
        teamConfiguration.put("Greg", TowerColor.BLACK);
        teamConfiguration.put("Pirovano", TowerColor.BLACK);
        teamConfiguration.put("Ceruti", TowerColor.WHITE);
        TeamManager teamManager = new TeamManager();

        assertThrows(IllegalArgumentException.class, () -> teamManager.create(gameConfig, teamConfiguration));

    }

Replace Generic With Diamond LinkedHashMap<String,TowerColor> with LinkedHashMap<> in method package createException4Players() : void from class it.polimi.ingsw.GameModel.Board.Player.TeamManagerTest


    /**
     * Creates the Archipelago and creates 12 IslandGroups,
     */
    public Archipelago() {
        islandGroups = new ArrayList<>();
        int startingIsland = selectStartingIsland();
        for (int i = 0; i < 12; i++) {
            islandGroups.add(new IslandGroup(i==startingIsland));
        }
        moveMotherNatureStrategy = new MoveMotherNatureStrategyStandard();
        resolveStrategy = new ResolveStrategyStandard();
    }

    /**
     * Creates the Archipelago and creates 12 IslandGroups,
     */
    public Archipelago() {
        islandGroups = new ArrayList<IslandGroup>();
        int startingIsland = selectStartingIsland();
        for (int i = 0; i < 12; i++) {
            islandGroups.add(new IslandGroup(i==startingIsland));
        }
        moveMotherNatureStrategy = new MoveMotherNatureStrategyStandard();
        resolveStrategy = new ResolveStrategyStandard();
    }

Replace Generic With Diamond ArrayList<IslandGroup> with ArrayList<> in method public Archipelago() from class it.polimi.ingsw.GameModel.Board.Archipelago.Archipelago


    public IslandGroup(boolean isStarting){
        this.islandTiles = new ArrayList<>();
        this.islandTiles.add(new IslandTile(null, isStarting, this)); //CHECKME: player null replace with "neutral"?
    }

    public IslandGroup(boolean isStarting){
        this.islandTiles = new ArrayList<IslandTile>();
        this.islandTiles.add(new IslandTile(null, isStarting, this)); //CHECKME: player null replace with "neutral"?
    }

Replace Generic With Diamond ArrayList<IslandTile> with ArrayList<> in method public IslandGroup(isStarting boolean) from class it.polimi.ingsw.GameModel.Board.Archipelago.IslandGroup


    /**
     * Creates PawnContainer with owner and maxPawns
     * @param player the owner of the container
     * @param maxPawns the maximum number of pawns the container can hold
     */
    public PawnContainer(Player player, int maxPawns) {
        super(player);
        this.pawns = new ArrayList<>();
        this.maxPawns = maxPawns;
    }

    /**
     * Creates PawnContainer with owner and maxPawns
     * @param player the owner of the container
     * @param maxPawns the maximum number of pawns the container can hold
     */
    public PawnContainer(Player player, int maxPawns) {
        super(player);
        this.pawns = new ArrayList<T>();
        this.maxPawns = maxPawns;
    }

Replace Generic With Diamond ArrayList<T> with ArrayList<> in method public PawnContainer(player Player, maxPawns int) from class it.polimi.ingsw.GameModel.BoardElements.PawnContainer


    /** Creates a new instance of MACAddressesTable
     * @param timeout seconds
     */
    public MACAddressesTable(int timeout) {
        table = new ConcurrentHashMap<>();
        this.timeout = timeout;
    }

    /** Creates a new instance of MACAddressesTable
     * @param timeout seconds
     */
    public MACAddressesTable(int timeout) {
        table = new HashMap<MACAddress, MappedPort>();
        this.timeout = timeout;
    }

Replace Generic With Diamond HashMap<MACAddress,MappedPort> with ConcurrentHashMap<> in method public MACAddressesTable(timeout int) from class org.netsimulator.net.MACAddressesTable


    /**
     * @return true if the app is running within a docker container, false otherwise
     */
    public boolean isDocker() {
        boolean isDocker = false;
        try (Stream<String> lines = Files.lines(Paths.get(CGROUP_FILE))){
            isDocker = lines.map(line ->
                    line.matches(".*/docker.*")).reduce(false, (first, found) -> found || first);
        } catch (IOException e) {
            // not linux?
        }
        return isDocker;
    }

    /**
     * @return true if the app is running within a docker container, false otherwise
     */
    public boolean isDocker() {
        boolean isDocker = false;
        try {
            isDocker = Files.lines(Paths.get(CGROUP_FILE)).map(line ->
                    line.matches(".*/docker.*")).reduce(false, (first, found) -> found || first);
        } catch (IOException e) {
            // not linux?
        }
        return isDocker;
    }

Try With Resources try(Stream<String> lines=Files.lines(Paths.get(CGROUP_FILE))) in method public isDocker() : boolean from class com.garyclayburg.upbanner.WhatsUpProbes


    /**
     * @return true if the app is running within a kubernetes environment, false otherwise
     */
    public boolean isKubernetes() {
        boolean isKubernetes = false;
        try (Stream<String> lines = Files.lines(Paths.get(CGROUP_FILE))){
            //todo is this consistent with https://docs.spring.io/spring-boot/docs/current/reference/html/deployment.html#cloud-deployment-kubernetes ?

            isKubernetes = lines.map(line ->
                    line.matches(".*/kubepod.*")).reduce(false, (first, found) -> found || first);
        } catch (IOException e) {
            // not linux?
        }
        return isKubernetes;
    }

    /**
     * @return true if the app is running within a kubernetes environment, false otherwise
     */
    public boolean isKubernetes() {
        boolean isKubernetes = false;
        try {
            //todo is this consistent with https://docs.spring.io/spring-boot/docs/current/reference/html/deployment.html#cloud-deployment-kubernetes ?
            isKubernetes = Files.lines(Paths.get(CGROUP_FILE)).map(line ->
                    line.matches(".*/kubepod.*")).reduce(false, (first, found) -> found || first);
        } catch (IOException e) {
            // not linux?
        }
        return isKubernetes;
    }

Try With Resources try(Stream<String> lines=Files.lines(Paths.get(CGROUP_FILE))) in method public isKubernetes() : boolean from class com.garyclayburg.upbanner.WhatsUpProbes


    /**
     * Would be setter that returns a {@link ExpressionFunctionParameter} with the given {@link ExpressionFunctionParameterName}.
     */
    public ExpressionFunctionParameter<T> setName(final ExpressionFunctionParameterName name) {
        Objects.requireNonNull(name, "name");

        return this.name.equals(name) ?
                this :
                new ExpressionFunctionParameter<>(
                        name,
                        this.type,
                        this.cardinality,
                        this.typeParameters,
                        this.kinds
                );
    }

    /**
     * Would be setter that returns a {@link ExpressionFunctionParameter} with the given {@link ExpressionFunctionParameterName}.
     */
    public ExpressionFunctionParameter<T> setName(final ExpressionFunctionParameterName name) {
        Objects.requireNonNull(name, "name");

        return this.name.equals(name) ?
                this :
                new ExpressionFunctionParameter<T>(
                        name,
                        this.type,
                        this.cardinality,
                        this.typeParameters,
                        this.kinds
                );
    }

Replace Generic With Diamond ExpressionFunctionParameter<T> with ExpressionFunctionParameter<> in method public setName(name ExpressionFunctionParameterName) : ExpressionFunctionParameter<T> from class walkingkooka.tree.expression.function.ExpressionFunctionParameter


    @Test
    public void testApplyAndCheck() {
        final List<Object> parameters = Lists.of(true, 1, "***parameters3***");
        final Object expected = "**123**";

        new ExpressionFunctionTesting<>() {

            @Override
            public ExpressionFunction<Object, ExpressionEvaluationContext> createBiFunction() {
                return new FakeExpressionFunction<>() {
                    @Override
                    public Object apply(final List<Object> p,
                                        final ExpressionEvaluationContext c) {
                        checkEquals(parameters, p);
                        checkEquals(CONTEXT, c);
                        return expected;
                    }
                };
            }

            @Override
            public int minimumParameterCount() {
                return 1;
            }

            @Override
            public ExpressionEvaluationContext createContext() {
                return CONTEXT;
            }

            @Override
            public Class<ExpressionFunction<Object, ExpressionEvaluationContext>> type() {
                throw new UnsupportedOperationException();
            }
        }.applyAndCheck(parameters, expected);
    }

    @Test
    public void testApplyAndCheck() {
        final List<Object> parameters = Lists.of(true, 1, "***parameters3***");
        final Object expected = "**123**";

        new ExpressionFunctionTesting<ExpressionFunction<Object, ExpressionEvaluationContext>, Object, ExpressionEvaluationContext>() {

            @Override
            public ExpressionFunction<Object, ExpressionEvaluationContext> createBiFunction() {
                return new FakeExpressionFunction<>() {
                    @Override
                    public Object apply(final List<Object> p,
                                        final ExpressionEvaluationContext c) {
                        checkEquals(parameters, p);
                        checkEquals(CONTEXT, c);
                        return expected;
                    }
                };
            }

            @Override
            public int minimumParameterCount() {
                return 1;
            }

            @Override
            public ExpressionEvaluationContext createContext() {
                return CONTEXT;
            }

            @Override
            public Class<ExpressionFunction<Object, ExpressionEvaluationContext>> type() {
                throw new UnsupportedOperationException();
            }
        }.applyAndCheck(parameters, expected);
    }

Replace Generic With Diamond ExpressionFunctionTesting<ExpressionFunction<Object,ExpressionEvaluationContext>,Object,ExpressionEvaluationContext> with ExpressionFunctionTesting<> in method public testApplyAndCheck() : void from class walkingkooka.tree.expression.function.ExpressionFunctionTestingTest


            @Override
            public ExpressionFunction<?, ExpressionEvaluationContext> function(final FunctionExpressionName name) {
                checkEquals(FUNCTION_NAME, name, "namedFunction name");

                return new FakeExpressionFunction<>() {
                    @Override
                    public Object apply(final List<Object> parameters,
                                        final ExpressionEvaluationContext context) {
                        return functionValue;
                    }

                    @Override
                    public List<ExpressionFunctionParameter<?>> parameters(final int count) {
                        throw new UnsupportedOperationException();
                    }
                };
            }

            @Override
            public ExpressionFunction<?, ExpressionEvaluationContext> function(final FunctionExpressionName name) {
                checkEquals(name("fx"), name, "namedFunction name");

                return new FakeExpressionFunction<Object, ExpressionEvaluationContext>() {
                    @Override
                    public Object apply(final List<Object> parameters,
                                        final ExpressionEvaluationContext context) {
                        return functionValue;
                    }

                    @Override
                    public List<ExpressionFunctionParameter<?>> parameters(final int count) {
                        throw new UnsupportedOperationException();
                    }
                };
            }

Replace Generic With Diamond FakeExpressionFunction<Object,ExpressionEvaluationContext> with FakeExpressionFunction<> in method public function(name FunctionExpressionName) : ExpressionFunction<?,ExpressionEvaluationContext> from class walkingkooka.tree.expression.CallExpressionTest.context.new FakeExpressionEvaluationContext


    private ExpressionEvaluationContext context(final String functionValue) {
        final ExpressionEvaluationContext context = context();

        return new FakeExpressionEvaluationContext() {
            @Override
            public ExpressionFunction<?, ExpressionEvaluationContext> function(final FunctionExpressionName name) {
                checkEquals(FUNCTION_NAME, name, "namedFunction name");

                return new FakeExpressionFunction<>() {
                    @Override
                    public Object apply(final List<Object> parameters,
                                        final ExpressionEvaluationContext context) {
                        return functionValue;
                    }

                    @Override
                    public List<ExpressionFunctionParameter<?>> parameters(final int count) {
                        throw new UnsupportedOperationException();
                    }
                };
            }

            @Override
            public Object evaluate(final FunctionExpressionName name,
                                   final List<Object> parameters) {
                return this.function(name)
                        .apply(parameters, this);
            }

            @Override
            public MathContext mathContext() {
                return context.mathContext();
            }

            @Override
            public <T> Either<T, String> convert(final Object value, final Class<T> target) {
                return context.convert(value, target);
            }
        };
    }

    private ExpressionEvaluationContext context(final String functionValue) {
        final ExpressionEvaluationContext context = context();

        return new FakeExpressionEvaluationContext() {
            @Override
            public ExpressionFunction<?, ExpressionEvaluationContext> function(final FunctionExpressionName name) {
                checkEquals(name("fx"), name, "namedFunction name");

                return new FakeExpressionFunction<Object, ExpressionEvaluationContext>() {
                    @Override
                    public Object apply(final List<Object> parameters,
                                        final ExpressionEvaluationContext context) {
                        return functionValue;
                    }

                    @Override
                    public List<ExpressionFunctionParameter<?>> parameters(final int count) {
                        throw new UnsupportedOperationException();
                    }
                };
            }

            @Override
            public Object evaluate(final FunctionExpressionName name,
                                   final List<Object> parameters) {
                return this.function(name)
                        .apply(parameters, this);
            }

            @Override
            public MathContext mathContext() {
                return context.mathContext();
            }

            @Override
            public <T> Either<T, String> convert(final Object value, final Class<T> target) {
                return context.convert(value, target);
            }
        };
    }

Replace Generic With Diamond FakeExpressionFunction<Object,ExpressionEvaluationContext> with FakeExpressionFunction<> in method private context(functionValue String) : ExpressionEvaluationContext from class walkingkooka.tree.expression.CallExpressionTest


    @Test
    public void testEvaluateFunctionThrowsExceptionTranslated() {
        final ExpressionNumberKind kind = ExpressionNumberKind.DOUBLE;

        final FunctionExpressionName name = FunctionExpressionName.with("test123");

        this.evaluateAndCheck(
                BasicExpressionEvaluationContext.with(
                                kind,
                                (n) -> {
                                    return new FakeExpressionFunction<>() {
                                        @Override
                                        public Object apply(final List<Object> objects,
                                                            final ExpressionEvaluationContext context) {
                                            throw new UnsupportedOperationException("Thrown123");
                                        }

                                        @Override
                                        public FunctionExpressionName name() {
                                            return name;
                                        }

                                        @Override
                                        public List<ExpressionFunctionParameter<?>> parameters(final int count) {
                                            return ExpressionFunctionParameter.EMPTY;
                                        }
                                    };
                                },
                                (r) -> "@@@" + r.getMessage(),
                                (r) -> {
                                    throw new UnsupportedOperationException();
                                },
                                (r) -> {
                                    throw new UnsupportedOperationException();
                                },
                                CASE_SENSITIVITY,
                                new FakeConverterContext() {
                                    @Override
                                    public <T> Either<T, String> convert(final Object value,
                                                                         final Class<T> target) {
                                        return Cast.to(
                                                Either.left(value)
                                        );
                                    }
                                }
                ),
                name,
                Lists.empty(),
                "@@@Thrown123"
        );
    }

    @Test
    public void testEvaluateFunctionThrowsExceptionTranslated() {
        final ExpressionNumberKind kind = ExpressionNumberKind.DOUBLE;

        final FunctionExpressionName name = FunctionExpressionName.with("test123");

        this.evaluateAndCheck(
                BasicExpressionEvaluationContext.with(
                                kind,
                                (n) -> {
                                    return new FakeExpressionFunction<>() {
                                        @Override
                                        public Object apply(final List<Object> objects,
                                                            final ExpressionEvaluationContext context) {
                                            throw new UnsupportedOperationException("Thrown123");
                                        }

                                        @Override
                                        public FunctionExpressionName name() {
                                            return name;
                                        }

                                        @Override
                                        public List<ExpressionFunctionParameter<?>> parameters(final int count) {
                                            return ExpressionFunctionParameter.EMPTY;
                                        }

                                        public Set<ExpressionFunctionKind> kinds() {
                                            return Sets.empty();
                                        }
                                    };
                                },
                                (r) -> "@@@" + r.getMessage(),
                                (r) -> {
                                    throw new UnsupportedOperationException();
                                },
                                (r) -> {
                                    throw new UnsupportedOperationException();
                                },
                                CASE_SENSITIVITY,
                                new FakeConverterContext() {
                                    @Override
                                    public <T> Either<T, String> convert(final Object value,
                                                                         final Class<T> target) {
                                        return Cast.to(
                                                Either.left(value)
                                        );
                                    }
                                }
                ),
                name,
                Lists.empty(),
                "@@@Thrown123"
        );
    }

Replace Anonymous With Lambda walkingkooka.tree.expression.BasicExpressionEvaluationContextTest.testEvaluateFunctionThrowsExceptionTranslated.evaluateAndCheck.with.new FakeConverterContext with (n) -> {return new FakeExpressionFunction<>(){ in method public testEvaluateFunctionThrowsExceptionTranslated() : void from class walkingkooka.tree.expression.BasicExpressionEvaluationContextTest


    @Test
    public void testEvaluateFunctionThrowsExceptionTranslated() {
        final ExpressionNumberKind kind = ExpressionNumberKind.DOUBLE;

        final FunctionExpressionName name = FunctionExpressionName.with("test123");

        this.evaluateAndCheck(
                BasicExpressionEvaluationContext.with(
                                kind,
                                (n) -> {
                                    return new FakeExpressionFunction<>() {
                                        @Override
                                        public Object apply(final List<Object> objects,
                                                            final ExpressionEvaluationContext context) {
                                            throw new UnsupportedOperationException("Thrown123");
                                        }

                                        @Override
                                        public FunctionExpressionName name() {
                                            return name;
                                        }

                                        @Override
                                        public List<ExpressionFunctionParameter<?>> parameters(final int count) {
                                            return ExpressionFunctionParameter.EMPTY;
                                        }

                                        public Set<ExpressionFunctionKind> kinds() {
                                            return Sets.empty();
                                        }
                                    };
                                },
                                (r) -> "@@@" + r.getMessage(),
                                (r) -> {
                                    throw new UnsupportedOperationException();
                                },
                                (r) -> {
                                    throw new UnsupportedOperationException();
                                },
                                CASE_SENSITIVITY,
                                new FakeConverterContext() {
                                    @Override
                                    public <T> Either<T, String> convert(final Object value,
                                                                         final Class<T> target) {
                                        return Cast.to(
                                                Either.left(value)
                                        );
                                    }
                                }
                ),
                name,
                Lists.empty(),
                "@@@Thrown123"
        );
    }

    @Test
    public void testEvaluateFunctionThrowsExceptionTranslated() {
        final ExpressionNumberKind kind = ExpressionNumberKind.DOUBLE;

        final FunctionExpressionName name = FunctionExpressionName.with("test123");

        this.evaluateAndCheck(
                BasicExpressionEvaluationContext.with(
                                kind,
                                (n) -> {
                                    return new FakeExpressionFunction<>() {
                                        @Override
                                        public Object apply(final List<Object> objects,
                                                            final ExpressionEvaluationContext context) {
                                            throw new UnsupportedOperationException("Thrown123");
                                        }

                                        @Override
                                        public FunctionExpressionName name() {
                                            return name;
                                        }

                                        @Override
                                        public List<ExpressionFunctionParameter<?>> parameters() {
                                            return ExpressionFunctionParameter.EMPTY;
                                        }

                                        public Set<ExpressionFunctionKind> kinds() {
                                            return Sets.empty();
                                        }
                                    };
                                },
                                (r) -> "@@@" + r.getMessage(),
                                (r) -> {
                                    throw new UnsupportedOperationException();
                                },
                                (r) -> {
                                    throw new UnsupportedOperationException();
                                },
                                CASE_SENSITIVITY,
                                new FakeConverterContext() {
                                    @Override
                                    public <T> Either<T, String> convert(final Object value,
                                                                         final Class<T> target) {
                                        return Cast.to(
                                                Either.left(value)
                                        );
                                    }
                                }
                ),
                name,
                Lists.empty(),
                "@@@Thrown123"
        );
    }