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.ikanow.aleph2.management_db.services.DataBucketCrudService.java

/** Deletes the entire bucket, ie data and state
 * @param to_delete//  ww w.j  a va2s .  c  o m
 * @param storage_service
 */
public static void removeBucketPath(final DataBucketBean to_delete, final IStorageService storage_service,
        Optional<String> extra_path) throws Exception {
    final FileContext dfs = storage_service.getUnderlyingPlatformDriver(FileContext.class, Optional.empty())
            .get();
    final String bucket_root = storage_service.getBucketRootPath() + "/" + to_delete.full_name()
            + IStorageService.BUCKET_SUFFIX;
    dfs.delete(new Path(bucket_root + extra_path.map(s -> "/" + s).orElse("")), true);
}

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

private boolean precedesLastRegisteredActivity(ActivityPayload payload,
        Optional<ActivityDto> lastRegisteredActivity) {
    return lastRegisteredActivity.map(lra -> payload.endTime.isBefore(lra.getStartTime())).orElse(false);
}

From source file:org.wallride.web.support.Posts.java

public Object customValue(Post post, String code) {
    Optional<CustomFieldValue> target = post.getCustomFieldValues().stream()
            .filter(v -> v.getCustomField().getCode().equals(code))
            .filter(v -> v.getCustomField().getLanguage().equals(post.getLanguage())).findFirst();
    Object value = target.map(CustomFieldValue::getValue).orElse(null);
    if (value != null && target.get().getCustomField().getFieldType().equals(CustomField.FieldType.HTML)) {
        return parse(target.get().getTextValue());
    }/*from  w  w  w.j a v a2  s  .c o  m*/
    return value;
}

From source file:com.ikanow.aleph2.aleph2_rest_utils.SharedLibraryCrudServiceWrapper.java

@Override
public CompletableFuture<Boolean> deleteObjectById(Object id) {
    //delete from shared lib, then delete from filesys
    //have to get shared lib entry, so we know where the file is on filesys
    final Optional<SharedLibraryBean> shared_library_bean = shared_library_crud.getObjectById(id).join();
    return shared_library_bean.map(slb -> {
        return shared_library_crud.deleteObjectById(id).<Boolean>thenCompose(f -> {
            if (f) {
                final Tuple2<ICrudService<FileDescriptor>, FileDescriptor> storage = getSharedLibraryDataStore(
                        service_context, slb.path_name(), new FileDescriptor(null, null));
                return storage._1.deleteObjectById(storage._2.file_name());
            } else {
                return CompletableFuture.completedFuture(f); //false, shared object delete must have failed
            }/*ww w . j av  a  2  s . c  o m*/
        });
    }).orElseGet(() -> CompletableFuture.completedFuture(false));
}

From source file:alfio.manager.PaymentManager.java

/**
 * This method processes the pending payment using the configured payment gateway (at the time of writing, only STRIPE)
 * and returns a PaymentResult./*w  ww .ja  v a 2  s .com*/
 * In order to preserve the consistency of the payment, when a non-gateway Exception is thrown, it rethrows an IllegalStateException
 *
 * @param reservationId
 * @param gatewayToken
 * @param price
 * @param event
 * @param email
 * @param customerName
 * @param billingAddress
 * @return PaymentResult
 * @throws java.lang.IllegalStateException if there is an error after charging the credit card
 */
