Example usage for java.util Optional orElseGet

List of usage examples for java.util Optional orElseGet

Introduction

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

Prototype

public T orElseGet(Supplier<? extends T> supplier) 

Source Link

Document

If a value is present, returns the value, otherwise returns the result produced by the supplying function.

Usage

From source file:com.spotify.heroic.suggest.elasticsearch.ElasticsearchSuggestModule.java

@JsonCreator
public ElasticsearchSuggestModule(@JsonProperty("id") Optional<String> id,
        @JsonProperty("groups") Optional<Groups> groups,
        @JsonProperty("connection") Optional<ConnectionModule> connection,
        @JsonProperty("writesPerSecond") Optional<Double> writesPerSecond,
        @JsonProperty("rateLimitSlowStartSeconds") Optional<Long> rateLimitSlowStartSeconds,
        @JsonProperty("writeCacheDurationMinutes") Optional<Long> writeCacheDurationMinutes,
        @JsonProperty("templateName") Optional<String> templateName,
        @JsonProperty("backendType") Optional<String> backendType,
        @JsonProperty("configure") Optional<Boolean> configure) {
    this.id = id;
    this.groups = groups.orElseGet(Groups::empty).or(DEFAULT_GROUP);
    this.connection = connection.orElseGet(ConnectionModule::buildDefault);
    this.writesPerSecond = writesPerSecond.orElse(DEFAULT_WRITES_PER_SECOND);
    this.rateLimitSlowStartSeconds = rateLimitSlowStartSeconds.orElse(DEFAULT_RATE_LIMIT_SLOW_START_SECONDS);
    this.writeCacheDurationMinutes = writeCacheDurationMinutes.orElse(DEFAULT_WRITES_CACHE_DURATION_MINUTES);
    this.templateName = templateName.orElse(DEFAULT_TEMPLATE_NAME);
    this.backendType = backendType.orElse(DEFAULT_BACKEND_TYPE);
    this.type = backendType.map(this::lookupBackendType).orElse(defaultSetup);
    this.configure = configure.orElse(DEFAULT_CONFIGURE);
}

From source file:com.ikanow.aleph2.analytics.storm.services.MockAnalyticsContext.java

@Override
public List<String> getInputTopics(final Optional<DataBucketBean> bucket, final AnalyticThreadJobBean job,
        final AnalyticThreadJobInputBean job_input) {
    // (Note this is just the bare bones required for Storm streaming enrichment testing, nothing more functional than that)
    final DataBucketBean my_bucket = bucket.orElseGet(() -> _mutable_state.bucket.get());

    final String topic = _distributed_services.generateTopicName(my_bucket.full_name(), Optional.empty());
    _distributed_services.createTopic(topic, Optional.empty());

    _logger.info("Created input topic for passthrough topology: " + topic);

    return Arrays.asList(topic);
}

From source file:com.intuit.wasabi.repository.cassandra.impl.CassandraAssignmentsRepository.java

@Override
public void updateBucketAssignmentCount(Experiment experiment, Assignment assignment, boolean countUp) {
    Optional<Bucket.Label> labelOptional = Optional.ofNullable(assignment.getBucketLabel());
    try {//from w  ww.  ja v  a 2s  .  com
        if (countUp) {
            bucketAssignmentCountAccessor.incrementCountBy(experiment.getID().getRawID(),
                    labelOptional.orElseGet(() -> NULL_LABEL).toString());
        } else {
            bucketAssignmentCountAccessor.decrementCountBy(experiment.getID().getRawID(),
                    labelOptional.orElseGet(() -> NULL_LABEL).toString());
        }
    } catch (WriteTimeoutException | UnavailableException | NoHostAvailableException e) {
        throw new RepositoryException("Could not update the bucket count for experiment " + experiment.getID()
                + " bucket " + labelOptional.orElseGet(() -> NULL_LABEL).toString(), e);
    }
}

From source file:com.intuit.wasabi.repository.cassandra.impl.CassandraAssignmentsRepository.java

List<Date> getDateHourRangeList(Experiment.ID experimentID, Parameters parameters) {
    final Experiment id = experimentRepository.getExperiment(experimentID);
    if (isNull(id)) {
        throw new ExperimentNotFoundException(experimentID);
    }/*from   w  ww .  j a  va 2s.  c o m*/
    final Optional<Date> from_ts = Optional.ofNullable(parameters.getFromTime());
    final Optional<Date> to_ts = Optional.ofNullable(parameters.getToTime());

    // Fetches the relevant partitions for a given time window where the user assignments data resides.
    return getUserAssignmentPartitions(from_ts.orElseGet(id::getCreationTime), to_ts.orElseGet(Date::new));
}

