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.oneandone.gitter.out.CSVConsumer.java

public void consume(Map<String, Map<?, ?>> perProjectResults, Function<Object, String> keyFormatter,
        Function<Object, String> valueFormatter, Supplier<Object> nullValue) throws IOException {
    List<String> projects = perProjectResults.keySet().stream().sorted().collect(Collectors.toList());
    List<String> headers = new ArrayList<>(projects);
    headers.add(0, "Key");
    CSVPrinter printer = CSVFormat.EXCEL.withHeader(headers.toArray(new String[0])).print(p);

    Set<Object> keys = perProjectResults.values().stream().flatMap(m -> m.keySet().stream())
            .collect(Collectors.toSet());
    TreeSet<Object> sortedKeys = new TreeSet<>(keys);

    sortedKeys.stream().forEachOrdered(key -> {
        List<String> values = new ArrayList<>();
        values.add(keyFormatter.apply(key));
        projects.forEach(project -> {
            Object obj = perProjectResults.get(project).get(key);
            if (obj == null) {
                obj = nullValue.get();
            }/*from   w  w w. j  a va 2 s.  c  o m*/
            Objects.requireNonNull(obj,
                    () -> "Object at key " + keyFormatter.apply(key) + " for project " + project + " is null");
            values.add(obj != null ? valueFormatter.apply(obj) : "<null>");
        });
        try {

            printer.printRecord(values);
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }
    });
}

From source file:org.onosproject.p4runtime.ctl.P4RuntimeClientImpl.java

/**
 * Executes the given task (supplier) in the gRPC context executor of this client, such that if the context is
 * cancelled (e.g. client shutdown) the RPC is automatically cancelled.
 * <p>//  w  w  w .java  2s. co  m
 * Important: Tasks submitted in parallel by different threads are forced executed sequentially.
 * <p>
 */
private <U> CompletableFuture<U> supplyInContext(Supplier<U> supplier, String opDescription) {
    return CompletableFuture.supplyAsync(() -> {
        // TODO: explore a more relaxed locking strategy.
        writeLock.lock();
        try {
            return supplier.get();
        } catch (StatusRuntimeException ex) {
            log.warn("Unable to execute {} on {}: {}", opDescription, deviceId, ex.toString());
            throw ex;
        } catch (Throwable ex) {
            log.error("Exception in client of {}, executing {}", deviceId, opDescription, ex);
            throw ex;
        } finally {
            writeLock.unlock();
        }
    }, contextExecutor);
}

From source file:org.opencb.cellbase.client.rest.CellBaseClient.java

@SuppressWarnings("unchecked")
private <T extends ParentRestClient> T getClient(String key, Supplier<T> constructorIfAbsent) {
    // Avoid concurrent modifications
    if (!clients.containsKey(key)) {
        synchronized (clients) {
            if (!clients.containsKey(key)) {
                clients.put(key, constructorIfAbsent.get());
            }//from   w  ww .  j  a  v  a2 s. co m
        }
    }
    return (T) clients.get(key);
}

From source file:org.opendaylight.controller.cluster.datastore.shardmanager.ShardManager.java

