Example usage for java.util Optional ifPresent

List of usage examples for java.util Optional ifPresent

Introduction

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

Prototype

public void ifPresent(Consumer<? super T> action) 

Source Link

Document

If a value is present, performs the given action with the value, otherwise does nothing.

Usage

From source file:com.ikanow.aleph2.analytics.services.DeduplicationService.java

@Override
public Collection<BasicMessageBean> validateModule(IEnrichmentModuleContext context, DataBucketBean bucket,
        EnrichmentControlMetadataBean control) {

    final LinkedList<BasicMessageBean> mutable_errs = new LinkedList<>();

    // Validation

    // 1) Check that has doc schema enabled unless override set 

    final DedupConfigBean dedup_config = BeanTemplateUtils
            .from(Optional.ofNullable(control.config()).orElse(Collections.emptyMap()), DedupConfigBean.class)
            .get();/*from   w  w  w .ja  va2 s.  c o m*/

    final DocumentSchemaBean doc_schema = Optional.ofNullable(dedup_config.doc_schema_override())
            .orElse(bucket.data_schema().document_schema()); //(exists by construction)
    if (null == doc_schema) { // Has to either have a doc schema or an override 
        mutable_errs.add(ErrorUtils.buildErrorMessage(this.getClass().getSimpleName(), "validateModule",
                ErrorUtils.get(ErrorUtils.MISSING_DOCUMENT_SERVICE)));
        return mutable_errs; //(no point going any further here)
    }

    if (!Optional.ofNullable(doc_schema.lookup_service_override()).filter(s -> !s.isEmpty()).isPresent()) {
        final boolean doc_schema_enabled = Optionals.of(() -> bucket.data_schema().document_schema())
                .map(ds -> Optional.ofNullable(ds.enabled()).orElse(true)).orElse(false);
        if (!doc_schema_enabled) {
            mutable_errs.add(ErrorUtils.buildErrorMessage(this.getClass().getSimpleName(), "validateModule",
                    ErrorUtils.get(ErrorUtils.MISSING_DOCUMENT_SERVICE)));
        }
    }
    //(else up to the user to ensure that the required service is included)

    // 1.5) Validate that the service override is valid

    final Validation<String, Tuple2<Optional<Class<? extends IUnderlyingService>>, Optional<String>>> service_to_use = getDataService(
            doc_schema);

    if (service_to_use.isFail()) {
        mutable_errs.add(ErrorUtils.buildErrorMessage(this.getClass().getSimpleName(), "validateModule",
                service_to_use.fail()));
    }

    // 2) Validate any child modules

    Optional<EnrichmentControlMetadataBean> custom_config = Optionals
            .ofNullable(doc_schema.custom_deduplication_configs()).stream()
            .filter(cfg -> Optional.ofNullable(cfg.enabled()).orElse(true)).findFirst();

    custom_config.ifPresent(cfg -> {
        mutable_errs.addAll(getEnrichmentModules(context, cfg).stream()
                .flatMap(module -> module.validateModule(context, bucket, cfg).stream())
                .collect(Collectors.toList()));
    });
    return mutable_errs;
}

From source file:nu.yona.server.ThymeleafConfigurationTest.java

private String buildEmailBuddy(Optional<Locale> locale, String buddyFirstName, String buddyLastName,
        String inviteUrl, String personalInvitationMessage, String requestingUserFirstName,
        String requestingUserLastName, String requestingUserMobileNumber, String requestingUserNickname) {
    Context ctx = ThymeleafUtil.createContext();
    ctx.setVariable("buddyFirstName", buddyFirstName);
    ctx.setVariable("buddyLastName", buddyLastName);
    ctx.setVariable("inviteUrl", inviteUrl);
    ctx.setVariable("personalInvitationMessage", personalInvitationMessage);
    ctx.setVariable("requestingUserFirstName", requestingUserFirstName);
    ctx.setVariable("requestingUserLastName", requestingUserLastName);
    ctx.setVariable("requestingUserMobileNumber", requestingUserMobileNumber);
    ctx.setVariable("requestingUserNickname", requestingUserNickname);
    ctx.setVariable("includedMediaBaseUrl", "https://app.prd.yona.nu/media/");
    locale.ifPresent(l -> ctx.setLocale(l));

    return emailTemplateEngine.process("buddy-invitation-body.html", ctx);
}

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