From source file:com.spotify.heroic.metadata.elasticsearch.ElasticsearchMetadataModule.java

@JsonCreator
public ElasticsearchMetadataModule(@JsonProperty("id") Optional<String> id,
        @JsonProperty("groups") Optional<Groups> groups,
        @JsonProperty("connection") Optional<ConnectionModule> connection,
        @JsonProperty("writesPerSecond") Optional<Double> writesPerSecond,
        @JsonProperty("rateLimitSlowStartSeconds") Optional<Long> rateLimitSlowStartSeconds,
        @JsonProperty("writeCacheDurationMinutes") Optional<Long> writeCacheDurationMinutes,
        @JsonProperty("deleteParallelism") Optional<Integer> deleteParallelism,
        @JsonProperty("templateName") Optional<String> templateName,
        @JsonProperty("backendType") Optional<String> backendType,
        @JsonProperty("configure") Optional<Boolean> configure) {
    this.id = id;
    this.groups = groups.orElseGet(Groups::empty).or(DEFAULT_GROUP);
    this.connection = connection.orElseGet(ConnectionModule::buildDefault);
    this.writesPerSecond = writesPerSecond.orElse(DEFAULT_WRITES_PER_SECOND);
    this.rateLimitSlowStartSeconds = rateLimitSlowStartSeconds.orElse(DEFAULT_RATE_LIMIT_SLOW_START_SECONDS);
    this.writeCacheDurationMinutes = writeCacheDurationMinutes.orElse(DEFAULT_WRITE_CACHE_DURATION_MINUTES);
    this.deleteParallelism = deleteParallelism.orElse(DEFAULT_DELETE_PARALLELISM);
    this.templateName = templateName.orElse(DEFAULT_TEMPLATE_NAME);
    this.backendTypeBuilder = backendType.flatMap(bt -> ofNullable(backendTypes.get(bt))).orElse(defaultSetup);
    this.configure = configure.orElse(false);
}

From source file:org.ops4j.pax.web.resources.jsf.OsgiResourceHandler.java

@Override
public Resource createResource(final String resourceName, String libraryName, String contentType) {
    // first, use default ResourceHandler for lookup
    Resource standardResource = super.createResource(resourceName, libraryName, contentType);
    if (standardResource != null) {
        return standardResource;
    }//from  w  ww . j av  a 2  s.co  m

    String workResourceName = resourceName;

    // nothing found, continue with OsgiResourceHandler
    final FacesContext facesContext = FacesContext.getCurrentInstance();
    if (workResourceName.charAt(0) == PATH_SEPARATOR) {
        // If resourceName starts with '/', remove that character because it
        // does not have any meaning (with and without should point to the
        // same resource).
        workResourceName = workResourceName.substring(1);
    }
    if (!ResourceValidationUtils.isValidResourceName(workResourceName)) {
        logger.debug("Invalid resourceName '{}'", workResourceName);
        return null;
    }
    if (libraryName != null && !ResourceValidationUtils.isValidLibraryName(libraryName)) {
        logger.debug("Invalid libraryName '{}'", libraryName);
        return null;
    }

    final Optional<String> localePrefix = ResourceHandlerUtils.getLocalePrefixForLocateResource(facesContext);
    // Contract currently not supported: final List<String> contracts = facesContext.getResourceLibraryContracts();

    final JsfResourceQuery query = new JsfResourceQuery(localePrefix.orElse(null), libraryName,
            workResourceName, contentType);
    final Optional<JsfResourceQueryResult> matchedQueryResult = getServiceAndExecute(
            service -> matchResources(service, query));
    if (matchedQueryResult.isPresent()) {
        JsfResourceQueryResult queryResult = matchedQueryResult.get();
        return new OsgiResource(queryResult.getResourceInformation().getUrl(),
                queryResult.isMatchedLocalePrefix() ? localePrefix.orElseGet(null) : null, workResourceName,
                queryResult.getResourceVersion(), libraryName, queryResult.getLibraryVersion(),
                queryResult.getResourceInformation().getLastModified());
    } else {
        return null;
    }

    // inspect final resource for contentType
    // FIXME deal with content-type
    //      if (contentType == null)
    //      {
    //         try(InputStream is = resourceInfo.getUrl().openConnection().getInputStream()){
    //            contentType = URLConnection.guessContentTypeFromStream(is);
    //         }catch(IOException e){
    //            logger.error("Could not determine contentType from url-resource!", e);
    //         }
    //      }

}

