Example usage for java.util Optional ofNullable

List of usage examples for java.util Optional ofNullable

Introduction

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

Prototype

@SuppressWarnings("unchecked")
public static <T> Optional<T> ofNullable(T value) 

Source Link

Document

Returns an Optional describing the given value, if non- null , otherwise returns an empty Optional .

Usage

From source file:eu.interedition.collatex.tools.CollationServer.java

public static void start(CommandLine commandLine) {
    final CollationServer collator = new CollationServer(
            Integer.parseInt(commandLine.getOptionValue("mpc", "2")),
            Integer.parseInt(commandLine.getOptionValue("mcs", "0")),
            Optional.ofNullable(commandLine.getOptionValue("dot")).orElse(detectDotPath()));
    final String staticPath = System.getProperty("collatex.static.path", "");
    final HttpHandler httpHandler = staticPath.isEmpty()
            ? new CLStaticHttpHandler(CollationPipe.class.getClassLoader(), "/static/") {
                @Override/*ww w  . ja  va 2s .  com*/
                protected void onMissingResource(Request request, Response response) throws Exception {
                    collator.service(request, response);
                }
            }
            : new StaticHttpHandler(staticPath.replaceAll("/+$", "") + "/") {
                @Override
                protected void onMissingResource(Request request, Response response) throws Exception {
                    collator.service(request, response);
                }
            };

    final NetworkListener httpListener = new NetworkListener("http", "0.0.0.0",
            Integer.parseInt(commandLine.getOptionValue("p", "7369")));

    final CompressionConfig compressionConfig = httpListener.getCompressionConfig();
    compressionConfig.setCompressionMode(CompressionConfig.CompressionMode.ON);
    compressionConfig.setCompressionMinSize(860); // http://webmasters.stackexchange.com/questions/31750/what-is-recommended-minimum-object-size-for-gzip-performance-benefits
    compressionConfig.setCompressableMimeTypes("application/javascript", "application/json", "application/xml",
            "text/css", "text/html", "text/javascript", "text/plain", "text/xml");

    final HttpServer httpServer = new HttpServer();
    final ServerConfiguration httpServerConfig = httpServer.getServerConfiguration();

    httpServer.addListener(httpListener);
    httpServerConfig.addHttpHandler(httpHandler,
            commandLine.getOptionValue("cp", "").replaceAll("/+$", "") + "/*");
    httpServerConfig.getMonitoringConfig().getWebServerConfig()
            .addProbes(new AccessLogProbe(new StandardOutAccessLogAppender(), ApacheLogFormat.COMBINED));

    Runtime.getRuntime().addShutdownHook(new Thread(() -> {
        LOG.info("Stopping HTTP server");
        httpServer.shutdown();
    }));

    try {
        httpServer.start();
        Thread.sleep(Long.MAX_VALUE);
    } catch (IOException | InterruptedException e) {
        LOG.log(Level.SEVERE, e, e::getMessage);
    }
}

From source file:org.ow2.proactive.connector.iaas.rest.InfrastructureRest.java

@DELETE
@Path("/{infrastructureId}")
@Produces(MediaType.APPLICATION_JSON)//  ww  w  .j  a v a 2  s  .  c  o  m
public Response deleteInfrastructureById(@PathParam("infrastructureId") String infrastructureId,
        @QueryParam("deleteInstances") Boolean deleteInstances) {
    Optional.ofNullable(infrastructureService.getInfrastructure(infrastructureId)).ifPresent(infrastructure -> {
        if (Optional.ofNullable(deleteInstances).orElse(false)) {
            infrastructureService.deleteInfrastructureWithCreatedInstances(infrastructure);
        } else {
            infrastructureService.deleteInfrastructure(infrastructure);
        }
    });
    return Response.ok(infrastructureService.getAllSupportedInfrastructure()).build();
}

From source file:io.devcon5.pageobjects.tx.TransactionHelper.java

/**
 * Determines the transaction name of the method. The method must be annotated with {@link Transaction} otherwise
 * the empty optional is returned. The name is derived from the value of the {@link Transaction} annotation or from
 * the mehtod name. If the declaring class denotes a transaction itself, it's name prefixes the method transaction.
 *
 * @param method/*from w  ww.  j a  va2s .  c  o  m*/
 *         the method for which the transaction name should be determined
 *
 * @return the name of the transaction or the empty optional if the method denotes no transaction
 */
public static Optional<String> getTxName(Object object, final Method method) {

    return Optional.ofNullable(method.getAnnotation(Transaction.class))
            .map(t -> getClassTxName(object.getClass()).map(ctx -> ctx + '_').orElse("")
                    + (isEmpty(t.value()) ? method.getName() : t.value()));
}