private <REQ extends Message, RESP extends Message> Handler<AsyncResult<Void>> messageConsumerCompletionHandler(
        final String address, final Optional<Handler<AsyncResult<Void>>> handler,
        final MessageConsumerConfig<REQ, RESP> config) {
    return (AsyncResult<Void> result) -> {
        if (result.succeeded()) {
            info.log("messageConsumerCompletionHandler.succeeded",
                    () -> messageConsumerLogInfo(address, config));
        } else {/*  ww w.j  av a  2  s .  co  m*/
            error.log("messageConsumerCompletionHandler.failed", () -> messageConsumerLogInfo(address, config),
                    result.cause());
        }
        handler.ifPresent(h -> h.handle(result));
    };
}

From source file:at.medevit.elexis.emediplan.core.internal.EMediplanServiceImpl.java

private void createPdf(Optional<Image> qrCode, Object jaxbModel, OutputStream output) {
    BundleContext bundleContext = FrameworkUtil.getBundle(getClass()).getBundleContext();
    ServiceReference<IFormattedOutputFactory> fopFactoryRef = bundleContext
            .getServiceReference(IFormattedOutputFactory.class);
    if (fopFactoryRef != null) {
        IFormattedOutputFactory fopFactory = bundleContext.getService(fopFactoryRef);
        IFormattedOutput foOutput = fopFactory.getFormattedOutputImplementation(ObjectType.JAXB,
                OutputType.PDF);//  w ww .  j  a  v  a2 s  . com
        HashMap<String, String> parameters = new HashMap<>();
        parameters.put("logoJpeg", getEncodedLogo());
        qrCode.ifPresent(qr -> {
            parameters.put("qrJpeg", getEncodedQr(qr));
        });
        foOutput.transform(jaxbModel,
                EMediplanServiceImpl.class.getResourceAsStream("/rsc/xslt/emediplan.xslt"), output, parameters);
        bundleContext.ungetService(fopFactoryRef);
    } else {
        throw new IllegalStateException("No IFormattedOutputFactory available");
    }
}

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   ww w  .j a va2 s. co 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:com.ikanow.aleph2.v1.document_db.utils.V1DocumentDbHadoopUtils.java

