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:info.archinnov.achilles.internals.parser.CodecFactory.java

public CodecInfo createCodec(TypeName sourceType, AnnotationTree annotationTree, FieldParsingContext context,
        Optional<CodecInfo> codecFromRegistry) {
    final String fieldName = context.fieldName;
    final String className = context.className;

    TypeName targetType = sourceType;/* w ww .  jav a  2  s  .c o m*/
    TypeMirror typeMirror = annotationTree.getCurrentType();

    final Optional<TypedMap> jsonTransform = extractTypedMap(annotationTree, JSON.class);
    final Optional<TypedMap> enumerated = extractTypedMap(annotationTree, Enumerated.class);
    final Optional<TypedMap> codecFromType = extractTypedMap(annotationTree, Codec.class);
    final Optional<TypedMap> runtimeCodec = extractTypedMap(annotationTree, RuntimeCodec.class);
    final Optional<TypedMap> computed = extractTypedMap(annotationTree, Computed.class);
    final Optional<TypeName> computedCQLClass = computed.map(x -> x.<Class<?>>getTyped("cqlClass"))
            .map(ClassName::get);
    final boolean isCounter = extractTypedMap(annotationTree, Counter.class).isPresent();

    CodeBlock codec;

    if (jsonTransform.isPresent()) {
        codec = CodeBlock.builder().add("new $T<>($T.class, $L)", JSON_CODEC, getRawType(sourceType).box(),
                buildJavaTypeForJackson(sourceType)).build();
        targetType = ClassName.get(String.class);
        return new CodecInfo(codec, sourceType, targetType);
    } else if (codecFromType.isPresent()) {
        final Tuple2<TypeName, CodeBlock> tuple2 = codecCodeGen(codecFromType.get(), sourceType,
                computedCQLClass, isCounter);
        targetType = tuple2._1();
        codec = tuple2._2();
        return new CodecInfo(codec, sourceType, targetType);
    } else if (runtimeCodec.isPresent()) {
        final Tuple2<TypeName, CodeBlock> tuple2 = runtimeCodecCodeGen(runtimeCodec.get(), computedCQLClass,
                isCounter);
        targetType = tuple2._1();
        codec = tuple2._2();
        return new CodecInfo(codec, sourceType, targetType);
    } else if (enumerated.isPresent()) {
        final Tuple2<TypeName, CodeBlock> tuple2 = enumeratedCodecCodeGen(enumerated.get(), sourceType,
                fieldName, className);
        codec = tuple2._2();
        targetType = tuple2._1();
        return new CodecInfo(codec, sourceType, targetType);
    } else if (typeMirror.getKind() == TypeKind.ARRAY && typeMirror.toString().equals("byte[]")) {
        if (codecFromRegistry.isPresent()) {
            return codecFromRegistry.get();
        } else {
            codec = CodeBlock.builder().add("new $T()", BYTE_ARRAY_PRIMITIVE_CODEC).build();
            return new CodecInfo(codec, sourceType, BYTE_BUFFER);
        }
    } else if (typeMirror.getKind() == TypeKind.ARRAY && typeMirror.toString().equals("java.lang.Byte[]")) {
        if (codecFromRegistry.isPresent()) {
            return codecFromRegistry.get();
        } else {
            codec = CodeBlock.builder().add("new $T()", BYTE_ARRAY_CODEC).build();
            return new CodecInfo(codec, sourceType, BYTE_BUFFER);
        }
    } else {
        if (codecFromRegistry.isPresent()) {
            return codecFromRegistry.get();
        } else {
            if (computedCQLClass.isPresent()) {
                aptUtils.validateTrue(sourceType.equals(computedCQLClass.get()),
                        "CQL class '%s' of @Computed field '%s' of class '%s' should be same as field class '%s'",
                        computedCQLClass.get(), fieldName, className, sourceType);
            }
            validateAllowedTypes(aptUtils, sourceType, sourceType);
            codec = CodeBlock.builder()
                    .add("new $T<>($T.class)", FALL_THROUGH_CODEC, getRawType(sourceType).box()).build();
            return new CodecInfo(codec, sourceType, targetType);
        }
    }
}

From source file:alfio.manager.StripeManager.java

