Example usage for java.util.function Consumer accept

List of usage examples for java.util.function Consumer accept

Introduction

In this page you can find the example usage for java.util.function Consumer accept.

Prototype

void accept(T t);

Source Link

Document

Performs this operation on the given argument.

Usage

From source file:org.elasticsearch.client.RequestConvertersTests.java

private static void setRandomIndicesOptions(Consumer<IndicesOptions> setter, Supplier<IndicesOptions> getter,
        Map<String, String> expectedParams) {

    if (randomBoolean()) {
        setter.accept(
                IndicesOptions.fromOptions(randomBoolean(), randomBoolean(), randomBoolean(), randomBoolean()));
    }//  w  ww .j  a va2  s.  co  m
    expectedParams.put("ignore_unavailable", Boolean.toString(getter.get().ignoreUnavailable()));
    expectedParams.put("allow_no_indices", Boolean.toString(getter.get().allowNoIndices()));
    if (getter.get().expandWildcardsOpen() && getter.get().expandWildcardsClosed()) {
        expectedParams.put("expand_wildcards", "open,closed");
    } else if (getter.get().expandWildcardsOpen()) {
        expectedParams.put("expand_wildcards", "open");
    } else if (getter.get().expandWildcardsClosed()) {
        expectedParams.put("expand_wildcards", "closed");
    } else {
        expectedParams.put("expand_wildcards", "none");
    }
}

From source file:org.apache.hadoop.hbase.client.AsyncRpcRetryingCaller.java

protected void onError(Throwable error, Supplier<String> errMsg, Consumer<Throwable> updateCachedLocation) {
    error = translateException(error);/* w ww  .j  a v a2 s  . c om*/
    if (tries > startLogErrorsCnt) {
        LOG.warn(errMsg.get() + ", tries = " + tries + ", maxAttempts = " + maxAttempts + ", timeout = "
                + TimeUnit.NANOSECONDS.toMillis(operationTimeoutNs) + " ms, time elapsed = " + elapsedMs()
                + " ms", error);
    }
    RetriesExhaustedException.ThrowableWithExtraContext qt = new RetriesExhaustedException.ThrowableWithExtraContext(
            error, EnvironmentEdgeManager.currentTime(), "");
    exceptions.add(qt);
    if (error instanceof DoNotRetryIOException || tries >= maxAttempts) {
        completeExceptionally();
        return;
    }
    long delayNs;
    if (operationTimeoutNs > 0) {
        long maxDelayNs = remainingTimeNs() - SLEEP_DELTA_NS;
        if (maxDelayNs <= 0) {
            completeExceptionally();
            return;
        }
        delayNs = Math.min(maxDelayNs, getPauseTime(pauseNs, tries - 1));
    } else {
        delayNs = getPauseTime(pauseNs, tries - 1);
    }
    updateCachedLocation.accept(error);
    tries++;
    retryTimer.newTimeout(t -> doCall(), delayNs, TimeUnit.NANOSECONDS);
}

From source file:com.evolveum.midpoint.prism.schema.DomToSchemaPostProcessor.java

private void applyToDeclarations(XSComponent component, Consumer<XSDeclaration> consumer) {
    if (component == null) {
        return;//from  ww w  .  ja  v  a 2 s.  c  o m
    }
    if (component instanceof XSDeclaration) {
        consumer.accept((XSDeclaration) component);
    }
    // recursion (if needed)
    if (component instanceof XSParticle) {
        applyToDeclarations(((XSParticle) component).getTerm(), consumer);
    } else if (component instanceof XSModelGroup) {
        for (XSParticle particle : ((XSModelGroup) component).getChildren()) {
            applyToDeclarations(particle, consumer);
        }
    } else if (component instanceof XSModelGroupDecl) {
        applyToDeclarations(((XSModelGroupDecl) component).getModelGroup(), consumer);
    }
}

From source file:org.elasticsearch.client.RequestConvertersTests.java

private static void setRandomVersionType(Consumer<VersionType> setter, Map<String, String> expectedParams) {
    if (randomBoolean()) {
        VersionType versionType = randomFrom(VersionType.values());
        setter.accept(versionType);
        if (versionType != VersionType.INTERNAL) {
            expectedParams.put("version_type", versionType.name().toLowerCase(Locale.ROOT));
        }/*  ww  w.  jav  a2 s.c om*/
    }
}