/** 
 * @param input_config - the input settings
 * @return//from   w w w. j  a  v a2 s  . co  m
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public static IAnalyticsAccessContext<InputFormat> getInputFormat(final String user_id,
        final AnalyticThreadJobBean.AnalyticThreadJobInputBean job_input,
        final Optional<ISecurityService> maybe_security, final V1DocDbConfigBean config) {
    //TODO (ALEPH-20): need to perform security in here

    return new IAnalyticsAccessContext<InputFormat>() {
        private LinkedHashMap<String, Object> _mutable_output = null;

        @Override
        public String describe() {
            //(return the entire thing)
            return ErrorUtils.get("service_name={0} options={1}",
                    this.getAccessService().right().value().getSimpleName(),
                    this.getAccessConfig().get().entrySet().stream()
                            .filter(kv -> !DESCRIBE_FILTER.contains(kv.getKey()))
                            .collect(Collectors.toMap(kv -> kv.getKey(), kv -> kv.getValue())));
        }

        /* (non-Javadoc)
         * @see com.ikanow.aleph2.data_model.interfaces.data_analytics.IAnalyticsAccessContext#getAccessService()
         */
        @Override
        public Either<InputFormat, Class<InputFormat>> getAccessService() {
            return Either.right((Class<InputFormat>) (Class<?>) Aleph2V1InputFormat.class);
        }

        /* (non-Javadoc)
         * @see com.ikanow.aleph2.data_model.interfaces.data_analytics.IAnalyticsAccessContext#getAccessConfig()
         */
        @Override
        public Optional<Map<String, Object>> getAccessConfig() {
            if (null != _mutable_output) {
                return Optional.of(_mutable_output);
            }
            _mutable_output = new LinkedHashMap<>();

            // Parse various inputs:

            final List<String> communities = Arrays
                    .stream(job_input.resource_name_or_id()
                            .substring(BucketUtils.EXTERNAL_BUCKET_PREFIX.length()).split("_"))
                    .collect(Collectors.toList());

            // Validate communities:
            maybe_security.ifPresent(sec -> {
                communities.stream().filter(cid -> !sec.isUserPermitted(user_id, Tuples._2T("community", cid),
                        Optional.of(ISecurityService.ACTION_READ))).findAny().ifPresent(cid -> {
                            throw new RuntimeException(ErrorUtils
                                    .get(V1DocumentDbErrorUtils.V1_DOCUMENT_USER_PERMISSIONS, user_id, cid));
                        });
            });

            final String query = _mapper
                    .convertValue(Optional.ofNullable(job_input.filter()).orElse(Collections.emptyMap()),
                            JsonNode.class)
                    .toString();

            final Tuple4<String, Tuple2<Integer, Integer>, BasicDBObject, DBObject> horrible_object = LegacyV1HadoopUtils
                    .parseQueryObject(query, communities);

            final String db_server = config.mongodb_connection();

            // Here's all the fields to fill in

            // 1) Generic MongoDB fields:
            //name of job shown in jobtracker --><name>mongo.job.name</name><value>title
            //run the job verbosely ? --><name>mongo.job.verbose</name><value>true
            //Run the job in the foreground and wait for response, or background it? --><name>mongo.job.background</name><value>false
            //If you are reading from mongo, the URI --><name>mongo.input.uri</name><value>mongodb://"+dbserver+"/"+input
            //The number of documents to limit to for read [OPTIONAL] --><name>mongo.input.limit</name><value>" + nLimit
            //The query, in JSON, to execute [OPTIONAL] --><name>mongo.input.query</name><value>" + StringEscapeUtils.escapeXml(query)
            //The fields, in JSON, to read [OPTIONAL] --><name>mongo.input.fields</name><value>"+( (fields==null) ? ("") : fields )
            //InputFormat Class --><name>mongo.job.input.format</name><value>com.ikanow.infinit.e.data_model.custom.InfiniteMongoInputFormat

            _mutable_output.put("mongo.job.name",
                    Optional.ofNullable(job_input.data_service()).orElse("unknown") + ":"
                            + Optional.ofNullable(job_input.resource_name_or_id()).orElse("unknown")); // (i think this is ignored in fact)            
            _mutable_output.put("mongo.job.verbose", "true");
            _mutable_output.put("mongo.job.background", "false");
            _mutable_output.put("mongo.input.uri", "mongodb://" + db_server + "/doc_metadata.metadata");
            _mutable_output.put("mongo.input.query", horrible_object._1());
            _mutable_output.put("mongo.input.fields",
                    Optional.ofNullable(horrible_object._4()).map(o -> o.toString()).orElse(""));
            _mutable_output.put("mongo.input.limit", Optional.ofNullable(job_input.config())
                    .map(cfg -> cfg.test_record_limit_request()).map(o -> o.toString()).orElse("0"));

            // 2) Basic Infinit.e/MongoDB fields:
            //Maximum number of splits [optional] --><name>max.splits</name><value>"+nSplits
            //Maximum number of docs per split [optional] --><name>max.docs.per.split</name><value>"+nDocsPerSplit
            _mutable_output.put("max.splits", horrible_object._2()._1().toString());
            _mutable_output.put("max.docs.per.split", horrible_object._2()._2().toString());

            // 3) Advanced Infinit.e/MongoDB fields:            
            //Infinit.e src tags filter [optional] --><name>infinit.e.source.tags.filter</name><value>"+srcTags.toString()
            if (null != horrible_object._3()) {
                _mutable_output.put("infinit.e.source.tags.filter", horrible_object._3().toString());
            }
            return Optional.of(Collections.unmodifiableMap(_mutable_output));
        }
    };
}

From source file:ai.grakn.graql.GraqlShell.java