PaymentResult processStripePayment(String reservationId, String gatewayToken, int price, Event event,
        String email, CustomerName customerName, String billingAddress) {
    try {
        final Optional<Charge> optionalCharge = stripeManager.chargeCreditCard(gatewayToken, price, event,
                reservationId, email, customerName.getFullName(), billingAddress);
        return optionalCharge.map(charge -> {
            log.info("transaction {} paid: {}", reservationId, charge.getPaid());
            Pair<Long, Long> fees = Optional.ofNullable(charge.getBalanceTransactionObject()).map(bt -> {
                List<Fee> feeDetails = bt.getFeeDetails();
                return Pair.of(
                        Optional.ofNullable(StripeManager.getFeeAmount(feeDetails, "application_fee"))
                                .map(Long::parseLong).orElse(0L),
                        Optional.ofNullable(StripeManager.getFeeAmount(feeDetails, "stripe_fee"))
                                .map(Long::parseLong).orElse(0L));
            }).orElse(null);

            transactionRepository.insert(charge.getId(), null, reservationId, ZonedDateTime.now(), price,
                    event.getCurrency(), charge.getDescription(), PaymentProxy.STRIPE.name(),
                    fees != null ? fees.getLeft() : 0L, fees != null ? fees.getRight() : 0L);
            return PaymentResult.successful(charge.getId());
        }).orElseGet(() -> PaymentResult.unsuccessful("error.STEP2_UNABLE_TO_TRANSITION"));
    } catch (Exception e) {
        if (e instanceof StripeException) {
            return PaymentResult.unsuccessful(stripeManager.handleException((StripeException) e));
        }
        throw new IllegalStateException(e);
    }

}

From source file:com.ikanow.aleph2.analytics.spark.utils.SparkTechnologyUtils.java

/** Creates a command line call to launch spark
 * @param spark_home//www  .  j av  a2s.  c  om
 * @param yarn_home
 * @param spark_master
 * @param main_clazz
 * @param context_signature
 * @param main_jar
 * @param other_jars
 * @param spark_job_options
 * @param spark_system_options
 */
public static ProcessBuilder createSparkJob(final String job_name, final String spark_home,
        final String yarn_home, final String spark_master, final Optional<String> maybe_main_clazz,
        final String context_signature, final Optional<String> test_signature, final String main_jar_or_py,
        final Collection<String> other_jars, final Collection<String> other_files,
        final Collection<String> other_lang_files, final List<String> external_jars,
        final List<String> external_files, final List<String> external_lang_files,
        final Optional<Map<String, Object>> spark_generic_options, final Map<String, String> spark_job_options,
        final Map<String, String> spark_system_options

) {
    //https://spark.apache.org/docs/1.2.0/submitting-applications.html

    final List<String> command_line = ImmutableList.<String>builder().add(SBT_SUBMIT_BINARY).add("--name")
            .add(job_name)
            .addAll(maybe_main_clazz.map(main_clazz -> Arrays.asList("--class", main_clazz))
                    .orElse(Collections.emptyList()))
            .add("--master").add(spark_master).add("--jars")
            .add(Stream.concat(other_jars.stream(), external_jars.stream()).collect(Collectors.joining(",")))
            .addAll(Optional
                    .of(Stream.concat(other_files.stream(), external_files.stream())
                            .collect(Collectors.joining(",")))
                    .filter(s -> !s.isEmpty()).map(s -> Arrays.asList("--files", s))
                    .orElse(Collections.emptyList()))
            //TODO (ALEPH-63): handle R in the example below
            .addAll(Optional
                    .of(Stream.concat(other_lang_files.stream(), external_lang_files.stream())
                            .collect(Collectors.joining(",")))
                    .filter(s -> !s.isEmpty()).map(s -> Arrays.asList("--py-files", s))
                    .orElse(Collections.emptyList()))
            .addAll(Optional.ofNullable(System.getProperty("hdp.version")).map(hdp_version -> { // Set HDP version from whatever I'm set to
                return (List<String>) ImmutableList.<String>of("--conf",
                        "spark.executor.extraJavaOptions=-Dhdp.version=" + hdp_version, "--conf",
                        "spark.driver.extraJavaOptions=-Dhdp.version=" + hdp_version, "--conf",
                        "spark.yarn.am.extraJavaOption=-Dhdp.version=" + hdp_version);
            }).orElse(Collections.emptyList()))
            .addAll(spark_job_options.isEmpty() ? Collections.emptyList()
                    : spark_job_options.entrySet().stream()
                            .flatMap(kv -> Stream.of("--conf", kv.getKey() + "=" + kv.getValue()))
                            .collect(Collectors.toList()))
            .addAll(spark_system_options.entrySet().stream()
                    .flatMap(kv -> Stream.of(kv.getKey(), kv.getValue())).collect(Collectors.toList()))
            .addAll(spark_generic_options.map(opts -> Arrays.asList("--conf",
                    SparkTopologyConfigBean.JOB_CONFIG_KEY + "="
                            + BeanTemplateUtils.configureMapper(Optional.empty()).convertValue(opts,
                                    JsonNode.class)))
                    .orElse(Collections.emptyList()))
            .add(main_jar_or_py).add(context_signature)
            .addAll(test_signature.map(ts -> Arrays.asList(ts)).orElse(Collections.emptyList())).build();

    final ProcessBuilder pb = new ProcessBuilder();

    final Map<String, String> mutable_env = pb.environment();
    mutable_env.put("HADOOP_CONF_DIR", yarn_home);

    return pb.directory(new File(spark_home)).command(command_line);
}

