Example usage for java.util Optional map

List of usage examples for java.util Optional map

Introduction

In this page you can find the example usage for java.util Optional map.

Prototype

public <U> Optional<U> map(Function<? super T, ? extends U> mapper) 

Source Link

Document

If a value is present, returns an Optional describing (as if by #ofNullable ) the result of applying the given mapping function to the value, otherwise returns an empty Optional .

Usage

From source file:com.holonplatform.core.internal.beans.DefaultBeanPropertySet.java

/**
 * Get the property with given <code>propertyPath</code> from bean property set using the properties full name as
 * matching rule./*w w w  .j a  va 2 s .  co m*/
 * @param propertyPath Property path
 * @param ignoreMissing <code>true</code> to ignore mismatches
 * @return Optional matching bean property
 * @throws PropertyNotFoundException If ignoreMissing is false and a matching bean property was not found
 */
private Optional<BeanProperty<?>> getProperty(Path<?> propertyPath, boolean ignoreMissing)
        throws PropertyNotFoundException {
    ObjectUtils.argumentNotNull(propertyPath, "Property path must be not null");
    Optional<PathProperty<?>> beanProperty = stream()
            .filter(p -> propertyPath.relativeName().equals(p.relativeName())).findFirst();
    if (!ignoreMissing && !beanProperty.isPresent()) {
        throw new PropertyNotFoundException(
                (propertyPath instanceof Property) ? (Property<?>) propertyPath : null,
                "Property with name [" + propertyPath.relativeName() + "] was not found in bean ["
                        + getBeanClass() + "] property set");
    }
    return beanProperty.map(p -> (BeanProperty<?>) p);
}

From source file:com.ikanow.aleph2.search_service.elasticsearch.services.ElasticsearchIndexService.java

/** A slightly generic function that determines what roles this service is playing
 * @param bucket//from   www. ja v a 2 s  .c  o m
 * @param service_clazz
 * @param maybe_schema
 * @return
 */
protected <I extends IUnderlyingService, T> boolean isServiceFor(final DataBucketBean bucket,
        final Class<I> service_clazz, Optional<T> maybe_schema) {
    return maybe_schema.flatMap(Lambdas.maybeWrap_i(schema -> {
        final JsonNode schema_map = BeanTemplateUtils.toJson(schema);
        final JsonNode enabled = schema_map.get("enabled");

        if ((null != enabled) && enabled.isBoolean() && !enabled.asBoolean()) {
            return false;
        } else {
            final Optional<I> maybe_service = _service_context.getService(service_clazz,
                    Optional.ofNullable(schema_map.get("service_name")).<String>map(j -> j.asText()));

            return maybe_service.map(service -> this.getClass().equals(service.getClass())).orElse(false);
        }
    })).orElse(false);
}

From source file:org.eclipse.hono.adapter.http.AbstractVertxBasedHttpProtocolAdapter.java

/**
 * Opens a command receiver link for a device by creating a command and control consumer.
 *
 * @param ctx The routing context of the HTTP request.
 * @param tenant The tenant of the device for that a command may be received.
 * @param deviceId The id of the device for that a command may be received.
 * @param commandReceivedHandler Handler to be called after a command was received or the timer expired.
 *                               The link was closed at this time already.
 *                               If the timer expired, the passed command message is null, otherwise the received command message is passed.
 *
 * @return Optional An optional handler that cancels a timer that might have been started to close the receiver link again.
 *///ww w .  j ava2s  . com
private Future<Handler<Void>> openCommandReceiverLink(final RoutingContext ctx, final String tenant,
        final String deviceId, final Handler<Message> commandReceivedHandler) {

    final Future<Handler<Void>> resultWithLinkCloseHandler = Future.future();

    final AtomicReference<MessageConsumer> messageConsumerRef = new AtomicReference<>(null);

    final Integer timeToDelayResponse = Optional.ofNullable(HttpUtils.getTimeTilDisconnect(ctx)).orElse(-1);

    if (timeToDelayResponse > 0) {
        // create a handler for being invoked if a command was received
        final Handler<Message> commandHandler = commandMessage -> {
            // if a link close handler was set, invoke it
            Optional.ofNullable(resultWithLinkCloseHandler.result()).map(linkCloseHandler -> {
                linkCloseHandler.handle(null);
                return null;
            });

            // if desired, now invoke the passed commandReceivedHandler and pass the message
            Optional.ofNullable(commandReceivedHandler).map(h -> {
                h.handle(commandMessage);
                return null;
            });

            final Optional<String> replyIdOpt = getReplyToIdFromCommand(tenant, deviceId, commandMessage);
            if (!replyIdOpt.isPresent()) {
                // from Java 9 on: switch to opt.ifPresentOrElse
                LOG.debug(
                        "Received command without valid replyId for device [tenantId: {}, deviceId: {}] - no reply will be sent to the application",
                        tenant, deviceId);
            } else {
                replyIdOpt.map(replyId -> {
                    // send answer to caller via sender link
                    final Future<CommandResponseSender> responseSender = createCommandResponseSender(tenant,
                            deviceId, replyId);
                    responseSender.compose(commandResponseSender -> commandResponseSender.sendCommandResponse(
                            getCorrelationIdFromMessage(commandMessage), null, null, HttpURLConnection.HTTP_OK))
                            .map(delivery -> {
                                LOG.debug("acknowledged command [message-id: {}]",
                                        commandMessage.getMessageId());
                                responseSender.result().close(v -> {
                                });
                                return null;
                            }).otherwise(t -> {
                                LOG.debug("could not acknowledge command [message-id: {}]",
                                        commandMessage.getMessageId(), t);
                                return Optional.ofNullable(responseSender.result()).map(r -> {
                                    r.close(v -> {
                                    });
                                    return null;
                                }).orElse(null);
                            });

                    return replyId;
                });

            }
        };

        // create the commandMessageConsumer that handles an incoming command message
        final BiConsumer<ProtonDelivery, Message> commandMessageConsumer = createCommandMessageConsumer(ctx,
                tenant, deviceId, commandHandler);

        createCommandConsumer(tenant, deviceId, commandMessageConsumer,
                v -> onCloseCommandConsumer(tenant, deviceId, commandMessageConsumer)).map(messageConsumer -> {
                    // remember message consumer for later usage
                    messageConsumerRef.set(messageConsumer);
                    // let only one command reach the adapter (may change in the future)
                    messageConsumer.flow(1);

                    // create a timer that is invoked if no command was received until timeToDelayResponse is expired
                    final long timerId = getVertx().setTimer(timeToDelayResponse * 1000L, delay -> {
                        closeCommandReceiverLink(messageConsumerRef);
                        // command finished, invoke handler
                        Optional.ofNullable(commandReceivedHandler).map(h -> {
                            h.handle(null);
                            return null;
                        });
                    });
                    // define the cancel code as closure
                    resultWithLinkCloseHandler.complete(v -> {
                        getVertx().cancelTimer(timerId);
                        closeCommandReceiverLink(messageConsumerRef);
                    });

                    return messageConsumer;
                }).recover(t -> {
                    closeCommandReceiverLink(messageConsumerRef);
                    resultWithLinkCloseHandler.fail(t);
                    return Future.failedFuture(t);
                });

    } else {
        resultWithLinkCloseHandler.complete();
    }

    return resultWithLinkCloseHandler;
}

From source file:blusunrize.immersiveengineering.api.energy.wires.ImmersiveNetHandler.java

public Set<AbstractConnection> getIndirectEnergyConnections(BlockPos node, World world,
        boolean ignoreIsEnergyOutput) {
    int dimension = world.provider.getDimension();
    if (!ignoreIsEnergyOutput && indirectConnections.containsKey(dimension)
            && indirectConnections.get(dimension).containsKey(node))
        return indirectConnections.get(dimension).get(node);
    else if (ignoreIsEnergyOutput && indirectConnectionsIgnoreOut.containsKey(dimension)
            && indirectConnectionsIgnoreOut.get(dimension).containsKey(node))
        return indirectConnectionsIgnoreOut.get(dimension).get(node);

    PriorityQueue<Pair<IImmersiveConnectable, Float>> queue = new PriorityQueue<>(
            Comparator.comparingDouble(Pair::getRight));
    Set<AbstractConnection> closedList = newSetFromMap(new ConcurrentHashMap<AbstractConnection, Boolean>());
    List<BlockPos> checked = new ArrayList<>();
    HashMap<BlockPos, BlockPos> backtracker = new HashMap<>();

    checked.add(node);/*from w  ww . j a v  a  2  s .  co m*/
    Set<Connection> conL = getConnections(world, node);
    if (conL != null)
        for (Connection con : conL) {
            IImmersiveConnectable end = toIIC(con.end, world);
            if (end != null) {
                queue.add(new ImmutablePair<>(end, con.getBaseLoss()));
                backtracker.put(con.end, node);
            }
        }

    IImmersiveConnectable next;
    final int closedListMax = 1200;

    while (closedList.size() < closedListMax && !queue.isEmpty()) {
        Pair<IImmersiveConnectable, Float> pair = queue.poll();
        next = pair.getLeft();
        float loss = pair.getRight();
        BlockPos nextPos = toBlockPos(next);
        if (!checked.contains(nextPos) && queue.stream().noneMatch((p) -> p.getLeft().equals(nextPos))) {
            boolean isOutput = next.isEnergyOutput();
            if (ignoreIsEnergyOutput || isOutput) {
                BlockPos last = toBlockPos(next);
                WireType minimumType = null;
                int distance = 0;
                List<Connection> connectionParts = new ArrayList<>();
                while (last != null) {
                    BlockPos prev = last;
                    last = backtracker.get(last);
                    if (last != null) {

                        Set<Connection> conLB = getConnections(world, last);
                        if (conLB != null)
                            for (Connection conB : conLB)
                                if (conB.end.equals(prev)) {
                                    connectionParts.add(0, conB);
                                    distance += conB.length;
                                    if (minimumType == null
                                            || conB.cableType.getTransferRate() < minimumType.getTransferRate())
                                        minimumType = conB.cableType;
                                    break;
                                }
                    }
                }
                closedList.add(new AbstractConnection(toBlockPos(node), toBlockPos(next), minimumType, distance,
                        isOutput, connectionParts.toArray(new Connection[connectionParts.size()])));
            }

            Set<Connection> conLN = getConnections(world, toBlockPos(next));
            if (conLN != null)
                for (Connection con : conLN)
                    if (next.allowEnergyToPass(con)) {
                        IImmersiveConnectable end = toIIC(con.end, world);

                        Optional<Pair<IImmersiveConnectable, Float>> existing = queue.stream()
                                .filter((p) -> p.getLeft() == end).findAny();
                        float newLoss = con.getBaseLoss() + loss;
                        if (end != null && !checked.contains(con.end)
                                && existing.map(Pair::getRight).orElse(Float.MAX_VALUE) > newLoss) {
                            existing.ifPresent(p1 -> queue.removeIf((p2) -> p1.getLeft() == p2.getLeft()));
                            queue.add(new ImmutablePair<>(end, newLoss));
                            backtracker.put(con.end, toBlockPos(next));
                        }
                    }
            checked.add(toBlockPos(next));
        }
    }
    if (FMLCommonHandler.instance().getEffectiveSide() == Side.SERVER) {
        if (ignoreIsEnergyOutput) {
            if (!indirectConnectionsIgnoreOut.containsKey(dimension))
                indirectConnectionsIgnoreOut.put(dimension, new ConcurrentHashMap<>());
            Map<BlockPos, Set<AbstractConnection>> conns = indirectConnectionsIgnoreOut.get(dimension);
            if (!conns.containsKey(node))
                conns.put(node, newSetFromMap(new ConcurrentHashMap<>()));
            conns.get(node).addAll(closedList);
        } else {
            if (!indirectConnections.containsKey(dimension))
                indirectConnections.put(dimension, new ConcurrentHashMap<>());
            Map<BlockPos, Set<AbstractConnection>> conns = indirectConnections.get(dimension);
            if (!conns.containsKey(node))
                conns.put(node, newSetFromMap(new ConcurrentHashMap<>()));
            conns.get(node).addAll(closedList);
        }
    }
    return closedList;
}

From source file:com.thinkbiganalytics.metadata.modeshape.datasource.JcrDatasourceProvider.java

@Override
public <D extends DatasourceDetails> Optional<D> ensureDatasourceDetails(@Nonnull final Datasource.ID id,
        @Nonnull final Class<D> type) {
    try {/* w ww.j  a  v a2  s .c  om*/
        // Ensure the data source exists
        final Optional<JcrUserDatasource> parent = Optional.ofNullable(getDatasource(id))
                .filter(JcrUserDatasource.class::isInstance).map(JcrUserDatasource.class::cast);
        if (!parent.isPresent()) {
            return Optional.empty();
        }

        // Create the details
        final Class<? extends JcrDatasourceDetails> implType = JcrUserDatasource.resolveDetailsClass(type);
        final boolean isNew = !hasEntityNode(parent.get().getPath(), JcrUserDatasource.DETAILS);

        final Node node = findOrCreateEntityNode(parent.get().getPath(), JcrUserDatasource.DETAILS, implType);
        @SuppressWarnings("unchecked")
        final D details = (D) JcrUtil.createJcrObject(node, implType);

        // Re-assign permissions to data source
        if (isNew) {
            final UsernamePrincipal owner = parent.map(JcrUserDatasource::getOwner).map(Principal::getName)
                    .map(UsernamePrincipal::new).orElse(JcrMetadataAccess.getActiveUser());
            if (accessController.isEntityAccessControlled()) {
                final List<SecurityRole> roles = roleProvider.getEntityRoles(SecurityRole.DATASOURCE);
                actionsProvider.getAvailableActions(AllowedActions.DATASOURCE).ifPresent(
                        actions -> parent.get().enableAccessControl((JcrAllowedActions) actions, owner, roles));
            } else {
                actionsProvider.getAvailableActions(AllowedActions.DATASOURCE).ifPresent(
                        actions -> parent.get().disableAccessControl((JcrAllowedActions) actions, owner));
            }
        }

        return Optional.of(details);
    } catch (final IllegalArgumentException e) {
        throw new MetadataException("Unable to create datasource details: " + type, e);
    }
}

From source file:it.tidalwave.bluemarine2.metadata.impl.audio.musicbrainz.MusicBrainzAudioMedatataImporter.java

/*******************************************************************************************************************
 *
 * Downloads and imports MusicBrainz data for the given {@link Metadata}.
 *
 * @param   metadata                the {@code Metadata}
 * @return                          the RDF triples
 * @throws  InterruptedException    in case of I/O error
 * @throws  IOException             in case of I/O error
 *
 ******************************************************************************************************************/
@Nonnull/*from w  w w  . ja va 2 s.  c o  m*/
public Optional<Model> handleMetadata(final @Nonnull Metadata metadata)
        throws InterruptedException, IOException {
    final ModelBuilder model = createModelBuilder();
    final Optional<String> optionalAlbumTitle = metadata.get(ALBUM);
    final Optional<Cddb> optionalCddb = metadata.get(CDDB);

    if (optionalAlbumTitle.isPresent() && !optionalAlbumTitle.get().trim().isEmpty()
            && optionalCddb.isPresent()) {
        final String albumTitle = optionalAlbumTitle.get();
        final Cddb cddb = optionalCddb.get();
        final String toc = cddb.getToc();

        synchronized (processedTocs) {
            if (processedTocs.contains(toc)) {
                return Optional.empty();
            }

            processedTocs.add(toc);
        }

        log.info("QUERYING MUSICBRAINZ FOR TOC OF: {}", albumTitle);
        final List<ReleaseMediumDisk> rmds = new ArrayList<>();
        final RestResponse<ReleaseList> releaseList = mbMetadataProvider.findReleaseListByToc(toc,
                TOC_INCLUDES);
        // even though we're querying by TOC, matching offsets is required to kill many false results
        releaseList.ifPresent(
                releases -> rmds.addAll(findReleases(releases, cddb, Validation.TRACK_OFFSETS_MATCH_REQUIRED)));

        if (rmds.isEmpty()) {
            log.info("TOC NOT FOUND, QUERYING MUSICBRAINZ FOR TITLE: {}", albumTitle);
            final List<ReleaseGroup> releaseGroups = new ArrayList<>();
            releaseGroups.addAll(mbMetadataProvider.findReleaseGroupByTitle(albumTitle)
                    .map(ReleaseGroupList::getReleaseGroup).orElse(emptyList()));

            final Optional<String> alternateTitle = cddbAlternateTitleOf(metadata);
            alternateTitle.ifPresent(t -> log.info("ALSO USING ALTERNATE TITLE: {}", t));
            releaseGroups.addAll(alternateTitle.map(_f(mbMetadataProvider::findReleaseGroupByTitle))
                    .map(response -> response.get().getReleaseGroup()).orElse(emptyList()));
            rmds.addAll(findReleases(releaseGroups, cddb, Validation.TRACK_OFFSETS_MATCH_REQUIRED));
        }

        model.with(markedAlternative(rmds, albumTitle).stream().parallel()
                .map(_f(rmd -> handleRelease(metadata, rmd))).collect(toList()));
    }

    return Optional.of(model.toModel());
}

From source file:org.ow2.proactive.connector.iaas.cloud.provider.azure.scaleset.AzureScaleSetProvider.java

private VirtualMachineScaleSet createVMSS(Azure azureService, Region region, ResourceGroup resourceGroup,
        Instance instance, Network network, LoadBalancer lb, String imageNameOrId, String vmAdminUsername,
        Optional<String> vmAdminSSHPubKey, String vmAdminPassword, int vmssNbOfInstances, List<String> fileUris,
        String installCommand) {//from   w  ww. j a v  a  2  s. c o  m

    VirtualMachineScaleSet.DefinitionStages.WithLinuxRootPasswordOrPublicKeyManagedOrUnmanaged virtualMachineScaleSetStage1 = azureService
            .virtualMachineScaleSets().define(azureScaleSetName)

            .withRegion(region).withExistingResourceGroup(resourceGroup)
            .withSku(selectScaleSetSku(instance.getHardware().getType()))
            .withExistingPrimaryNetworkSubnet(network, azureSubnetName)
            .withExistingPrimaryInternetFacingLoadBalancer(lb)
            .withPrimaryInternetFacingLoadBalancerBackends(azureBackendPoolName)
            .withPrimaryInternetFacingLoadBalancerInboundNatPools(azureNATPoolSSHName, azureNATPoolPNPName,
                    azureNATPoolPNPSName)
            .withoutPrimaryInternalLoadBalancer().withPopularLinuxImage(selectScaleSetLinuxImage(imageNameOrId))
            .withRootUsername(vmAdminUsername);
    VirtualMachineScaleSet.DefinitionStages.WithLinuxCreateManagedOrUnmanaged virtualMachineScaleSetStage2;

    virtualMachineScaleSetStage2 = vmAdminSSHPubKey.map(virtualMachineScaleSetStage1::withSsh)
            .orElseGet(() -> virtualMachineScaleSetStage1.withRootPassword(vmAdminPassword));

    return virtualMachineScaleSetStage2

            .withNewDataDisk(azureVMDiskSize).withCapacity(vmssNbOfInstances)

            .defineNewExtension("CustomScriptForLinux").withPublisher("Microsoft.OSTCExtensions")
            .withType("CustomScriptForLinux").withVersion("1.4").withMinorVersionAutoUpgrade()
            .withPublicSetting("fileUris", fileUris).withPublicSetting("commandToExecute", installCommand)

            .attach().create();
}

From source file:com.blazegraph.gremlin.structure.BlazeGraph.java

/**
 * Add a vertex./*from  w w w.  jav a 2s  .com*/
 * 
 * @see Graph#addVertex(Object...)
 */
@Override
public BlazeVertex addVertex(final Object... kvs) {
    ElementHelper.legalPropertyKeyValueArray(kvs);
    final Optional<Object> suppliedId = validateSuppliedId(kvs);

    final String id = suppliedId.map(String.class::cast).orElse(nextId());
    final String label = ElementHelper.getLabelValue(kvs).orElse(Vertex.DEFAULT_LABEL);
    ElementHelper.validateLabel(label);

    if (!bulkLoad) {
        final Optional<BlazeVertex> existing = vertex(id);
        if (existing.isPresent()) {
            throw Graph.Exceptions.vertexWithIdAlreadyExists(id);
        }
    }

    log.info(() -> "v(" + id + ", " + label + ")");

    final BigdataValueFactory rdfvf = rdfValueFactory();
    final BigdataURI uri = rdfvf.asValue(vf.elementURI(id));
    final BigdataURI rdfLabel = rdfvf.asValue(vf.typeURI(label));

    final RepositoryConnection cxn = cxn();
    Code.wrapThrow(() -> {
        cxn.add(uri, TYPE, rdfLabel);
    });

    final BlazeVertex vertex = new BlazeVertex(this, uri, rdfLabel);
    ElementHelper.attachProperties(vertex, VertexProperty.Cardinality.set, kvs);
    return vertex;
}

From source file:com.blazegraph.gremlin.structure.BlazeGraph.java

/**
 * Add an edge. Helper for {@link BlazeVertex#addEdge(String, Vertex, Object...)}
 * to consolidate these operations in one place.
 * //from   w ww .j ava 2s.c  o m
 * @see Vertex#addEdge(String, Vertex, Object...)
 */
public BlazeEdge addEdge(final BlazeVertex from, final BlazeVertex to, final String label,
        final Object... kvs) {
    ElementHelper.validateLabel(label);
    ElementHelper.legalPropertyKeyValueArray(kvs);
    final Optional<Object> suppliedId = validateSuppliedId(kvs);

    final String id = suppliedId.map(String.class::cast).orElse(nextId());

    if (!bulkLoad) {
        final Optional<BlazeEdge> existing = edge(id);
        if (existing.isPresent()) {
            throw Graph.Exceptions.vertexWithIdAlreadyExists(id);
        }
    }

    log.info(() -> "v(" + from + ")-e(" + id + ", " + label + ")->v(" + to + ")");

    final BigdataValueFactory rdfvf = rdfValueFactory();

    final URI uri = rdfvf.asValue(vf.elementURI(id));
    final BigdataURI rdfLabel = rdfvf.asValue(vf.typeURI(label));

    final BigdataStatement edgeStmt = rdfvf.createStatement(from.rdfId(), uri, to.rdfId());

    final RepositoryConnection cxn = cxn();
    Code.wrapThrow(() -> {
        // blaze:person:1 blaze:knows:7 blaze:person:2 .
        cxn.add(edgeStmt);
        // <<blaze:person:1 blaze:knows:7 blaze:person:2>> rdf:type "knows" .
        cxn.add(rdfvf.createBNode(edgeStmt), TYPE, rdfLabel);
    });

    final BlazeEdge edge = new BlazeEdge(this, edgeStmt, rdfLabel, from, to);
    ElementHelper.attachProperties(edge, kvs);
    return edge;
}