Example usage for java.util Optional of

List of usage examples for java.util Optional of

Introduction

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

Prototype

public static <T> Optional<T> of(T value) 

Source Link

Document

Returns an Optional describing the given non- null value.

Usage

From source file:com.orange.ngsi2.model.Notification.java

@JsonIgnore
public void setQuery(String key, String value) {
    if (this.query == null) {
        this.query = Optional.of(new HashMap<>());
    }/*from w  w  w .  j av  a2  s .  c  o m*/
    this.query.get().put(key, value);
}

From source file:net.pkhsolutions.pecsapp.control.PictureFileStorage.java

/**
 * TODO Document me/*from   ww w .  j a  v a  2  s . c o  m*/
 *
 * @param descriptor
 * @param layout
 * @return
 * @throws IOException
 */
@NotNull
public Optional<BufferedImage> load(@NotNull PictureDescriptor descriptor, @NotNull Optional<PageLayout> layout)
        throws IOException {
    final Path path = getDirectoryForLayout(layout)
            .resolve(String.format("%d.%s", descriptor.getId(), descriptor.getMimeType().getSubtype()));
    LOGGER.debug("Loading image from {}", path);
    if (!Files.exists(path)) {
        LOGGER.warn("File {} does not exist", path);
        return Optional.empty();
    }
    try (InputStream inputStream = Files.newInputStream(path)) {
        return Optional.of(ImageIO.read(inputStream));
    }
}

From source file:org.artifactory.ui.rest.service.admin.configuration.repositories.util.validator.ReplicationConfigValidator.java

/**
 * Validates the given local repo replication models and sets default values where needed and nulls are given
 *
 * @throws RepoConfigException/*  ww w . java 2 s  .  co m*/
 */
public void validateLocalModels(List<LocalReplicationConfigModel> replications) throws RepoConfigException {
    long enabledReplications = replications.stream().filter(LocalReplicationConfigModel::isEnabled).count();
    if (replications.size() > 0 && !addonsManager.isLicenseInstalled()) {
        throw new RepoConfigException("Replication is only available with a pro license and above",
                SC_FORBIDDEN);
    } else if (enabledReplications > 1 && !addonsManager.isHaLicensed()) {
        throw new RepoConfigException("Multi-push replication is only available with an Enterprise license.",
                SC_FORBIDDEN);
    }
    if (replications.size() > 1) {
        checkForDuplicateUrls(replications);
    }
    for (LocalReplicationConfigModel replication : replications) {
        if (!CronUtils.isValid(replication.getCronExp())) {
            throw new RepoConfigException("Invalid cron expression", SC_BAD_REQUEST);
        }
        replication.setEnabled(Optional.of(replication.isEnabled()).orElse(false));
        //Required field, but don't fail validation for it as default is in place
        replication.setSocketTimeout(Optional.of(replication.getSocketTimeout()).orElse(15000));
        replication.setSyncDeletes(Optional.of(replication.isSyncDeletes()).orElse(false));
        replication.setSyncProperties(Optional.of(replication.isSyncProperties()).orElse(false));
        replication
                .setEnableEventReplication(Optional.of(replication.isEnableEventReplication()).orElse(false));
        String proxyKey = replication.getProxy();
        if ((StringUtils.isNotBlank(proxyKey)) && (configService.getDescriptor().getProxy(proxyKey) == null)) {
            throw new RepoConfigException("Invalid proxy configuration name", SC_BAD_REQUEST);
        }
        if (StringUtils.isBlank(replication.getUrl())) {
            throw new RepoConfigException("Replication url is required", SC_BAD_REQUEST);
        }
        if (StringUtils.isBlank(replication.getUsername())) {
            throw new RepoConfigException("Replication username is required", SC_BAD_REQUEST);
        }
    }
}

From source file:org.trellisldp.rosid.file.CachedResource.java

/**
 * Read the cached resource from a directory
 * @param directory the directory/* ww w.j av  a2s.  c  om*/
 * @return the resource data, if present
 */
public static Optional<ResourceData> read(final File directory) {
    if (isNull(directory)) {
        return Optional.empty();
    }

    try {
        return Optional.of(MAPPER.readValue(new File(directory, RESOURCE_CACHE), ResourceData.class));
    } catch (final IOException ex) {
        LOGGER.warn("Error reading cached resource: {}", ex.getMessage());
    }
    return Optional.empty();
}

From source file:io.kamax.mxisd.backend.sql.SqlThreePidProvider.java