public boolean refund(Transaction transaction, Event event, Optional<Integer> amount) {
    String chargeId = transaction.getTransactionId();
    try {/* w w  w.ja v a2 s  . com*/
        String amountOrFull = amount.map(MonetaryUtil::formatCents).orElse("full");
        log.info("Stripe: trying to do a refund for payment {} with amount: {}", chargeId, amountOrFull);
        Map<String, Object> params = new HashMap<>();
        params.put("charge", chargeId);
        amount.ifPresent(a -> params.put("amount", a));
        if (isConnectEnabled(event)) {
            params.put("refund_application_fee", true);
        }

        Optional<RequestOptions> requestOptionsOptional = options(event);
        if (requestOptionsOptional.isPresent()) {
            RequestOptions options = requestOptionsOptional.get();
            Refund r = Refund.create(params, options);
            if ("succeeded".equals(r.getStatus())) {
                log.info("Stripe: refund for payment {} executed with success for amount: {}", chargeId,
                        amountOrFull);
                return true;
            } else {
                log.warn(
                        "Stripe: was not able to refund payment with id {}, returned status is not 'succeded' but {}",
                        chargeId, r.getStatus());
                return false;
            }
        }
        return false;
    } catch (StripeException e) {
        log.warn("Stripe: was not able to refund payment with id " + chargeId, e);
        return false;
    }
}

From source file:io.neba.core.resourcemodels.registration.ModelRegistryConsolePlugin.java

private void writeHeadnavigation(HttpServletResponse response) throws IOException {
    String template = readTemplateFile("/META-INF/consoleplugin/modelregistry/templates/head.html");

    Optional<ResourceResolver> resourceResolver = getResourceResolver();
    String configurationHint = resourceResolver.map(r -> {
        r.close();//from w  w  w. j ava  2  s  .  c o  m
        return "";
    }).orElse("<br />" + " Warning: No amendment mapping for io.neba.neba-core:" + SUBSERVICE_NAME
            + " is <a href='" + getServletContext().getContextPath()
            + "/system/console/configMgr/'>configured</a>"
            + " or the mapping is invalid, and using the default admin account has failed."
            + " This console plugin will not be able to access the repository.");
    response.getWriter().printf(template, getNumberOfModels(), configurationHint);
}

From source file:ee.ria.xroad.opmonitordaemon.HealthDataRequestHandler.java

private ServicesEventsType buildServicesEvents(Optional<ClientId> provider) {
    ServicesEventsType servicesEvents = OBJECT_FACTORY.createServicesEventsType();

    servicesWithAvailableMetrics()/* w  w w. ja va  2  s .co m*/
            // If a client ID was provided in the request then
            // only include service metrics for that provider
            .filter(id -> provider.map(id.getClientId()::equals).orElse(true))
            .forEach(service -> servicesEvents.getServiceEvents().add(buildServiceEvents(service)));

    return servicesEvents;
}

From source file:nu.yona.server.analysis.service.AnalysisEngineService.java

private void updateLastMonitoredActivityDateIfRelevant(List<ActivityPayload> payloads,
        UserAnonymizedDto userAnonymized, UserAnonymizedEntityHolder userAnonymizedEntityHolder) {
    Optional<LocalDate> lastActivityEndTime = payloads.stream().map(payload -> payload.endTime)
            .max(ZonedDateTime::compareTo).map(ZonedDateTime::toLocalDate);
    Optional<LocalDate> lastMonitoredActivityDate = userAnonymized.getLastMonitoredActivityDate();
    if (lastActivityEndTime.isPresent()
            && lastMonitoredActivityDate.map(d -> d.isBefore(lastActivityEndTime.get())).orElse(true)) {
        activityUpdateService.updateLastMonitoredActivityDate(userAnonymizedEntityHolder.getEntity(),
                lastActivityEndTime.get());
    }//from  w w  w .j  a  v  a 2 s  . c  o m
}

From source file:org.ow2.proactive.connector.iaas.cloud.provider.azure.vm.AzureVMsProvider.java