From source file:io.gravitee.repository.mongodb.management.MongoPageRepository.java

@Override
public Optional<Page> findById(String pageId) throws TechnicalException {
    logger.debug("Find page by ID [{}]", pageId);

    PageMongo page = internalPageRepo.findOne(pageId);
    Page res = mapper.map(page, Page.class);

    logger.debug("Find page by ID [{}] - Done", pageId);
    return Optional.ofNullable(res);
}

From source file:net.hamnaberg.json.Property.java

public List<Value> getArray() {
    return Optional.ofNullable(delegate.get("array"))
            .map(array -> array.isArray()
                    ? unmodifiableList(stream(array.spliterator(), false).map(ValueFactory::createValue)
                            .collect(Collectors.toList()))
                    : Collections.<Value>emptyList())
            .orElse(Collections.<Value>emptyList());
}

From source file:com.flipkart.flux.guice.module.AkkaModule.java

/**
 * Returns map of all the available routers and actors per router,
 * currently a router is created per Task of deployment unit //todo: handle dynamic deployments
 *///  w w  w  . j a  v a  2s .  co  m
@Provides
@Singleton
@Named("routerConfigMap")
public Map<String, Integer> getRouterConfigs(
        @Named("deploymentUnits") Map<String, DeploymentUnit> deploymentUnitsMap,
        @Named("routers.default.instancesPerNode") int defaultNoOfActors) {
    Map<String, Integer> routerConfigMap = new ConcurrentHashMap<>();

    //add all deployment units' routers
    for (Map.Entry<String, DeploymentUnit> deploymentUnitEntry : deploymentUnitsMap.entrySet()) {
        DeploymentUnit deploymentUnit = deploymentUnitEntry.getValue();
        Set<Method> taskMethods = deploymentUnit.getTaskMethods();
        Configuration taskConfiguration = deploymentUnit.getTaskConfiguration();

        for (Method taskMethod : taskMethods) {
            String routerName = new MethodId(taskMethod).getPrefix();
            Integer taskExecConcurrency = Optional
                    .ofNullable((Integer) taskConfiguration.getProperty(routerName + ".executionConcurrency"))
                    .orElse(defaultNoOfActors);
            routerConfigMap.put(routerName, taskExecConcurrency);
        }
    }
    return routerConfigMap;
}

From source file:com.github.jrh3k5.habitat4j.rest.CachingAccessTokenProvider.java

/**
 * Gets the current, if any, cached access token.
 * //from  w  ww  .j  av  a  2s  . c om
 * @return An {@link Optional} containing the access token that may be cached; this will be empty if no access token is currently cached.
 */
private Optional<AccessToken> getCurrentAccessToken() {
    final Lock readLock = storeLock.readLock();
    readLock.lock();
    try {
        return Optional.ofNullable(accessTokenStore.getValue());
    } finally {
        readLock.unlock();
    }
}

From source file:io.gravitee.gateway.env.GatewayConfiguration.java

private void initTenant() {
    String systemPropertyTenant = System.getProperty(MULTI_TENANT_SYSTEM_PROPERTY);
    if (systemPropertyTenant == null || systemPropertyTenant.isEmpty()) {
        systemPropertyTenant = null;//  w ww  . j a  va2  s.co m
    }

    String envPropertyTenant = environment.getProperty(MULTI_TENANT_CONFIGURATION);
    if (envPropertyTenant == null || envPropertyTenant.isEmpty()) {
        envPropertyTenant = null;
    }

    tenant = Optional.ofNullable(systemPropertyTenant == null ? envPropertyTenant : systemPropertyTenant);
}

From source file:com.github.yongchristophertang.engine.web.http.MultipartBodyFormBuilder.java

/**
 * Add an attaching file in body of {@link HttpRequestBuilders}
 *
 * @param name     attached file name//from   ww w  . j a va 2 s  .c  o m
 * @param filePath local file path
 * @return {@link MultipartBodyFormBuilder}
 */
public MultipartBodyFormBuilder file(String name, String filePath) {
    AssertUtils.notNull(name, "File name must not be null.");
    Optional.ofNullable(filePath).ifPresent(f -> builder.addBinaryBody(name, new File(f)));
    return this;
}

From source file:de.is24.aws.instancemetadataserver.RemoteHostRoleNameProducer.java

private Optional<String> getHostPart(String rawFqdn) {
    Matcher matcher = Pattern.compile("^([a-zA-Z0-9]+)(\\.d)?\\.rz\\.is$").matcher(rawFqdn);

    if (!matcher.find()) {
        return Optional.empty();
    }//from w w w  .j  av a2 s.com

    return Optional.ofNullable(matcher.group(1));
}