From source file:ddf.catalog.impl.operations.OperationsCrudSupport.java

void commitAndCleanup(StorageRequest storageRequest, Optional<String> historianTransactionKey,
        HashMap<String, Path> tmpContentPaths) {
    if (storageRequest != null) {
        try {//from   www  . jav a 2s .  c o  m
            sourceOperations.getStorage().commit(storageRequest);
            historianTransactionKey.ifPresent(historian::commit);
        } catch (StorageException e) {
            LOGGER.error("Unable to commit content changes for id: {}", storageRequest.getId(), e);
            try {
                sourceOperations.getStorage().rollback(storageRequest);
            } catch (StorageException e1) {
                LOGGER.error("Unable to remove temporary content for id: {}", storageRequest.getId(), e1);
            } finally {
                try {
                    historianTransactionKey.ifPresent(historian::rollback);
                } catch (RuntimeException re) {
                    LOGGER.error("Unable to commit versioned items for historian transaction: {}",
                            historianTransactionKey.orElseGet(String::new), re);
                }
            }
        }
    }

    tmpContentPaths.values().forEach(path -> FileUtils.deleteQuietly(path.toFile()));
    tmpContentPaths.clear();

}

From source file:fr.brouillard.oss.jgitver.JGitverModelProcessor.java

private Model provisionModel(Model model, Map<String, ?> options) throws IOException {
    try {//from   ww  w .ja v a2s  .  c  om
        calculateVersionIfNecessary();
    } catch (Exception ex) {
        throw new IOException("cannot build a Model object using jgitver", ex);
    }

    Source source = (Source) options.get(ModelProcessor.SOURCE);
    //logger.debug( "JGitverModelProcessor.provisionModel source="+source );
    if (source == null) {
        return model;
    }

    File location = new File(source.getLocation());
    //logger.debug( "JGitverModelProcessor.provisionModel location="+location );
    if (!location.isFile()) {
        // their JavaDoc says Source.getLocation "could be a local file path, a URI or just an empty string."
        // if it doesn't resolve to a file then calling .getParentFile will throw an exception,
        // but if it doesn't resolve to a file then it isn't under getMultiModuleProjectDirectory,
        return model; // therefore the model shouldn't be modified.
    }

    File relativePath = location.getParentFile().getCanonicalFile();

    if (StringUtils.containsIgnoreCase(relativePath.getCanonicalPath(),
            workingConfiguration.getMultiModuleProjectDirectory().getCanonicalPath())) {

        workingConfiguration.getNewProjectVersions().put(GAV.from(model.clone()),
                workingConfiguration.getCalculatedVersion());

        if (Objects.nonNull(model.getVersion())) {
            // TODO evaluate how to set the version only when it was originally set in the pom file
            model.setVersion(workingConfiguration.getCalculatedVersion());
        }

        if (Objects.nonNull(model.getParent())) {
            // if the parent is part of the multi module project, let's update the parent version 
            File relativePathParent = new File(
                    relativePath.getCanonicalPath() + File.separator + model.getParent().getRelativePath())
                            .getParentFile().getCanonicalFile();
            if (StringUtils.containsIgnoreCase(relativePathParent.getCanonicalPath(),
                    workingConfiguration.getMultiModuleProjectDirectory().getCanonicalPath())) {
                model.getParent().setVersion(workingConfiguration.getCalculatedVersion());
            }
        }

        // we should only register the plugin once, on the main project
        if (relativePath.getCanonicalPath()
                .equals(workingConfiguration.getMultiModuleProjectDirectory().getCanonicalPath())) {
            if (Objects.isNull(model.getBuild())) {
                model.setBuild(new Build());
            }

            if (Objects.isNull(model.getBuild().getPlugins())) {
                model.getBuild().setPlugins(new ArrayList<>());
            }

            Optional<Plugin> pluginOptional = model.getBuild().getPlugins().stream()
                    .filter(x -> JGitverUtils.EXTENSION_GROUP_ID.equalsIgnoreCase(x.getGroupId())
                            && JGitverUtils.EXTENSION_ARTIFACT_ID.equalsIgnoreCase(x.getArtifactId()))
                    .findFirst();

            StringBuilder pluginVersion = new StringBuilder();

            try (InputStream inputStream = getClass()
                    .getResourceAsStream("/META-INF/maven/" + JGitverUtils.EXTENSION_GROUP_ID + "/"
                            + JGitverUtils.EXTENSION_ARTIFACT_ID + "/pom" + ".properties")) {
                Properties properties = new Properties();
                properties.load(inputStream);
                pluginVersion.append(properties.getProperty("version"));
            } catch (IOException ignored) {
                // TODO we should not ignore in case we have to reuse it
                logger.warn(ignored.getMessage(), ignored);
            }

            Plugin plugin = pluginOptional.orElseGet(() -> {
                Plugin plugin2 = new Plugin();
                plugin2.setGroupId(JGitverUtils.EXTENSION_GROUP_ID);
                plugin2.setArtifactId(JGitverUtils.EXTENSION_ARTIFACT_ID);
                plugin2.setVersion(pluginVersion.toString());

                model.getBuild().getPlugins().add(plugin2);
                return plugin2;
            });

            if (Objects.isNull(plugin.getExecutions())) {
                plugin.setExecutions(new ArrayList<>());
            }

            Optional<PluginExecution> pluginExecutionOptional = plugin.getExecutions().stream()
                    .filter(x -> "verify".equalsIgnoreCase(x.getPhase())).findFirst();

            PluginExecution pluginExecution = pluginExecutionOptional.orElseGet(() -> {
                PluginExecution pluginExecution2 = new PluginExecution();
                pluginExecution2.setPhase("verify");

                plugin.getExecutions().add(pluginExecution2);
                return pluginExecution2;
            });

            if (Objects.isNull(pluginExecution.getGoals())) {
                pluginExecution.setGoals(new ArrayList<>());
            }

            if (!pluginExecution.getGoals().contains(JGitverAttachModifiedPomsMojo.GOAL_ATTACH_MODIFIED_POMS)) {
                pluginExecution.getGoals().add(JGitverAttachModifiedPomsMojo.GOAL_ATTACH_MODIFIED_POMS);
            }

            if (Objects.isNull(plugin.getDependencies())) {
                plugin.setDependencies(new ArrayList<>());
            }

            Optional<Dependency> dependencyOptional = plugin.getDependencies().stream()
                    .filter(x -> JGitverUtils.EXTENSION_GROUP_ID.equalsIgnoreCase(x.getGroupId())
                            && JGitverUtils.EXTENSION_ARTIFACT_ID.equalsIgnoreCase(x.getArtifactId()))
                    .findFirst();

            dependencyOptional.orElseGet(() -> {
                Dependency dependency = new Dependency();
                dependency.setGroupId(JGitverUtils.EXTENSION_GROUP_ID);
                dependency.setArtifactId(JGitverUtils.EXTENSION_ARTIFACT_ID);
                dependency.setVersion(pluginVersion.toString());

                plugin.getDependencies().add(dependency);
                return dependency;
            });
        }

        try {
            legacySupport.getSession().getUserProperties().put(
                    JGitverModelProcessorWorkingConfiguration.class.getName(),
                    JGitverModelProcessorWorkingConfiguration.serializeTo(workingConfiguration));
        } catch (JAXBException ex) {
            throw new IOException("unexpected Model serialization issue", ex);
        }
    }

    return model;
}