@Override
public Set<Instance> createInstance(Infrastructure infrastructure, Instance instance) {

    Azure azureService = azureServiceCache.getService(infrastructure);
    String instanceTag = Optional.ofNullable(instance.getTag()).orElseThrow(
            () -> new RuntimeException("ERROR missing instance tag/name from instance: '" + instance + "'"));

    // Check for Image by name first and then by id
    String imageNameOrId = Optional.ofNullable(instance.getImage()).orElseThrow(
            () -> new RuntimeException("ERROR missing Image name/id from instance: '" + instance + "'"));

    VirtualMachineCustomImage image = getImageByName(azureService, imageNameOrId)
            .orElseGet(() -> getImageById(azureService, imageNameOrId).orElseThrow(() -> new RuntimeException(
                    "ERROR unable to find custom Image: '" + instance.getImage() + "'")));

    // Get the options (Optional by design)
    Optional<Options> options = Optional.ofNullable(instance.getOptions());

    // Try to retrieve the resourceGroup from provided name, otherwise get it from image
    ResourceGroup resourceGroup = azureProviderUtils
            .searchResourceGroupByName(azureService,
                    options.map(Options::getResourceGroup).orElseGet(image::resourceGroupName))
            .orElseThrow(() -> new RuntimeException(
                    "ERROR unable to find a suitable resourceGroup from instance: '" + instance + "'"));

    // Try to get region from provided name, otherwise get it from image
    Region region = options.map(presentOptions -> Region.findByLabelOrName(presentOptions.getRegion()))
            .orElseGet(image::region);// w  ww.  j  a  v  a2 s .  c  o m

    // Prepare the VM(s)
    Optional<Boolean> optionalStaticPublicIP = options.map(Options::getStaticPublicIP);
    List<Creatable<VirtualMachine>> creatableVirtualMachines = prepareCreatableVirtualMachines(azureService,
            options, region, resourceGroup, instanceTag, instance, image, optionalStaticPublicIP);

    // Create all VMs in parallel and collect IDs
    return azureService.virtualMachines().create(creatableVirtualMachines).values().stream()
            .map(vm -> instance.withTag(vm.name()).withId(vm.vmId()).withNumber(SINGLE_INSTANCE_NUMBER))
            .collect(Collectors.toSet());
}

From source file:org.ow2.proactive.connector.iaas.cloud.provider.azure.vm.AzureVMsProvider.java

private List<Creatable<VirtualMachine>> prepareCreatableVirtualMachines(Azure azureService,
        Optional<Options> options, Region region, ResourceGroup resourceGroup, String instanceTag,
        Instance instance, VirtualMachineCustomImage image, Optional<Boolean> optionalStaticPublicIP) {

    // Prepare a new virtual private network (same for all VMs)
    Optional<String> optionalPrivateNetworkCIDR = options.map(Options::getPrivateNetworkCIDR);
    Creatable<Network> creatableVirtualNetwork = azureProviderNetworkingUtils.prepareVirtualNetwork(
            azureService, region, resourceGroup, createUniqueVirtualNetworkName(instanceTag),
            optionalPrivateNetworkCIDR.orElse(defaultPrivateNetworkCidr));

    // Get existing virtual private network if specified
    Optional<Network> optionalVirtualNetwork = options.map(Options::getSubnetId)
            .map(subnetId -> azureProviderUtils.searchVirtualNetworkByName(azureService, subnetId).get());

    // Prepare a new  security group (same for all VMs)
    Creatable<NetworkSecurityGroup> creatableNetworkSecurityGroup = azureProviderNetworkingUtils
            .prepareProactiveNetworkSecurityGroup(azureService, region, resourceGroup,
                    createUniqueSecurityGroupName(instance.getTag()));

    // Get existing security group if specified
    Optional<NetworkSecurityGroup> optionalNetworkSecurityGroup = options.map(Options::getSecurityGroupNames)
            .map(secGrpNames -> secGrpNames.get(0)).map(secGrpName -> azureProviderUtils
                    .searchNetworkSecurityGroupByName(azureService, secGrpName).get());

    // Get existing public IP address if specified
    Optional<PublicIpAddress> optionalPublicIpAddress = options.map(Options::getPublicIpAddress)
            .map(publicIpAddress -> azureProviderUtils.searchPublicIpAddressByIp(azureService, publicIpAddress)
                    .get());/*from  ww  w  . j  a  va  2 s  . c  o  m*/

    return IntStream
            .rangeClosed(1,
                    Integer.valueOf(Optional.ofNullable(instance.getNumber()).orElse(SINGLE_INSTANCE_NUMBER)))
            .mapToObj(instanceNumber -> {
                // Create a new public IP address (one per VM)
                String publicIPAddressName = createUniquePublicIPName(
                        createUniqueInstanceTag(instanceTag, instanceNumber));
                Creatable<PublicIpAddress> creatablePublicIpAddress = azureProviderNetworkingUtils
                        .preparePublicIPAddress(azureService, region, resourceGroup, publicIPAddressName,
                                optionalStaticPublicIP.orElse(DEFAULT_STATIC_PUBLIC_IP));

                // Prepare a new network interface (one per VM)
                String networkInterfaceName = createUniqueNetworkInterfaceName(
                        createUniqueInstanceTag(instanceTag, instanceNumber));
                Creatable<NetworkInterface> creatableNetworkInterface = azureProviderNetworkingUtils
                        .prepareNetworkInterface(azureService, region, resourceGroup, networkInterfaceName,
                                creatableVirtualNetwork, optionalVirtualNetwork.orElse(null),
                                creatableNetworkSecurityGroup, optionalNetworkSecurityGroup.orElse(null),
                                creatablePublicIpAddress,
                                instanceNumber == 1 ? optionalPublicIpAddress.orElse(null) : null);

                return prepareVirtualMachine(instance, azureService, resourceGroup, region,
                        createUniqueInstanceTag(instanceTag, instanceNumber), image, creatableNetworkInterface);
            }).collect(Collectors.toList());
}

