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:org.ow2.proactive.connector.iaas.cloud.provider.azure.AzureProvider.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);//from w  w  w.j  ava 2s.  c o m

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

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

    // Prepare the VM(s)
    Optional<Boolean> optionalStaticPublicIP = options.map(Options::getStaticPublicIP);
    List<Creatable<VirtualMachine>> creatableVirtualMachines = 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 = azureProviderUtils.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 = azureProviderUtils
                        .prepareNetworkInterfaceFromScratch(azureService, region, resourceGroup,
                                networkInterfaceName, creatableVirtualNetwork, creatableNetworkSecurityGroup,
                                creatablePublicIPAddress);

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

    // 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:com.ikanow.aleph2.analytics.storm.services.StreamingEnrichmentContextService.java

@Override
public Validation<BasicMessageBean, JsonNode> emitImmutableObject(final long id, final JsonNode original_json,
        final Optional<ObjectNode> mutations, final Optional<AnnotationBean> annotations,
        final Optional<JsonNode> grouping_fields) {
    if (annotations.isPresent()) {
        throw new RuntimeException(ErrorUtils.NOT_YET_IMPLEMENTED);
    }/*  w  ww  .j  av  a2  s  .c  o  m*/
    if (grouping_fields.isPresent()) {
        throw new RuntimeException(ErrorUtils.NOT_YET_IMPLEMENTED);
    }
    final JsonNode to_emit = mutations.map(o -> StreamSupport.<Map.Entry<String, JsonNode>>stream(
            Spliterators.spliteratorUnknownSize(o.fields(), Spliterator.ORDERED), false).reduce(original_json,
                    (acc, kv) -> ((ObjectNode) acc).set(kv.getKey(), kv.getValue()), (val1, val2) -> val2))
            .orElse(original_json);

    emitMutableObject(0L, (ObjectNode) to_emit, annotations, Optional.empty());
    return Validation.success(to_emit);
}

From source file:alfio.manager.PaymentManager.java

public boolean refund(TicketReservation reservation, Event event, Optional<Integer> amount, String username) {
    Transaction transaction = transactionRepository.loadByReservationId(reservation.getId());
    boolean res;//from  w w  w  . ja va2  s .co  m
    switch (reservation.getPaymentMethod()) {
    case PAYPAL:
        res = paypalManager.refund(transaction, event, amount);
        break;
    case STRIPE:
        res = stripeManager.refund(transaction, event, amount);
        break;
    default:
        throw new IllegalStateException("Cannot refund ");
    }

    if (res) {
        Map<String, Object> changes = new HashMap<>();
        changes.put("refund", amount.map(Object::toString).orElse("full"));
        changes.put("paymentMethod", reservation.getPaymentMethod().toString());
        auditingRepository.insert(reservation.getId(), userRepository.findIdByUserName(username).orElse(null),
                event.getId(), Audit.EventType.REFUND, new Date(), Audit.EntityType.RESERVATION,
                reservation.getId(), Collections.singletonList(changes));
    }

    return res;
}

From source file:com.ikanow.aleph2.data_import_manager.analytics.actors.TestAnalyticsTriggerWorkerActor.java

/**
 * @param bucket_name//from   w ww  . j a  v  a 2 s .c  o  m
 * @param job_name
 * @param curr_not_last - true to get curr_run, false to get last_run
 * @return
 */
protected static Long getLastRunTime(final String bucket_name, final Optional<String> job_name,
        final boolean curr_not_last) {
    return _status_crud.getObjectBySpec(
            CrudUtils.allOf(DataBucketStatusBean.class).when(DataBucketStatusBean::bucket_path, bucket_name))
            .join().<Long>map(status_bean -> {
                return job_name
                        .map(jn -> Optional.ofNullable(status_bean.analytic_state()).map(as -> as.get(jn))
                                .map(d -> curr_not_last ? d.curr_run() : d.last_run()).map(d -> d.getTime())
                                .orElse(-1L))
                        .orElseGet(() -> Optional.ofNullable(status_bean.global_analytic_state())
                                .map(d -> curr_not_last ? d.curr_run() : d.last_run()).map(d -> d.getTime())
                                .orElse(-1L));
            }).orElse(-1L);
}

From source file:co.runrightfast.vertx.core.RunRightFastVerticle.java