/**
 * Create a new Graql shell//from   w  w  w .  j a  va 2  s .  c o  m
 */
GraqlShell(String historyFilename, String keyspace, Optional<String> username, Optional<String> password,
        GraqlClient client, URI uri, Optional<List<String>> queryStrings, String outputFormat,
        boolean showImplicitTypes, boolean infer, boolean materialise) throws Throwable {

    this.historyFilename = historyFilename;

    try {
        console = new ConsoleReader(System.in, System.out);
        session = new JsonSession(client, uri);

        // Send the requested keyspace and output format to the server once connected
        Json initJson = Json.object(ACTION, ACTION_INIT, KEYSPACE, keyspace, OUTPUT_FORMAT, outputFormat,
                IMPLICIT, showImplicitTypes, INFER, infer, MATERIALISE, materialise);
        username.ifPresent(u -> initJson.set(USERNAME, u));
        password.ifPresent(p -> initJson.set(PASSWORD, p));
        session.sendJson(initJson);

        // Wait to receive confirmation
        handleMessagesFromServer();

        // If session has closed, then we couldn't authorise
        if (!session.isOpen()) {
            return;
        }

        // Start shell
        start(queryStrings);

    } finally {
        client.close();
        console.flush();
    }
}

From source file:com.nestedbird.modules.formparser.FormParse.java

/**
 * Updates a BaseEntity in the database/*w  w w  . j av a2  s . co  m*/
 *
 * @param value     data to edit
 * @param fieldType type of baseentity
 * @return edited base entity
 * @throws JSONException the exception
 */
private BaseEntity parseBaseEntity(final JSONObject value, final Class fieldType) throws JSONException {
    final JpaRepository repository = getFieldRepository(fieldType);
    Optional<BaseEntity> entity = Optional.empty();

    if (value.has("id") && (!value.isNull("id"))) {
        final String id = value.get("id").toString();
        entity = Optional.ofNullable((BaseEntity) repository.findOne(id));
    }

    if (!entity.isPresent()) {
        try {
            entity = Optional.ofNullable((BaseEntity) Class.forName(fieldType.getName()).newInstance());
        } catch (InstantiationException | ClassNotFoundException | IllegalAccessException e1) {
            logger.info("[FormParse] [parseBaseEntity] Failure To Create Class Instance", e1);
        }
    }
    entity.ifPresent(e -> {
        final ParameterMapParser parser = new ParameterMapParser(value);
        parser.loopData((key, data) -> writeToEntity(e, key, data));
        repository.saveAndFlush(e);
    });

    return entity.orElseGet(null);
}

From source file:com.ikanow.aleph2.graph.titan.utils.TitanGraphBuildingUtils.java

/** Calls user merge on the various possibly duplicate elements, and sorts out user responses
 * @param tx// w  w w.  j  av a  2  s.  com
 * @param config
 * @param security_service
 * @param logger
 * @param maybe_merger
 * @param titan_mapper
 * @param element_type
 * @param key
 * @param new_elements
 * @param existing_elements
 * @return
 */