@Override
public Optional<SingleLookupReply> find(SingleLookupRequest request) {
    log.info("SQL lookup");
    String stmtSql = StringUtils.defaultIfBlank(cfg.getIdentity().getMedium().get(request.getType()),
            cfg.getIdentity().getQuery());
    log.info("SQL query: {}", stmtSql);
    try (Connection conn = pool.get()) {
        try (PreparedStatement stmt = conn.prepareStatement(stmtSql)) {
            stmt.setString(1, request.getType().toLowerCase());
            stmt.setString(2, request.getThreePid().toLowerCase());

            try (ResultSet rSet = stmt.executeQuery()) {
                while (rSet.next()) {
                    String uid = rSet.getString("uid");
                    log.info("Found match: {}", uid);
                    if (StringUtils.equals("uid", cfg.getIdentity().getType())) {
                        log.info("Resolving as localpart");
                        return Optional
                                .of(new SingleLookupReply(request, new MatrixID(uid, mxCfg.getDomain())));
                    }//w w  w.  jav  a  2s  .c o m
                    if (StringUtils.equals("mxid", cfg.getIdentity().getType())) {
                        log.info("Resolving as MXID");
                        return Optional.of(new SingleLookupReply(request, new MatrixID(uid)));
                    }

                    log.info("Identity type is unknown, skipping");
                }

                log.info("No match found in SQL");
                return Optional.empty();
            }
        }
    } catch (SQLException e) {
        throw new RuntimeException(e);
    }
}

From source file:co.runrightfast.core.utils.ConfigUtils.java

static Optional<Long> getLong(final Config config, final String path, final String... paths) {
    if (!hasPath(config, path, paths)) {
        return Optional.empty();
    }//from   ww  w .  j  av a2s .co m
    return Optional.of(config.getLong(configPath(path, paths)));
}

From source file:se.omegapoint.facepalm.infrastructure.JPAUserRepository.java

@Override
public Optional<se.omegapoint.facepalm.domain.User> findByNameAndPassword(final String username,
        final String password) {
    notNull(username);//from   w  w w  .  j  a  va  2  s  .c  om
    notNull(password);

    final String query = format("SELECT * FROM ACCOUNTS WHERE USERNAME = '%s' AND PASSWORD = '%s'", username,
            password);

    final List<User> users = entityManager.createNativeQuery(query, User.class).getResultList();

    eventService.publish(users.isEmpty()
            ? new GenericEvent(format("No matching user with username[%s], password[%s]", username, password))
            : new GenericEvent(
                    format("Found matching users with username[%s], password[%s]", username, password)));

    return users.isEmpty() ? Optional.empty() : Optional.of(convertUserToDomain(users.get(0)));
}

From source file:com.ikanow.aleph2.v1.document_db.utils.V1DocumentDbHadoopUtils.java

/** 
 * @param input_config - the input settings
 * @return//from   w ww.j a v  a  2 s  .c  o 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:ddf.catalog.validation.impl.validator.EnumerationValidator.java

/**
 * {@inheritDoc}//  w w w .j a  va 2s  .c o  m
 * <p>
 * Validates each of {@code attribute}'s values against the set of acceptable values by calling
 * {@link String#valueOf(Object)} on each value and checking whether that string is in the set.
 * <p>
 * Note: comparisons are <strong>case-sensitive</strong>.
 */
@Override
public Optional<AttributeValidationReport> validate(final Attribute attribute) {
    Preconditions.checkArgument(attribute != null, "The attribute cannot be null.");

    final String name = attribute.getName();
    for (final Serializable value : attribute.getValues()) {
        final String stringValue = String.valueOf(value);
        if (!values.contains(stringValue)) {
            final AttributeValidationReportImpl report = new AttributeValidationReportImpl();
            // TODO (jrnorth) - escape the value.
            report.addViolation(new ValidationViolationImpl(Collections.singleton(name),
                    name + " has an invalid value: [" + stringValue + "]", Severity.ERROR));
            values.forEach(report::addSuggestedValue);
            return Optional.of(report);
        }
    }

    return Optional.empty();
}

From source file:adb4j.executor.CmdExecutor.java

/**
 * Runs a general command and wait for it to exit.
 *
 * @param command The command you want to run
 * @return//from   w  w w.j  a va2  s  .c  o  m
 * @throws IOException
 * @see CmdResult
 * @see runAsync
 */
public CmdResult run(String command) throws IOException {
    CountDownLatch countDownLatch = new CountDownLatch(1);
    defaultHandler.countDownLatch = Optional.of(countDownLatch);

    runAsync(command, defaultHandler, false);

    try {
        countDownLatch.await();
    } catch (InterruptedException ex) {
    }
    return new CmdResult(exitValue, exception, defaultHandler.getOutputStream(),
            defaultHandler.getErrorStream());
}