From source file:com.ikanow.aleph2.search_service.elasticsearch.utils.ElasticsearchIndexUtils.java

/** Builds a lookup table of settings 
 * @param mapping - the mapping to use//from   w  w  w.j a va2 s . c  om
 * @param type - if the index has a specific type, lookup that and _default_ ; otherwise just _default
 * @return
 */
public static LinkedHashMap<Either<String, Tuple2<String, String>>, JsonNode> parseDefaultMapping(
        final JsonNode mapping, final Optional<String> type,
        final Optional<DataSchemaBean.SearchIndexSchemaBean> maybe_search_index_schema,
        final Optional<DataSchemaBean.DocumentSchemaBean> maybe_document_schema,
        final SearchIndexSchemaDefaultBean search_index_schema_override, final ObjectMapper mapper) {
    //(see similar code in createComplexStringLookups)
    final boolean tokenize_by_default = maybe_search_index_schema.map(schema -> schema.tokenize_by_default())
            .orElse(true);
    final boolean dual_tokenize_by_default = Optional
            .ofNullable(search_index_schema_override.dual_tokenize_by_default()).orElse(false);

    final JsonNode default_string_mapping = ((ObjectNode) (ElasticsearchIndexUtils.getMapping(
            Tuples._2T(tokenize_by_default, dual_tokenize_by_default), search_index_schema_override, mapper,
            true))).put(TYPE_MATCH_NAME, "string").put(PATH_MATCH_NAME, "*");

    // (this is always not tokenized but inherits dual tokenization)
    final ObjectNode not_analyzed_field = ((ObjectNode) (ElasticsearchIndexUtils.getMapping(
            Tuples._2T(false, dual_tokenize_by_default), search_index_schema_override, mapper, true)))
                    .put(TYPE_MATCH_NAME, "string");

    final LinkedHashMap<Either<String, Tuple2<String, String>>, JsonNode> ret = Optional
            .ofNullable(mapping.get("mappings")).map(m -> {
                if (!m.isObject())
                    throw new RuntimeException("mappings must be object");
                return m;
            })
            .map(m -> Optional.ofNullable(m.get(type.orElse("_default_")))
                    .map(mm -> !mm.isNull() ? mm : m.get("_default_")).orElse(m.get("_default_")))
            .filter(m -> !m.isNull()).map(i -> {
                if (!i.isObject())
                    throw new RuntimeException(type + " must be object");
                return i;
            }).map(i -> {
                // OK so I have a list of dynamic_templates, and a list of properties - and then a set of string defaults to apply
                // 1) want to leave the properties alone
                // 2) then the tokenization overrides from createComplexStringLookups
                // 3) then the existing templates
                final Map<Either<String, Tuple2<String, String>>, JsonNode> override_props = createComplexStringLookups(
                        maybe_search_index_schema, search_index_schema_override, mapper);

                // ensure string doc fields aren't analyzed
                final Map<Either<String, Tuple2<String, String>>, String> type_override = maybe_search_index_schema
                        .map(s -> s.type_override()).map(m -> buildTypeMap(m)).orElse(Collections.emptyMap());

                final Map<Either<String, Tuple2<String, String>>, JsonNode> doc_props = maybe_document_schema
                        .map(ds -> ds.deduplication_fields())
                        .<Map<Either<String, Tuple2<String, String>>, JsonNode>>map(fields -> {
                            return fields.stream().filter(f -> !override_props.containsKey(Either.left(f)))
                                    .filter(f -> !override_props.containsKey(Either.right(Tuples._2T(f, "*"))))
                                    .filter(f -> !type_override.containsKey(Either.left(f)))
                                    .filter(f -> !type_override.containsKey(Either.right(Tuples._2T(f, "*"))))
                                    .<Tuple2<Either<String, Tuple2<String, String>>, JsonNode>>map(
                                            f -> Tuples._2T(Either.right(Tuples._2T(f, "string")),
                                                    not_analyzed_field.deepCopy().put(PATH_MATCH_NAME, f)))
                                    .collect(Collectors.toMap(
                                            (Tuple2<Either<String, Tuple2<String, String>>, JsonNode> t2) -> t2
                                                    ._1(),
                                            t2 -> t2._2()));
                        }).orElse(Collections.emptyMap());

                final LinkedHashMap<Either<String, Tuple2<String, String>>, JsonNode> props = new LinkedHashMap<>();
                props.putAll(doc_props); // (put these first - though actually i'm fixing the order with an explicit sort in the columnar section)
                props.putAll(override_props);

                // extra mappings and extra templates
                Optionals.of(() -> search_index_schema_override.extra_field_mappings())
                        .map(o -> mapper.convertValue(o, JsonNode.class)).ifPresent(j -> {
                            props.putAll(getTemplates(j, default_string_mapping, props.keySet()));
                            props.putAll(getProperties(j));
                        });

                // full mappings at the end
                props.putAll(getTemplates(i, default_string_mapping, props.keySet()));
                props.putAll(getProperties(i));

                return props;
            }).orElse(new LinkedHashMap<>());

    return ret;
}