From source file:org.hawkular.inventory.impl.tinkerpop.provider.TitanProvider.java

@Override
public RuntimeException translateException(RuntimeException inputException, CanonicalPath affectedPath) {
    List<ExceptionMapper> exceptionMappers = exceptionMapping.get(inputException.getClass());
    if (exceptionMappers != null) {
        Optional<RuntimeException> firstMatch = exceptionMappers.stream()
                .filter(mapper -> mapper.getPredicate().test(inputException)).findFirst().map(mapper -> {
                    try {
                        // todo: find the proper ctor based on parameter match
                        //                                    Arrays.stream(mapper.getTargetException().getConstructors()).forEach(
                        //                                            constructor ->  {
                        //
                        //                                                Class<?>[] params = constructor.getParameterTypes();
                        //                                            }
                        //                                    );
                        return mapper.getTargetException().getConstructor(String.class)
                                .newInstance(inputException.getMessage());
                    } catch (Exception e) {
                        return inputException;
                    }/*from   w w w  .j a va  2s.c  o  m*/
                });
        if (firstMatch.isPresent()) {
            return firstMatch.orElseGet(() -> inputException);
        }
    }
    return inputException;
}

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

/**
 * Updates a BaseEntity in the database/* w ww .ja v  a 2 s. c  o 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);
}