Example usage for java.util.function Supplier get

List of usage examples for java.util.function Supplier get

Introduction

In this page you can find the example usage for java.util.function Supplier get.

Prototype

T get();

Source Link

Document

Gets a result.

Usage

From source file:org.apache.nifi.processors.standard.Wait.java

@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {

    final ComponentLog logger = getLogger();

    // Signal id is computed from attribute 'RELEASE_SIGNAL_IDENTIFIER' with expression language support
    final PropertyValue signalIdProperty = context.getProperty(RELEASE_SIGNAL_IDENTIFIER);
    final Integer bufferCount = context.getProperty(WAIT_BUFFER_COUNT).asInteger();

    final Map<Relationship, List<FlowFile>> processedFlowFiles = new HashMap<>();
    final Function<Relationship, List<FlowFile>> getFlowFilesFor = r -> processedFlowFiles.computeIfAbsent(r,
            k -> new ArrayList<>());

    final AtomicReference<String> targetSignalId = new AtomicReference<>();
    final AtomicInteger bufferedCount = new AtomicInteger(0);
    final List<FlowFile> failedFilteringFlowFiles = new ArrayList<>();
    final Supplier<FlowFileFilter.FlowFileFilterResult> acceptResultSupplier = () -> bufferedCount
            .incrementAndGet() == bufferCount ? ACCEPT_AND_TERMINATE : ACCEPT_AND_CONTINUE;
    final List<FlowFile> flowFiles = session.get(f -> {

        final String fSignalId = signalIdProperty.evaluateAttributeExpressions(f).getValue();

        // if the computed value is null, or empty, we transfer the FlowFile to failure relationship
        if (StringUtils.isBlank(fSignalId)) {
            // We can't penalize f before getting it from session, so keep it in a temporal list.
            logger.error("FlowFile {} has no attribute for given Release Signal Identifier",
                    new Object[] { f });
            failedFilteringFlowFiles.add(f);
            return ACCEPT_AND_CONTINUE;
        }//  w  w  w  .java2 s.  co m

        final String targetSignalIdStr = targetSignalId.get();
        if (targetSignalIdStr == null) {
            // This is the first one.
            targetSignalId.set(fSignalId);
            return acceptResultSupplier.get();
        }

        if (targetSignalIdStr.equals(fSignalId)) {
            return acceptResultSupplier.get();
        }

        return REJECT_AND_CONTINUE;

    });

    final String attributeCopyMode = context.getProperty(ATTRIBUTE_COPY_MODE).getValue();
    final boolean replaceOriginalAttributes = ATTRIBUTE_COPY_REPLACE.getValue().equals(attributeCopyMode);
    final AtomicReference<Signal> signalRef = new AtomicReference<>();

    final Consumer<FlowFile> transferToFailure = flowFile -> {
        flowFile = session.penalize(flowFile);
        getFlowFilesFor.apply(REL_FAILURE).add(flowFile);
    };

    final Consumer<Entry<Relationship, List<FlowFile>>> transferFlowFiles = routedFlowFiles -> {
        Relationship relationship = routedFlowFiles.getKey();

        if (REL_WAIT.equals(relationship)) {
            final String waitMode = context.getProperty(WAIT_MODE).getValue();

            if (WAIT_MODE_KEEP_IN_UPSTREAM.getValue().equals(waitMode)) {
                // Transfer to self.
                relationship = Relationship.SELF;
            }
        }

        final List<FlowFile> flowFilesWithSignalAttributes = routedFlowFiles.getValue().stream()
                .map(f -> copySignalAttributes(session, f, signalRef.get(), replaceOriginalAttributes))
                .collect(Collectors.toList());
        session.transfer(flowFilesWithSignalAttributes, relationship);
    };

    failedFilteringFlowFiles.forEach(f -> {
        flowFiles.remove(f);
        transferToFailure.accept(f);
    });

    if (flowFiles.isEmpty()) {
        // If there was nothing but failed FlowFiles while filtering, transfer those and end immediately.
        processedFlowFiles.entrySet().forEach(transferFlowFiles);
        return;
    }

    // the cache client used to interact with the distributed cache
    final AtomicDistributedMapCacheClient cache = context.getProperty(DISTRIBUTED_CACHE_SERVICE)
            .asControllerService(AtomicDistributedMapCacheClient.class);
    final WaitNotifyProtocol protocol = new WaitNotifyProtocol(cache);

    final String signalId = targetSignalId.get();
    final Signal signal;

    // get notifying signal
    try {
        signal = protocol.getSignal(signalId);
        signalRef.set(signal);
    } catch (final IOException e) {
        throw new ProcessException(String.format("Failed to get signal for %s due to %s", signalId, e), e);
    }

    String targetCounterName = null;
    long targetCount = 1;
    int releasableFlowFileCount = 1;

    final List<FlowFile> candidates = new ArrayList<>();

    for (FlowFile flowFile : flowFiles) {
        // Set wait start timestamp if it's not set yet
        String waitStartTimestamp = flowFile.getAttribute(WAIT_START_TIMESTAMP);
        if (waitStartTimestamp == null) {
            waitStartTimestamp = String.valueOf(System.currentTimeMillis());
            flowFile = session.putAttribute(flowFile, WAIT_START_TIMESTAMP, waitStartTimestamp);
        }

        long lWaitStartTimestamp;
        try {
            lWaitStartTimestamp = Long.parseLong(waitStartTimestamp);
        } catch (NumberFormatException nfe) {
            logger.error("{} has an invalid value '{}' on FlowFile {}",
                    new Object[] { WAIT_START_TIMESTAMP, waitStartTimestamp, flowFile });
            transferToFailure.accept(flowFile);
            continue;
        }

        // check for expiration
        long expirationDuration = context.getProperty(EXPIRATION_DURATION).asTimePeriod(TimeUnit.MILLISECONDS);
        long now = System.currentTimeMillis();
        if (now > (lWaitStartTimestamp + expirationDuration)) {
            logger.info("FlowFile {} expired after {}ms",
                    new Object[] { flowFile, (now - lWaitStartTimestamp) });
            getFlowFilesFor.apply(REL_EXPIRED).add(flowFile);
            continue;
        }

        // If there's no signal yet, then we don't have to evaluate target counts. Return immediately.
        if (signal == null) {
            if (logger.isDebugEnabled()) {
                logger.debug("No release signal found for {} on FlowFile {} yet",
                        new Object[] { signalId, flowFile });
            }
            getFlowFilesFor.apply(REL_WAIT).add(flowFile);
            continue;
        }

        // Fix target counter name and count from current FlowFile, if those are not set yet.
        if (candidates.isEmpty()) {
            targetCounterName = context.getProperty(SIGNAL_COUNTER_NAME).evaluateAttributeExpressions(flowFile)
                    .getValue();
            try {
                targetCount = Long.valueOf(context.getProperty(TARGET_SIGNAL_COUNT)
                        .evaluateAttributeExpressions(flowFile).getValue());
            } catch (final NumberFormatException e) {
                transferToFailure.accept(flowFile);
                logger.error("Failed to parse targetCount when processing {} due to {}",
                        new Object[] { flowFile, e }, e);
                continue;
            }
            try {
                releasableFlowFileCount = Integer.valueOf(context.getProperty(RELEASABLE_FLOWFILE_COUNT)
                        .evaluateAttributeExpressions(flowFile).getValue());
            } catch (final NumberFormatException e) {
                transferToFailure.accept(flowFile);
                logger.error("Failed to parse releasableFlowFileCount when processing {} due to {}",
                        new Object[] { flowFile, e }, e);
                continue;
            }
        }

        // FlowFile is now validated and added to candidates.
        candidates.add(flowFile);
    }

    boolean waitCompleted = false;
    boolean waitProgressed = false;
    if (signal != null && !candidates.isEmpty()) {

        if (releasableFlowFileCount > 1) {
            signal.releaseCandidatese(targetCounterName, targetCount, releasableFlowFileCount, candidates,
                    released -> getFlowFilesFor.apply(REL_SUCCESS).addAll(released),
                    waiting -> getFlowFilesFor.apply(REL_WAIT).addAll(waiting));
            waitProgressed = !getFlowFilesFor.apply(REL_SUCCESS).isEmpty();

        } else {
            // releasableFlowFileCount = 0 or 1
            boolean reachedTargetCount = StringUtils.isBlank(targetCounterName)
                    ? signal.isTotalCountReached(targetCount)
                    : signal.isCountReached(targetCounterName, targetCount);

            if (reachedTargetCount) {
                if (releasableFlowFileCount == 0) {
                    getFlowFilesFor.apply(REL_SUCCESS).addAll(candidates);
                } else {
                    // releasableFlowFileCount = 1
                    getFlowFilesFor.apply(REL_SUCCESS).add(candidates.remove(0));
                    getFlowFilesFor.apply(REL_WAIT).addAll(candidates);
                    // If releasableFlowFileCount == 0, leave signal as it is,
                    // so that any number of FlowFile can be released as long as target count condition matches.
                    waitCompleted = true;
                }
            } else {
                getFlowFilesFor.apply(REL_WAIT).addAll(candidates);
            }
        }
    }

    // Transfer FlowFiles.
    processedFlowFiles.entrySet().forEach(transferFlowFiles);

    // Update signal if needed.
    try {
        if (waitCompleted) {
            protocol.complete(signalId);
        } else if (waitProgressed) {
            protocol.replace(signal);
        }

    } catch (final IOException e) {
        session.rollback();
        throw new ProcessException(
                String.format("Unable to communicate with cache while updating %s due to %s", signalId, e), e);
    }

}