protected static <O extends Element> List<O> invokeUserMergeCode(final TitanTransaction tx,
        final GraphSchemaBean config, final Tuple2<String, ISecurityService> security_service,
        final Optional<IBucketLogger> logger,
        final Optional<Tuple2<IEnrichmentBatchModule, GraphMergeEnrichmentContext>> maybe_merger,
        final org.apache.tinkerpop.shaded.jackson.databind.ObjectMapper titan_mapper,
        final MutableStatsBean mutable_stats, final Class<O> element_type, final String bucket_path,
        final ObjectNode key, final Collection<ObjectNode> new_elements, final Collection<O> existing_elements,
        final Map<ObjectNode, Vertex> mutable_existing_vertex_store) {
    if (existing_elements.isEmpty() && (1 == new_elements.size()) && !config.custom_finalize_all_objects()) {

        return validateUserElement(new_elements.stream().findFirst().get(), config)
                .bind(el -> addGraphSON2Graph(bucket_path, key, el, mutable_existing_vertex_store,
                        Collections.emptyMap(), tx, element_type, mutable_stats))
                .<List<O>>validation(fail -> {
                    if (Vertex.class.isAssignableFrom(element_type))
                        mutable_stats.vertex_errors++;
                    else if (Edge.class.isAssignableFrom(element_type))
                        mutable_stats.edge_errors++;

                    logger.ifPresent(l -> l.inefficientLog(Level.DEBUG,
                            BeanTemplateUtils.clone(fail)
                                    .with(BasicMessageBean::source, "GraphBuilderEnrichmentService")
                                    .with(BasicMessageBean::command, "system.onObjectBatch").done()));
                    //(keep this here for c/p purposes .. if want to attach an expensive "details" object then could do that by copying the fields across one by one)                        
                    //                        logger.ifPresent(l -> l.log(Level.DEBUG,                        
                    //                              ErrorUtils.lazyBuildMessage(true, () -> "GraphBuilderEnrichmentService", 
                    //                                    () -> "system.onObjectBatch", 
                    //                                    () -> null, 
                    //                                    () -> ErrorUtils.get("MESSAGE", params),
                    //                                    () -> null)
                    //                                    ));                  

                    return Collections.emptyList();
                }, success -> Arrays.<O>asList(success));
    } else {
        // (just gives me the elements indexed by their ids so we can get them back again later)
        // (we'll convert to string as a slightly inefficient way of ensuring the same code can handle both edge andv vertex cases)
        final Map<String, Optional<O>> mutable_existing_element_vs_id_store = existing_elements.stream()
                .collect(Collectors.toMap(e -> e.id().toString(), e -> Optional.of(e)));

        return maybe_merger.<List<O>>map(merger -> {

            final Stream<Tuple2<Long, IBatchRecord>> in_stream = Stream.concat(
                    new_elements.stream().map(j -> Tuples._2T(0L, new BatchRecordUtils.JsonBatchRecord(j))),
                    existing_elements.stream().sorted((a, b) -> ((Long) a.id()).compareTo((Long) b.id())) // (ensure first found element has the lowest id)
                            .map(v -> _mapper.convertValue(titan_mapper.convertValue(v, Map.class),
                                    JsonNode.class))
                            .map(j -> Tuples._2T(0L, new BatchRecordUtils.InjectedJsonBatchRecord(j))));

            merger._2().initializeMerge(element_type);

            merger._1().onObjectBatch(in_stream, Optional.of(new_elements.size()), Optional.of(key));

            return merger._2().getAndResetElementList().stream()
                    .map(o -> addGraphSON2Graph(bucket_path, key, o, mutable_existing_vertex_store,
                            mutable_existing_element_vs_id_store, tx, element_type, mutable_stats))
                    .<O>flatMap(v -> v.validation(fail -> {
                        if (Vertex.class.isAssignableFrom(element_type))
                            mutable_stats.vertex_errors++;
                        else if (Edge.class.isAssignableFrom(element_type))
                            mutable_stats.edge_errors++;

                        logger.ifPresent(l -> l.inefficientLog(Level.DEBUG,
                                BeanTemplateUtils.clone(fail)
                                        .with(BasicMessageBean::source, "GraphBuilderEnrichmentService")
                                        .with(BasicMessageBean::command, "system.onObjectBatch").done()));

                        return Stream.empty();
                    }, success -> Stream.of(success))).collect(Collectors.toList());
        }).orElse(Collections.emptyList());
    }
}

From source file:com.orange.ngsi2.server.Ngsi2BaseController.java

/**
 * Endpoint delete /v2/entities/{entityId}
 * @param entityId the entity ID//from w  w w  . j a v a 2 s.c om
 * @param type an optional type of entity
 * @return http status 204 (no content)
 * @throws Exception
 */
@RequestMapping(method = RequestMethod.DELETE, value = { "/entities/{entityId}" })
final public ResponseEntity removeEntityEndpoint(@PathVariable String entityId,
        @RequestParam Optional<String> type) throws Exception {

    validateSyntax(entityId);
    type.ifPresent(this::validateSyntax);
    removeEntity(entityId);
    return new ResponseEntity(HttpStatus.NO_CONTENT);
}