private void sendResponse(ShardInformation shardInformation, boolean doWait, boolean wantShardReady,
        final Supplier<Object> messageSupplier) {
    if (!shardInformation.isShardInitialized()
            || (wantShardReady && !shardInformation.isShardReadyWithLeaderId())) {
        if (doWait) {
            final ActorRef sender = getSender();
            final ActorRef self = self();

            Runnable replyRunnable = () -> sender.tell(messageSupplier.get(), self);

            OnShardInitialized onShardInitialized = wantShardReady ? new OnShardReady(replyRunnable)
                    : new OnShardInitialized(replyRunnable);

            shardInformation.addOnShardInitialized(onShardInitialized);

            FiniteDuration timeout = shardInformation.getDatastoreContext().getShardInitializationTimeout()
                    .duration();/*w  w w.ja v a 2s . c  o m*/
            if (shardInformation.isShardInitialized()) {
                // If the shard is already initialized then we'll wait enough time for the shard to
                // elect a leader, ie 2 times the election timeout.
                timeout = FiniteDuration.create(shardInformation.getDatastoreContext().getShardRaftConfig()
                        .getElectionTimeOutInterval().toMillis() * 2, TimeUnit.MILLISECONDS);
            }

            LOG.debug("{}: Scheduling {} ms timer to wait for shard {}", persistenceId(), timeout.toMillis(),
                    shardInformation.getShardName());

            Cancellable timeoutSchedule = getContext().system().scheduler().scheduleOnce(timeout, getSelf(),
                    new ShardNotInitializedTimeout(shardInformation, onShardInitialized, sender),
                    getContext().dispatcher(), getSelf());

            onShardInitialized.setTimeoutSchedule(timeoutSchedule);

        } else if (!shardInformation.isShardInitialized()) {
            LOG.debug("{}: Returning NotInitializedException for shard {}", persistenceId(),
                    shardInformation.getShardName());
            getSender().tell(createNotInitializedException(shardInformation.getShardId()), getSelf());
        } else {
            LOG.debug("{}: Returning NoShardLeaderException for shard {}", persistenceId(),
                    shardInformation.getShardName());
            getSender().tell(createNoShardLeaderException(shardInformation.getShardId()), getSelf());
        }

        return;
    }

    getSender().tell(messageSupplier.get(), getSelf());
}

From source file:org.openecomp.sdc.asdctool.impl.migration.v1610.ToscaArtifactsAlignment.java

private <T extends ComponentMetadataData> void fillAllComponetOfSpecificType(List<T> components,
        NodeTypeEnum nodeType, Supplier<Class<T>> classGetter, Wrapper<TitanOperationStatus> errorWrapper) {

    Map<String, Object> props = new HashMap<String, Object>();
    props.put(GraphPropertiesDictionary.IS_DELETED.getProperty(), true);
    Either<List<T>, TitanOperationStatus> eitherComponentMD = titanGenericDao.getByCriteria(nodeType, null,
            props, classGetter.get());
    if (eitherComponentMD.isLeft()) {
        components.addAll(eitherComponentMD.left().value());
    } else {//from  w  ww  .  j  ava2s  .  c o m
        final TitanOperationStatus errorType = eitherComponentMD.right().value();
        if (errorType != TitanOperationStatus.NOT_FOUND) {
            log.error("{} When fetching all components of type:{} a titan error occured:{}", ERROR_PREFIX,
                    nodeType.getName(), errorType.name());
            errorWrapper.setInnerElement(errorType);
        }
    }

}

From source file:org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.java