private <REQ extends Message, RESP extends Message> Handler<Void> messageConsumerEndHandler(
        final String address, final Optional<Handler<Void>> handler,
        final MessageConsumerConfig<REQ, RESP> config) {
    final Handler<Void> defaultHandler = result -> {
        info.log("messageConsumerEndHandler", () -> messageConsumerLogInfo(address, config));
    };//from  w  w w  . j  a v  a2  s.c  o  m

    return handler.map(h -> {
        final Handler<Void> endHandler = result -> {
            defaultHandler.handle(result);
            h.handle(result);
        };
        return endHandler;
    }).orElse(defaultHandler);
}

From source file:com.ikanow.aleph2.data_import.services.HarvestContext.java

@Override
public <S> ICrudService<S> getBucketObjectStore(final Class<S> clazz, final Optional<DataBucketBean> bucket,
        final Optional<String> collection, final Optional<AssetStateDirectoryBean.StateDirectoryType> type) {
    final Optional<DataBucketBean> this_bucket = bucket.map(x -> Optional.of(x)).orElseGet(
            () -> _mutable_state.bucket.isSet() ? Optional.of(_mutable_state.bucket.get()) : Optional.empty());

    return Patterns.match(type).<ICrudService<S>>andReturn()
            .when(t -> t.isPresent() && AssetStateDirectoryBean.StateDirectoryType.analytic_thread == t.get(),
                    __ -> _core_management_db.getBucketAnalyticThreadState(clazz, this_bucket.get(),
                            collection))
            .when(t -> t.isPresent() && AssetStateDirectoryBean.StateDirectoryType.enrichment == t.get(),
                    __ -> _core_management_db.getBucketEnrichmentState(clazz, this_bucket.get(), collection))
            // assume this is the technology context, most likely usage
            .when(t -> t.isPresent() && AssetStateDirectoryBean.StateDirectoryType.library == t.get(),
                    __ -> _core_management_db.getPerLibraryState(clazz, this.getTechnologyLibraryConfig(),
                            collection))
            // default: harvest or not specified: harvest
            .otherwise(__ -> _core_management_db.getBucketHarvestState(clazz, this_bucket.get(), collection));
}

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

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

    // Initialize Azure service connector
    Azure azureService = azureServiceCache.getService(infrastructure);

    // Retrieve options and prepare Azure resources creation
    Optional<Options> options = Optional.ofNullable(instance.getOptions());
    genAzureResourcesNames(infrastructure);

    logger.info("Starting creation of Azure Scale set '" + azureScaleSetName + "'.");

    // Retrieve Linux image to be used (but have to comply with the Azure VMSS policy and supported images)
    // see selectLinuxImage() below.
    String imageNameOrId = Optional.ofNullable(instance.getImage()).orElseThrow(
            () -> new RuntimeException("ERROR missing Image name/id from instance: '" + instance + "'"));

    // Retrieve resource group
    String rgName = options.map(Options::getResourceGroup).orElseThrow(() -> new RuntimeException(
            "ERROR unable to find a suitable resourceGroup from instance: '" + instance + "'"));
    ResourceGroup resourceGroup = azureProviderUtils.searchResourceGroupByName(azureService, rgName)
            .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(resourceGroup::region);

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

    // Get VM admin user credentials
    String vmAdminUsername = Optional.ofNullable(instance.getCredentials())
            .map(InstanceCredentials::getUsername).orElse(defaultUsername);
    String vmAdminPassword = Optional.ofNullable(instance.getCredentials())
            .map(InstanceCredentials::getPassword).orElse(defaultPassword);
    Optional<String> vmAdminSSHPubKey = Optional.ofNullable(instance.getCredentials())
            .map(InstanceCredentials::getPublicKey);

    // Retrieve number of instances within the Scale Set
    int vmssNbOfInstances = Integer
            .valueOf(Optional.ofNullable(instance.getNumber()).orElse(SINGLE_INSTANCE_NUMBER));

    // Retrieve the customScript URL provided by the node source or throw an Exception otherwise.
    String customScriptUrl = Optional.ofNullable(instance.getCustomScriptUrl())
            .orElseThrow(() -> new RuntimeException("ERROR missing customScript URL."));
    final String scriptName = customScriptUrl.substring(customScriptUrl.lastIndexOf('/') + 1,
            customScriptUrl.length());//from  w w w. jav  a 2 s  . co  m
    final String installCommand = "bash " + scriptName;
    List<String> fileUris = new ArrayList<>();
    fileUris.add(customScriptUrl);

    // Retrieve the provided VNET or create a new one
    Network network = optionalVirtualNetwork.orElse(azureService.networks().define(azureVNetName)
            .withRegion(region).withExistingResourceGroup(resourceGroup).withAddressSpace(vmssNetAddressSpace)
            .defineSubnet(azureSubnetName).withAddressPrefix(vmssNetAddressPrefix).attach().create());

    // Retrieve the provided public IP address or create a new one
    PublicIpAddress publicIPAddress = options.map(Options::getPublicIpAddress)
            .map(publicIpAddresses -> azureProviderUtils
                    .searchPublicIpAddressByIp(azureService, publicIpAddresses).get())
            .orElse(azureService.publicIpAddresses().define(azureIPName).withRegion(region)
                    .withExistingResourceGroup(resourceGroup).withLeafDomainLabel(azureIPName).create());

    // Create a dedicated LB with the required rules
    LoadBalancer lb = createLoadBalancer(azureService, region, resourceGroup, publicIPAddress);

    // Create the Scale Set (multi-stages)
    VirtualMachineScaleSet virtualMachineScaleSet = createVMSS(azureService, region, resourceGroup, instance,
            network, lb, imageNameOrId, vmAdminUsername, vmAdminSSHPubKey, vmAdminPassword, vmssNbOfInstances,
            fileUris, installCommand);

    logger.info(
            "Azure Scale set '" + azureScaleSetName + "'" + " created inside resource group " + resourceGroup);

    // Return the list of VMs of the Scale Set
    return virtualMachineScaleSet.virtualMachines().list().stream()
            .map(vm -> instance.withTag(vm.name()).withId(vm.id()).withNumber(SINGLE_INSTANCE_NUMBER))
            .collect(Collectors.toSet());
}