From source file:org.apache.nifi.registry.flow.mapping.NiFiRegistryFlowMapper.java

private <E extends Exception> String getIdOrThrow(final Optional<String> currentVersionedId,
        final String componentId, final Supplier<E> exceptionSupplier) throws E {
    if (currentVersionedId.isPresent()) {
        return currentVersionedId.get();
    } else {//from   w w w  .  j av a2 s . co  m
        final String resolved = versionedComponentIds.get(componentId);
        if (resolved == null) {
            throw exceptionSupplier.get();
        }

        return resolved;
    }
}

From source file:org.apache.tinkerpop.gremlin.process.traversal.step.util.Parameters.java

public <S, E> List<E> get(final Traverser.Admin<S> traverser, final Object key,
        final Supplier<E> defaultValue) {
    final List<E> values = (List<E>) this.parameters.get(key);
    if (null == values)
        return Collections.singletonList(defaultValue.get());
    final List<E> result = new ArrayList<>();
    for (final Object value : values) {
        result.add(//  ww w  .j av  a 2s.co  m
                value instanceof Traversal.Admin ? TraversalUtil.apply(traverser, (Traversal.Admin<S, E>) value)
                        : (E) value);
    }
    return result;
}

From source file:org.apache.tinkerpop.gremlin.process.traversal.step.util.Parameters.java