From source file:org.elasticsearch.client.RequestConvertersTests.java

private static void setRandomTimeout(Consumer<String> setter, TimeValue defaultTimeout,
        Map<String, String> expectedParams) {
    if (randomBoolean()) {
        String timeout = randomTimeValue();
        setter.accept(timeout);
        expectedParams.put("timeout", timeout);
    } else {/*from w  w  w .j  a  v  a 2s . c  o m*/
        expectedParams.put("timeout", defaultTimeout.getStringRep());
    }
}

From source file:com.vmware.admiral.adapter.docker.service.DockerAdapterService.java

private void ensurePropertyExists(Consumer<Integer> callback) {
    if (retriesCount != null) {
        callback.accept(retriesCount);
    } else {/*  w  w  w  .jav  a2s  . c o  m*/
        String maxRetriesCountConfigPropPath = UriUtils.buildUriPath(ConfigurationFactoryService.SELF_LINK,
                PROVISION_CONTAINER_RETRIES_COUNT_PARAM_NAME);
        sendRequest(Operation.createGet(this, maxRetriesCountConfigPropPath).setCompletion((o, ex) -> {
            /** in case of exception the default retry count will be 3 */
            retriesCount = Integer.valueOf(3);
            if (ex == null) {
                retriesCount = Integer.valueOf(o.getBody(ConfigurationState.class).value);
            }
            callback.accept(retriesCount);
        }));
    }
}

From source file:jp.co.opentone.bsol.linkbinder.service.correspon.impl.CorresponFullTextSearchServiceImpl.java

private void handleResponse(ElasticsearchSearchResponse response,
        SearchFullTextSearchCorresponCondition condition, Consumer<FullTextSearchCorresponsResult> consumer) {
    response.records().forEach(rec -> {
        FullTextSearchCorresponsResult r = new FullTextSearchCorresponsResult();

        r.setId(idToLong(rec.getId()));/* w ww.  j ava 2  s  .c  o m*/
        if (rec.getHighlightedFragments("title").count() > 0) {
            r.setTitle(rec.getHighlightedFragments("title").collect(Collectors.joining()));
        } else {
            r.setTitle(rec.getValueAsString("title"));
        }
        r.setMdate(rec.getValueAsString("lastModified"));
        r.setWorkflowStatus(rec.getValueAsString("workflowStatus"));
        Stream<Map<String, Object>> s = rec.getValueAsStream("attachments");
        if (s != null) {
            s.forEach(a -> {
                r.setTitle(ObjectUtils.toString(a.get("name")));
                r.setAttachmentId(ObjectUtils.toString(a.get("id")));
            });
        }

        setSummaryData(condition, rec, r);

        consumer.accept(r);
    });
}

From source file:org.ovirt.api.metamodel.analyzer.ModelAnalyzer.java

private void analyzeModule(JavaClass javaClass, Consumer<Module> moduleSetter) {
    String javaName = javaClass.getPackageName();
    Name name = NameParser.parseUsingSeparator(javaName, '.');
    Module module = model.getModule(name);
    if (module == null) {
        module = new Module();
        module.setModel(model);//from   w  ww .jav a2  s.c om
        module.setName(name);
        model.addModule(module);
    }
    moduleSetter.accept(module);
}

From source file:org.commonjava.cartographer.graph.GraphResolver.java