From source file:com.bouncestorage.swiftproxy.v1.AccountResource.java

@GET
public Response getAccount(@NotNull @PathParam("account") String account,
        @QueryParam("limit") Optional<Integer> limit, @QueryParam("marker") Optional<String> marker,
        @QueryParam("end_marker") Optional<String> endMarker, @QueryParam("format") Optional<String> format,
        @QueryParam("prefix") Optional<String> prefix, @QueryParam("delimiter") Optional<String> delimiter,
        @HeaderParam("X-Auth-Token") String authToken,
        @HeaderParam("X-Newest") @DefaultValue("false") boolean newest,
        @HeaderParam("Accept") Optional<String> accept) {
    delimiter.ifPresent(x -> logger.info("delimiter not supported yet"));

    BlobStore blobStore = getBlobStore(authToken).get();
    ArrayList<ContainerEntry> entries = blobStore.list().stream().map(StorageMetadata::getName)
            .filter(name -> marker.map(m -> name.compareTo(m) > 0).orElse(true))
            .filter(name -> endMarker.map(m -> name.compareTo(m) < 0).orElse(true))
            .filter(name -> prefix.map(name::startsWith).orElse(true)).map(ContainerEntry::new)
            .collect(Collectors.toCollection(ArrayList::new));

    MediaType formatType;/* w w  w . j ava 2  s  .  com*/
    if (format.isPresent()) {
        formatType = BounceResourceConfig.getMediaType(format.get());
    } else if (accept.isPresent()) {
        formatType = MediaType.valueOf(accept.get());
    } else {
        formatType = MediaType.TEXT_PLAIN_TYPE;
    }

    if (blobStore.getContext().unwrap().getId().equals("transient")) {
        entries.sort((a, b) -> a.getName().compareTo(b.getName()));
    }

    long count = entries.size();
    limit.ifPresent((max) -> {
        if (entries.size() > max) {
            entries.subList(max, entries.size()).clear();
        }
    });

    Account root = new Account();
    root.name = account;
    root.container = entries;
    return output(root, entries, formatType).header("X-Account-Container-Count", count)
            .header("X-Account-Object-Count", -1).header("X-Account-Bytes-Used", -1).header("X-Timestamp", -1)
            .header("X-Trans-Id", -1).header("Accept-Ranges", "bytes").build();
}

From source file:cito.stomp.Frame.java

/**
 * /* w  w  w. ja  v  a 2 s  . c  om*/
 * @param command
 * @param headers
 * @param body
 */
Frame(@Nonnull Command command, @Nonnull Map<Header, List<String>> headers,
        @Nonnull Optional<ByteBuffer> body) {
    this.command = requireNonNull(command);
    final Map<Header, List<String>> tmpHeaders = new LinkedHashMap<>(headers);
    tmpHeaders.entrySet().forEach(e -> e.setValue(unmodifiableList(e.getValue())));
    this.headers = unmodifiableMap(tmpHeaders);
    this.body = body.map(ByteBuffer::asReadOnlyBuffer);
}