From source file:fi.csc.kapaVirtaAS.MessageTransformer.java

public String createAuthenticationString(String message) {
    try {/*from   w  w  w . java 2 s.  c o  m*/
        DocumentBuilder dBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document doc = dBuilder
                .parse(new InputSource(new ByteArrayInputStream(stripXmlDefinition(message).getBytes())));
        doc.setXmlVersion("1.0");
        doc.normalizeDocument();

        Optional<NodeList> headerNodes = getChildByKeyword(
                nodeListToStream(doc.getDocumentElement().getChildNodes()), "header");
        Optional<NodeList> clientHeaders = headerNodes
                .map(nodeList -> getChildByKeyword(nodeListToStream(nodeList), "client"))
                .orElse(Optional.empty());

        Number l = clientHeaders.get().getLength();
        l.toString();

        return clientHeaders
                .map(nodeList -> getNodeByKeyword(nodeListToStream(nodeList), "xRoadInstance")
                        .map(node -> node.getTextContent()))
                .orElse(Optional.empty()).orElse("")
                + ":"
                + clientHeaders.map(nodeList -> getNodeByKeyword(nodeListToStream(nodeList), "memberClass")
                        .map(node -> node.getTextContent())).orElse(Optional.empty()).orElse("")
                + ":"
                + clientHeaders.map(nodeList -> getNodeByKeyword(nodeListToStream(nodeList), "memberCode")
                        .map(node -> node.getTextContent())).orElse(Optional.empty()).orElse("")
                + ":"
                + clientHeaders.map(nodeList -> getNodeByKeyword(nodeListToStream(nodeList), "subsystemCode")
                        .map(node -> node.getTextContent())).orElse(Optional.empty()).orElse("");
    } catch (Exception e) {
        log.error("Error in parsing authenticationstring");
        log.error(e.toString());
        return "";
    }
}

From source file:alfio.manager.CheckInManager.java

public boolean manualCheckIn(int eventId, String ticketIdentifier, String user) {
    Optional<Ticket> ticket = findAndLockTicket(ticketIdentifier);
    return ticket.map((t) -> {

        if (t.getStatus() == TicketStatus.TO_BE_PAID) {
            acquire(ticketIdentifier);//from   w ww.  j  a  v  a  2  s.co  m
        }

        checkIn(ticketIdentifier);
        scanAuditRepository.insert(ticketIdentifier, eventId, ZonedDateTime.now(), user, SUCCESS,
                ScanAudit.Operation.SCAN);
        auditingRepository.insert(t.getTicketsReservationId(),
                userRepository.findIdByUserName(user).orElse(null), eventId, Audit.EventType.MANUAL_CHECK_IN,
                new Date(), Audit.EntityType.TICKET, Integer.toString(t.getId()));
        return true;
    }).orElse(false);
}