protected Either<ArtifactDefinition, ResponseFormat> generateArtifactPayload(
        ArtifactDefinition artifactDefinition, org.openecomp.sdc.be.model.Component component,
        String resourceInstanceName, User modifier, boolean shouldLock, Supplier<Long> payloadUpdateDateGen,
        Supplier<Either<ESArtifactData, ResponseFormat>> esDataCreator) {

    if (artifactDefinition.getPayloadUpdateDate() == null || artifactDefinition.getPayloadUpdateDate() == 0
            || artifactDefinition.getPayloadUpdateDate() < payloadUpdateDateGen.get()) {

        log.trace("Generaing payload for {} artifact {}", artifactDefinition.getArtifactType(),
                artifactDefinition.getEsId());
        Either<ESArtifactData, ResponseFormat> artifactDataRes = esDataCreator.get();
        ESArtifactData artifactData = null;

        if (artifactDataRes.isLeft()) {
            artifactData = artifactDataRes.left().value();
        } else {/*from   w  w  w.  j  a  va  2s.c  o m*/
            ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
            handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(),
                    modifier, artifactDefinition, artifactDefinition.getUniqueId(),
                    artifactDefinition.getUniqueId(), responseFormat, ComponentTypeEnum.RESOURCE_INSTANCE,
                    resourceInstanceName);

            return Either.right(artifactDataRes.right().value());
        }
        String newCheckSum = GeneralUtility.calculateMD5ByByteArray(artifactData.getDataAsArray());
        String oldCheckSum;
        String esArtifactId = artifactDefinition.getEsId();
        Either<ESArtifactData, CassandraOperationStatus> artifactfromES;
        ESArtifactData esArtifactData;
        if (esArtifactId != null && !esArtifactId.isEmpty()) {
            artifactfromES = artifactCassandraDao.getArtifact(esArtifactId);
            if (artifactfromES.isRight()) {
                CassandraOperationStatus resourceUploadStatus = artifactfromES.right().value();
                StorageOperationStatus storageResponse = DaoStatusConverter
                        .convertCassandraStatusToStorageStatus(resourceUploadStatus);
                ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageResponse);
                log.debug("Error when getting artifact from ES, error: {}", actionStatus.name());
                return Either.right(componentsUtils.getResponseFormatByArtifactId(actionStatus,
                        artifactDefinition.getArtifactDisplayName()));
            }
            esArtifactData = artifactfromES.left().value();
            oldCheckSum = GeneralUtility.calculateMD5ByByteArray(esArtifactData.getDataAsArray());
        } else {
            oldCheckSum = artifactDefinition.getArtifactChecksum();
        }
        Either<ArtifactDefinition, StorageOperationStatus> updateArifactDefinitionStatus;

        if (shouldLock) {
            Either<Boolean, ResponseFormat> lockComponent = lockComponent(component,
                    "Update Artifact - lock resource: ");
            if (lockComponent.isRight()) {
                handleAuditing(AuditingActionEnum.ARTIFACT_METADATA_UPDATE, component, component.getUniqueId(),
                        modifier, null, null, artifactDefinition.getUniqueId(), lockComponent.right().value(),
                        component.getComponentType(), null);
                return Either.right(lockComponent.right().value());
            }
        }
        try {
            if (oldCheckSum != null && oldCheckSum.equals(newCheckSum)) {

                artifactDefinition.setPayloadUpdateDate(payloadUpdateDateGen.get());
                updateArifactDefinitionStatus = artifactOperation.updateArifactDefinition(artifactDefinition,
                        false);
                log.trace("No real update done in payload for {} artifact, updating payloadUpdateDate {}",
                        artifactDefinition.getArtifactType(), artifactDefinition.getEsId());
                if (updateArifactDefinitionStatus.isRight()) {
                    ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(
                            componentsUtils
                                    .convertFromStorageResponse(updateArifactDefinitionStatus.right().value()),
                            artifactDefinition.getArtifactDisplayName());
                    log.trace("Failed to update payloadUpdateDate ", artifactDefinition.getEsId());
                    handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component,
                            component.getUniqueId(), modifier, artifactDefinition,
                            artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
                            ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);

                    return Either.right(responseFormat);
                }
            } else {

                oldCheckSum = artifactDefinition.getArtifactChecksum();
                artifactDefinition.setArtifactChecksum(newCheckSum);
                artifactOperation.updateUUID(artifactDefinition, oldCheckSum,
                        artifactDefinition.getArtifactVersion());
                artifactDefinition.setEsId(artifactDefinition.getUniqueId());
                updateArifactDefinitionStatus = artifactOperation.updateArifactDefinition(artifactDefinition,
                        true);

                log.trace("Update Payload  ", artifactDefinition.getEsId());

                if (updateArifactDefinitionStatus.isLeft()) {

                    artifactData.setId(artifactDefinition.getUniqueId());
                    CassandraOperationStatus saveArtifactStatus = artifactCassandraDao
                            .saveArtifact(artifactData);

                    if (saveArtifactStatus.equals(CassandraOperationStatus.OK)) {
                        titanGenericDao.commit();
                        log.debug("Artifact Saved In ES {}", artifactData.getId());
                        ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
                        handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component,
                                component.getUniqueId(), modifier, artifactDefinition,
                                artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(),
                                responseFormat, ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);

                    } else {
                        titanGenericDao.rollback();
                        log.info("Failed to save artifact {}.", artifactData.getId());
                        ResponseFormat responseFormat = componentsUtils
                                .getResponseFormat(ActionStatus.GENERAL_ERROR);
                        handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component,
                                component.getUniqueId(), modifier, artifactDefinition,
                                artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(),
                                responseFormat, ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);

                        return Either.right(responseFormat);
                    }
                } else {
                    ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(
                            componentsUtils
                                    .convertFromStorageResponse(updateArifactDefinitionStatus.right().value()),
                            artifactDefinition.getArtifactDisplayName());
                    log.debug("Failed To update artifact {}", artifactData.getId());
                    handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component,
                            component.getUniqueId(), modifier, artifactDefinition,
                            artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
                            ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);

                    return Either.right(responseFormat);

                }
            }
        } finally {
            if (shouldLock) {
                graphLockOperation.unlockComponent(component.getUniqueId(),
                        component.getComponentType().getNodeType());
            }
        }
    }

    return Either.left(artifactDefinition);
}