From source file:com.ethercamp.harmony.service.WalletService.java

private void checkForChangesInWallet(BlockSummary blockSummary, List<Transaction> transactions,
        Consumer<TransactionInfo> sendHandler, Consumer<TransactionInfo> receiveHandler) {
    final Set<ByteArrayWrapper> subscribed = addresses.keySet().stream().map(a -> cleanAddress(a))
            .flatMap(a -> {/*from ww w. java2 s. c o  m*/
                try {
                    return Stream.of(new ByteArrayWrapper(Hex.decode(a)));
                } catch (Exception e) {
                    log.error("Problem getting bytes representation from " + a);
                    return Stream.empty();
                }
            }).collect(Collectors.toSet());

    final List<Transaction> confirmedTransactions = transactions.stream()
            .filter(transaction -> isSetContains(subscribed, transaction.getReceiveAddress())
                    || isSetContains(subscribed, transaction.getSender()))
            .collect(Collectors.toList());

    confirmedTransactions.forEach(transaction -> {
        final String hash = toHexString(transaction.getHash());
        final BigInteger amount = ByteUtil.bytesToBigInteger(transaction.getValue());
        final boolean hasSender = isSetContains(subscribed, transaction.getSender());
        final boolean hasReceiver = isSetContains(subscribed, transaction.getReceiveAddress());
        log.debug("Handle transaction hash:" + hash + ", hasSender:" + hasSender + ", amount:" + amount);

        if (hasSender) {
            sendHandler
                    .accept(new TransactionInfo(hash, amount, hasSender, toHexString(transaction.getSender())));
        }
        if (hasReceiver) {
            receiveHandler.accept(
                    new TransactionInfo(hash, amount, hasSender, toHexString(transaction.getReceiveAddress())));
        }
    });

    // check if balance changes due to block reward
    final Optional<ByteArrayWrapper> coinbase = Optional.ofNullable(blockSummary)
            .map(bs -> new ByteArrayWrapper(bs.getBlock().getCoinbase()));
    final Boolean matchCoinbase = coinbase.map(c -> subscribed.stream().anyMatch(a -> c.equals(a)))
            .orElse(false);

    final boolean needToSendUpdate = matchCoinbase || !confirmedTransactions.isEmpty();
    if (needToSendUpdate) {
        // update wallet if transactions are related to wallet addresses
        clientMessageService.sendToTopic("/topic/getWalletInfo", getWalletInfo());
    }
}