From source file:com.netflix.spinnaker.clouddriver.kubernetes.v2.caching.view.provider.KubernetesV2ClusterProvider.java

@Override
public KubernetesV2ServerGroup getServerGroup(String account, String namespace, String name) {
    Pair<KubernetesKind, String> parsedName;
    try {/* ww w  .j  av  a 2 s. com*/
        parsedName = KubernetesManifest.fromFullResourceName(name);
    } catch (IllegalArgumentException e) {
        return null;
    }

    KubernetesKind kind = parsedName.getLeft();
    String shortName = parsedName.getRight();
    String key = Keys.infrastructure(kind, account, namespace, shortName);
    List<String> relatedTypes = kindMap.translateSpinnakerKind(INSTANCES).stream().map(KubernetesKind::toString)
            .collect(Collectors.toList());

    relatedTypes.addAll(kindMap.translateSpinnakerKind(LOAD_BALANCERS).stream().map(KubernetesKind::toString)
            .collect(Collectors.toList()));

    Optional<CacheData> serverGroupData = cacheUtils.getSingleEntryWithRelationships(kind.toString(), key,
            relatedTypes.toArray(new String[relatedTypes.size()]));

    return serverGroupData.map(cd -> {
        List<CacheData> instanceData = kindMap.translateSpinnakerKind(INSTANCES).stream()
                .map(k -> cacheUtils.loadRelationshipsFromCache(Collections.singletonList(cd), k.toString()))
                .flatMap(Collection::stream).collect(Collectors.toList());

        List<CacheData> loadBalancerData = kindMap.translateSpinnakerKind(LOAD_BALANCERS).stream()
                .map(k -> cacheUtils.loadRelationshipsFromCache(Collections.singletonList(cd), k.toString()))
                .flatMap(Collection::stream).collect(Collectors.toList());

        return cacheUtils.<KubernetesV2ServerGroup>resourceModelFromCacheData(
                KubernetesV2ServerGroupCacheData.builder().serverGroupData(cd).instanceData(instanceData)
                        .loadBalancerData(loadBalancerData).build());
    }).orElse(null);
}

From source file:com.ikanow.aleph2.data_model.utils.CrudServiceUtils.java

/** CRUD service proxy that optionally adds an extra term and allows the user to modify the results after they've run (eg to apply security service settings) 
 * @author Alex/*from  w  ww  .  ja  v a  2 s. co  m*/
 */