From source file:org.openecomp.sdc.be.model.operations.impl.AbstractOperation.java

protected <SomeData extends GraphNode, SomeDefenition> Either<SomeData, TitanOperationStatus> addDefinitionToNodeType(
        SomeDefenition someDefinition, NodeTypeEnum nodeType, String nodeUniqueId,
        final GraphEdgeLabels edgeType, Supplier<SomeData> dataBuilder, Supplier<String> defNameGenerator) {
    String defName = defNameGenerator.get();
    log.debug("Got {} {}", defName, someDefinition);

    SomeData someData = dataBuilder.get();

    log.debug("Before adding {} to graph. data = {}", defName, someData);

    @SuppressWarnings("unchecked")
    Either<SomeData, TitanOperationStatus> eitherSomeData = titanGenericDao.createNode(someData,
            (Class<SomeData>) someData.getClass());

    log.debug("After adding {} to graph. status is = {}", defName, eitherSomeData);

    if (eitherSomeData.isRight()) {
        TitanOperationStatus operationStatus = eitherSomeData.right().value();
        log.error("Failed to add {}  to graph. status is {}", defName, operationStatus);
        return Either.right(operationStatus);
    }//from ww w . j av a  2s  .c om
    UniqueIdData uniqueIdData = new UniqueIdData(nodeType, nodeUniqueId);
    log.debug("Before associating {} to {}.", uniqueIdData, defName);

    Either<GraphRelation, TitanOperationStatus> eitherRelations = titanGenericDao.createRelation(uniqueIdData,
            eitherSomeData.left().value(), edgeType, null);
    if (eitherRelations.isRight()) {
        TitanOperationStatus operationStatus = eitherRelations.right().value();
        BeEcompErrorManager.getInstance()
                .logInternalFlowError(
                        "AddDefinitionToNodeType", "Failed to associate" + nodeType.getName() + " "
                                + nodeUniqueId + "to " + defName + "in graph. status is " + operationStatus,
                        ErrorSeverity.ERROR);
        return Either.right(operationStatus);
    }
    return Either.left(eitherSomeData.left().value());
}

From source file:org.openecomp.sdc.be.model.operations.impl.AbstractOperation.java