/**
 * Resolve any variable versions in the specified root GAVs, retrieve, and if configured, discover missing parts of the relationship
 * graph. Return the {@link ViewParams} instance resulting from configuration via the given {@link AggregationOptions} and the root GAVs with
 * potential root GAV differences due to resolution of variable versions. If autoClose parameter is false, then leave the graph open for 
 * subsequent reuse./*www. ja va 2s.  co  m*/
 * <br/>
 * <b>NOTE:</b> This method assumes {@link RecipeResolver#resolve(AbstractGraphRequest)} has already been called.
 */
private void resolveGraph(final GraphDescription desc, final AbstractGraphRequest recipe,
        final Consumer<RelationshipGraph> consumer) throws CartoDataException, CartoRequestException {
    logger.info("Initial source location: '{}'", recipe.getSourceLocation());
    final URI sourceUri = sourceManager.createSourceURI(recipe.getSourceLocation().getUri());

    if (sourceUri == null) {
        throw new CartoDataException("Invalid source format: '{}'. Use the form: '{}' instead.",
                recipe.getSourceLocation(), sourceManager.getFormatHint());
    }

    if (!recipe.isResolve()) {
        final ViewParams params = new ViewParams.Builder(recipe.getWorkspaceId(), desc.rootsArray())
                .withFilter(desc.filter()).withMutator(desc.getMutatorInstance())
                .withSelections(recipe.getVersionSelections()).build();
        // ensure the graph is available.
        try {
            final RelationshipGraph graph = graphFactory.open(params, false);
            consumer.accept(graph);
        } catch (final RelationshipGraphException e) {
            throw new CartoDataException("Failed to open: %s. Reason: %s", e, params, e.getMessage());
        }

        return;
    }

    final AggregationOptions aggOptions = createAggregationOptions(recipe, desc.filter());
    final DiscoveryConfig discoveryConfig = recipe.getDiscoveryConfig();

    final List<ProjectVersionRef> specifics = new ArrayList<>();

    for (final ProjectVersionRef root : desc.getRoots()) {
        ProjectVersionRef specific = discoverer.resolveSpecificVersion(root, discoveryConfig);
        if (specific == null) {
            specific = root;
        }

        specifics.add(specific);
    }

    final ViewParams params = new ViewParams.Builder(recipe.getWorkspaceId(), specifics)
            .withFilter(aggOptions.getFilter()).withMutator(desc.getMutatorInstance())
            .withSelections(recipe.getVersionSelections()).build();

    sourceManager.activateWorkspaceSources(params, discoveryConfig.getLocations());

    try {
        final RelationshipGraph graph = graphFactory.open(params, true);
        for (final ProjectVersionRef root : specifics) {
            if (!graph.containsGraph(root) || graph.hasProjectError(root)) {
                try {
                    graph.clearProjectError(root);
                } catch (final RelationshipGraphException e) {
                    logger.error(String.format("Cannot clear project error for: %s in graph: %s. Reason: %s",
                            root, graph, e.getMessage()), e);
                    continue;
                }

                if (!aggOptions.isDiscoveryEnabled()) {
                    logger.info("Resolving direct relationships for root: {}", root);
                    final DiscoveryResult result = discoverer.discoverRelationships(root, graph,
                            discoveryConfig);
                    logger.info("Result: {} relationships",
                            (result == null ? 0 : result.getAcceptedRelationships().size()));
                }
            }
        }

        if (aggOptions.isDiscoveryEnabled()) {
            logger.info("Performing graph discovery for: {}", specifics);
            aggregator.connectIncomplete(graph, aggOptions);
        }

        consumer.accept(graph);
    } catch (final RelationshipGraphException e) {
        throw new CartoDataException("Failed to open/modify graph: {}. Reason: {}", e, params, e.getMessage());
    }
}

From source file:org.azrul.langmera.QLearningAnalytics.java

public void getCalculatedDecision(DecisionRequest req, Vertx vertx, Consumer<DecisionResponse> responseAction) {
    getDecisionPreCondition(req);/*  w  w  w.j  av  a  2  s  .  com*/
    LocalMap<String, Double> q = vertx.sharedData().getLocalMap("Q");
    String keyWithMaxVal = null;
    Double maxVal = Double.NEGATIVE_INFINITY;
    for (String k : q.keySet()) {
        if (q.get(k) > maxVal) {
            maxVal = q.get(k);
            keyWithMaxVal = k;
        }
    }
    DecisionResponse resp = null;
    if (keyWithMaxVal != null) {
        String decision = keyWithMaxVal.split(":")[1];
        resp = new DecisionResponse();
        resp.setDecisionId(req.getDecisionId());
        resp.setDecision(decision);
        resp.setQValue(maxVal);
        //save cache to be matched to feedback
        if (req != null) {
            vertx.sharedData().getLocalMap("DECISION_REQUEST").put(req.getDecisionId(), req);
        }
        if (resp != null) {
            vertx.sharedData().getLocalMap("DECISION_RESPONSE").put(req.getDecisionId(), resp);
        }
        responseAction.accept(resp);
    } else {
        getRandomDecision(req, vertx, responseAction);
    }

}