@SuppressWarnings("unchecked")
public static <T> ICrudService<T> intercept(final Class<T> clazz, final ICrudService<T> delegate,
        final Optional<QueryComponent<T>> extra_query,
        final Optional<Function<QueryComponent<T>, QueryComponent<T>>> query_transform,
        final Map<String, BiFunction<Object, Object[], Object>> interceptors,
        final Optional<BiFunction<Object, Object[], Object>> default_interceptor) {
    InvocationHandler handler = new InvocationHandler() {
        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            final Method m = delegate.getClass().getMethod(method.getName(), method.getParameterTypes());

            // First off, apply the extra term to any relevant args:
            final Object[] args_with_extra_query_pretransform = query_transform.map(q -> {
                return (null != args) ? Arrays.stream(args)
                        .map(o -> (null != o) && QueryComponent.class.isAssignableFrom(o.getClass())
                                ? q.apply((QueryComponent<T>) o)
                                : o)
                        .collect(Collectors.toList()).toArray() : args;
            }).orElse(args);

            final Object[] args_with_extra_query = extra_query.map(q -> {
                return (null != args_with_extra_query_pretransform)
                        ? Arrays.stream(args_with_extra_query_pretransform)
                                .map(o -> (null != o) && QueryComponent.class.isAssignableFrom(o.getClass())
                                        ? CrudUtils.allOf((QueryComponent<T>) o, q)
                                        : o)
                                .collect(Collectors.toList()).toArray()
                        : args_with_extra_query_pretransform;
            }).orElse(args_with_extra_query_pretransform);

            // Special cases for: readOnlyVersion, getFilterdRepo / countObjects / getRawService / *byId
            final Object o = Lambdas.get(() -> {
                final SingleQueryComponent<T> base_query = JsonNode.class.equals(clazz)
                        ? (SingleQueryComponent<T>) CrudUtils.allOf()
                        : CrudUtils.allOf(clazz);

                try {
                    if (extra_query.isPresent() && m.getName().equals("countObjects")) { // special case....change method and apply spec
                        return delegate.countObjectsBySpec(extra_query.get());
                    } else if (extra_query.isPresent() && m.getName().equals("getObjectById")) { // convert from id to spec and append extra_query
                        if (1 == args.length) {
                            return delegate.getObjectBySpec(CrudUtils.allOf(extra_query.get(),
                                    base_query.when(JsonUtils._ID, args[0])));
                        } else {
                            return delegate.getObjectBySpec(
                                    CrudUtils.allOf(extra_query.get(), base_query.when(JsonUtils._ID, args[0])),
                                    (List<String>) args[1], (Boolean) args[2]);
                        }
                    } else if (extra_query.isPresent() && m.getName().equals("deleteDatastore")) {
                        CompletableFuture<Long> l = delegate.deleteObjectsBySpec(extra_query.get());
                        return l.thenApply(ll -> ll > 0);
                    } else if (extra_query.isPresent() && m.getName().equals("deleteObjectById")) { // convert from id to spec and append extra_query
                        return delegate.deleteObjectBySpec(
                                CrudUtils.allOf(extra_query.get(), base_query.when(JsonUtils._ID, args[0])));
                    } else if (extra_query.isPresent() && m.getName().equals("updateObjectById")) { // convert from id to spec and append extra_query
                        return delegate.updateObjectBySpec(
                                CrudUtils.allOf(extra_query.get(), base_query.when(JsonUtils._ID, args[0])),
                                Optional.empty(), (UpdateComponent<T>) args[1]);
                    } else if (m.getName().equals("getRawService")) { // special case....convert the default query to JSON, if present
                        Object o_internal = m.invoke(delegate, args_with_extra_query);
                        Optional<QueryComponent<JsonNode>> json_extra_query = extra_query
                                .map(qc -> qc.toJson());
                        return intercept(JsonNode.class, (ICrudService<JsonNode>) o_internal, json_extra_query,
                                Optional.empty(), interceptors, default_interceptor);
                    } else { // wrap any CrudService types
                        Object o_internal = m.invoke(delegate, args_with_extra_query);
                        return (null != o_internal)
                                && ICrudService.class.isAssignableFrom(o_internal.getClass())
                                        ? intercept(clazz, (ICrudService<T>) o_internal, extra_query,
                                                Optional.empty(), interceptors, default_interceptor)
                                        : o_internal;
                    }
                } catch (IllegalAccessException ee) {
                    throw new RuntimeException(ee);
                } catch (InvocationTargetException e) {
                    throw new RuntimeException(e.getCause().getMessage(), e);
                }
            });

            return interceptors
                    .getOrDefault(m.getName(),
                            default_interceptor.orElse(CrudServiceUtils::identityInterceptor))
                    .apply(o, args_with_extra_query);
        }
    };

    return ICrudService.IReadOnlyCrudService.class.isAssignableFrom(delegate.getClass())
            ? (ICrudService<T>) Proxy.newProxyInstance(ICrudService.IReadOnlyCrudService.class.getClassLoader(),
                    new Class[] { ICrudService.IReadOnlyCrudService.class }, handler)
            : (ICrudService<T>) Proxy.newProxyInstance(ICrudService.class.getClassLoader(),
                    new Class[] { ICrudService.class }, handler);
}