protected <SomeData extends GraphNode, SomeDefenition> TitanOperationStatus addDefinitionToNodeType(
        TitanVertex vertex, SomeDefenition someDefinition, NodeTypeEnum nodeType, String nodeUniqueId,
        final GraphEdgeLabels edgeType, Supplier<SomeData> dataBuilder, Supplier<String> defNameGenerator) {
    String defName = defNameGenerator.get();
    log.debug("Got {} {}", defName, someDefinition);

    SomeData someData = dataBuilder.get();

    log.debug("Before adding {} to graph. data = {}", defName, someData);

    @SuppressWarnings("unchecked")
    Either<TitanVertex, TitanOperationStatus> eitherSomeData = titanGenericDao.createNode(someData);

    log.debug("After adding {} to graph. status is = {}", defName, eitherSomeData);

    if (eitherSomeData.isRight()) {
        TitanOperationStatus operationStatus = eitherSomeData.right().value();
        log.error("Failed to add {}  to graph. status is {}", defName, operationStatus);
        return operationStatus;
    }/*from  w  w  w  .  ja  v  a2 s . c  o m*/

    TitanOperationStatus relations = titanGenericDao.createEdge(vertex, eitherSomeData.left().value(), edgeType,
            null);
    if (!relations.equals(TitanOperationStatus.OK)) {
        TitanOperationStatus operationStatus = relations;
        BeEcompErrorManager.getInstance()
                .logInternalFlowError(
                        "AddDefinitionToNodeType", "Failed to associate" + nodeType.getName() + " "
                                + nodeUniqueId + "to " + defName + "in graph. status is " + operationStatus,
                        ErrorSeverity.ERROR);
        return operationStatus;
    }
    return relations;
}

From source file:org.openecomp.sdc.be.model.operations.impl.AbstractOperation.java

protected Either<String, TitanOperationStatus> getInnerType(ToscaPropertyType type,
        Supplier<SchemaDefinition> schemeGen) {
    String innerType = null;//  w ww.  j av  a 2 s  . co m
    if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {

        SchemaDefinition def = schemeGen.get();// propDataDef.getSchema();
        if (def == null) {
            log.debug("Schema doesn't exists for property of type {}", type);
            return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT);
        }
        PropertyDataDefinition propDef = def.getProperty();
        if (propDef == null) {
            log.debug("Property in Schema Definition inside property of type {} doesn't exists", type);
            return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT);
        }
        innerType = propDef.getType();
    }
    return Either.left(innerType);
}

From source file:org.openecomp.sdc.be.model.operations.impl.ComponentInstanceOperation.java

private <T extends GraphNode> TitanOperationStatus deleteAssociatedRIElements(NodeTypeEnum elementTypeToDelete,
        GraphEdgeLabels edgeConectingToRI, String resourceInstanceUid, Supplier<Class<T>> classGen) {

    Either<List<ImmutablePair<T, GraphEdge>>, TitanOperationStatus> elementsNodesRes = titanGenericDao
            .getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance),
                    resourceInstanceUid, edgeConectingToRI, elementTypeToDelete, classGen.get());

    if (elementsNodesRes.isRight()) {
        TitanOperationStatus status = elementsNodesRes.right().value();
        if (status != TitanOperationStatus.NOT_FOUND) {
            BeEcompErrorManager.getInstance().logInternalFlowError("deleteAssociatedRIElements",
                    "Failed to find the elements of resource instance " + resourceInstanceUid + ". status is "
                            + status,/*from w  w w . j  av  a  2 s . com*/
                    ErrorSeverity.ERROR);
            return status;
        }
    } else {

        List<ImmutablePair<T, GraphEdge>> relationshipNodes = elementsNodesRes.left().value();
        if (relationshipNodes != null) {
            for (ImmutablePair<T, GraphEdge> immutablePair : relationshipNodes) {
                T elementValueDataData = immutablePair.getKey();
                Either<T, TitanOperationStatus> deleteNode = titanGenericDao.deleteNode(elementValueDataData,
                        classGen.get());
                if (deleteNode.isRight()) {
                    TitanOperationStatus status = deleteNode.right().value();
                    BeEcompErrorManager.getInstance()
                            .logInternalFlowError(
                                    "deleteAssociatedRIElements", "Failed to delete element value node "
                                            + elementValueDataData + ". status is " + status,
                                    ErrorSeverity.ERROR);
                    return status;
                }
            }
        }

    }

    return TitanOperationStatus.OK;
}