/**
 * Gets the value of a key and if that key isn't present returns the default value from the {@link Supplier}.
 *
 * @param key the key to retrieve//  w  w w. j  a  v a2 s  .  c  o m
 * @param defaultValue the default value generator
 */
public <E> List<E> get(final Object key, final Supplier<E> defaultValue) {
    final List<E> list = (List<E>) this.parameters.get(key);
    return (null == list) ? Collections.singletonList(defaultValue.get()) : list;

}

From source file:org.apache.tinkerpop.gremlin.server.op.AbstractEvalOpProcessor.java

/**
 * A generalized implementation of the "eval" operation.  It handles script evaluation and iteration of results
 * so as to write {@link ResponseMessage} objects down the Netty pipeline.  It also handles script timeouts,
 * iteration timeouts, metrics and building bindings.  Note that result iteration is delegated to the
 * {@link #handleIterator} method, so those extending this class could override that method for better control
 * over result iteration./*from  w ww . j a v a 2  s . co  m*/
 *
 * @param context The current Gremlin Server {@link Context}
 * @param gremlinExecutorSupplier A function that returns the {@link GremlinExecutor} to use in executing the
 *                                script evaluation.
 * @param bindingsSupplier A function that returns the {@link Bindings} to provide to the
 *                         {@link GremlinExecutor#eval} method.
 */
protected void evalOpInternal(final Context context, final Supplier<GremlinExecutor> gremlinExecutorSupplier,
        final BindingSupplier bindingsSupplier) throws OpProcessorException {
    final Timer.Context timerContext = evalOpTimer.time();
    final ChannelHandlerContext ctx = context.getChannelHandlerContext();
    final RequestMessage msg = context.getRequestMessage();
    final GremlinExecutor gremlinExecutor = gremlinExecutorSupplier.get();
    final Settings settings = context.getSettings();

    final Map<String, Object> args = msg.getArgs();

    final String script = (String) args.get(Tokens.ARGS_GREMLIN);
    final String language = args.containsKey(Tokens.ARGS_LANGUAGE) ? (String) args.get(Tokens.ARGS_LANGUAGE)
            : null;
    final Bindings bindings = new SimpleBindings();

    // sessionless requests are always transaction managed, but in-session requests are configurable.
    final boolean managedTransactionsForRequest = manageTransactions ? true
            : (Boolean) args.getOrDefault(Tokens.ARGS_MANAGE_TRANSACTION, false);

    final GremlinExecutor.LifeCycle lifeCycle = GremlinExecutor.LifeCycle.build().beforeEval(b -> {
        try {
            b.putAll(bindingsSupplier.get());
        } catch (OpProcessorException ope) {
            // this should bubble up in the GremlinExecutor properly as the RuntimeException will be
            // unwrapped and the root cause thrown
            throw new RuntimeException(ope);
        }
    }).withResult(o -> {
        final Iterator itty = IteratorUtils.asIterator(o);

        logger.debug("Preparing to iterate results from - {} - in thread [{}]", msg,
                Thread.currentThread().getName());

        try {
            handleIterator(context, itty);
        } catch (TimeoutException ex) {
            final String errorMessage = String.format(
                    "Response iteration exceeded the configured threshold for request [%s] - %s", msg,
                    ex.getMessage());
            logger.warn(errorMessage);
            ctx.writeAndFlush(ResponseMessage.build(msg).code(ResponseStatusCode.SERVER_ERROR_TIMEOUT)
                    .statusMessage(errorMessage).create());
            if (managedTransactionsForRequest)
                attemptRollback(msg, context.getGraphManager(), settings.strictTransactionManagement);
        } catch (Exception ex) {
            logger.warn(String.format("Exception processing a script on request [%s].", msg), ex);
            ctx.writeAndFlush(ResponseMessage.build(msg).code(ResponseStatusCode.SERVER_ERROR)
                    .statusMessage(ex.getMessage()).create());
            if (managedTransactionsForRequest)
                attemptRollback(msg, context.getGraphManager(), settings.strictTransactionManagement);
        }
    }).create();

    final CompletableFuture<Object> evalFuture = gremlinExecutor.eval(script, language, bindings, lifeCycle);

    evalFuture.handle((v, t) -> {
        timerContext.stop();

        if (t != null) {
            if (t instanceof OpProcessorException) {
                ctx.writeAndFlush(((OpProcessorException) t).getResponseMessage());
            } else if (t instanceof TimedInterruptTimeoutException) {
                // occurs when the TimedInterruptCustomizerProvider is in play
                final String errorMessage = String.format(
                        "A timeout occurred within the script during evaluation of [%s] - consider increasing the limit given to TimedInterruptCustomizerProvider",
                        msg);
                logger.warn(errorMessage);
                ctx.writeAndFlush(ResponseMessage.build(msg).code(ResponseStatusCode.SERVER_ERROR_TIMEOUT)
                        .statusMessage(
                                "Timeout during script evaluation triggered by TimedInterruptCustomizerProvider")
                        .create());
            } else if (t instanceof TimeoutException) {
                final String errorMessage = String.format(
                        "Response evaluation exceeded the configured threshold for request [%s] - %s", msg,
                        t.getMessage());
                logger.warn(errorMessage, t);
                ctx.writeAndFlush(ResponseMessage.build(msg).code(ResponseStatusCode.SERVER_ERROR_TIMEOUT)
                        .statusMessage(t.getMessage()).create());
            } else {
                logger.warn(String.format("Exception processing a script on request [%s].", msg), t);
                ctx.writeAndFlush(
                        ResponseMessage.build(msg).code(ResponseStatusCode.SERVER_ERROR_SCRIPT_EVALUATION)
                                .statusMessage(t.getMessage()).create());
            }
        }

        return null;
    });
}

From source file:org.ballerinalang.langserver.command.testgen.ValueSpaceGenerator.java

/**
 * Populates defined space into the templates. Random value generator will be used for the spare values.
 *
 * @param definedSpace defined value space
 * @param template     templates set//w  w w .  j  a v  a  2 s  . co m
 * @param random       random value generator
 */
public static void populateValueSpace(String[] definedSpace, String[] template, Supplier<String> random) {
    // Populate defined values
    int min = Math.min(definedSpace.length, template.length);
    IntStream.range(0, min).forEach(i -> template[i] = template[i].replace(PLACE_HOLDER, definedSpace[i]));
    // Populate random values
    int max = Math.max(min, template.length);
    IntStream.range(0, max)
            .forEach(index -> template[index] = template[index].replace(PLACE_HOLDER, random.get()));
}

From source file:org.beryx.viewreka.fxui.settings.FxPropsManager.java

public void saveSettings() {
    propsMap.forEach((key, propPair) -> {
        Serializable value = null;
        try {/* ww  w  .j av  a2  s. c o  m*/
            Supplier<?> supplier = propPair.getValue();
            value = (Serializable) supplier.get();
            if (value != null) {
                settings.setProperty(key, value);
            }
        } catch (Exception e) {
            log.warn("Cannot save value '" + value + "' of '" + key + "'", e);
        }
    });
}

From source file:org.briljantframework.array.AbstractArray.java

@Override
public void assign(Supplier<T> supplier) {
    for (int i = 0; i < size(); i++) {
        set(i, supplier.get());
    }/*from   ww  w.j  a  v  a 2  s .co m*/
}

From source file:org.briljantframework.array.AbstractBooleanArray.java

@Override
public void assign(Supplier<Boolean> supplier) {
    for (int i = 0; i < size(); i++) {
        set(i, supplier.get());
    }/* w  w  w.  j  ava  2 s .  co m*/
}

From source file:org.briljantframework.array.AbstractComplexArray.java

@Override
public ComplexArray assign(Supplier<Complex> supplier) {
    for (int i = 0; i < size(); i++) {
        set(i, supplier.get());
    }//from w  ww .  ja va2s .  co m
    return this;
}