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:no.asgari.civilization.server.model.Player.java

@JsonIgnore
public Optional<LocalDateTime> getIfEmailSent() {
    return Optional.ofNullable(emailSent);
}

From source file:fi.helsinki.opintoni.security.SecurityUtils.java

private Optional<Authentication> getAuthentication() {
    return Optional.ofNullable(SecurityContextHolder.getContext().getAuthentication());
}

From source file:com.arpnetworking.configuration.jackson.JsonNodeFileSource.java

private JsonNodeFileSource(final Builder builder) {
    super(builder);
    _file = builder._file;//from   w w  w .  j  a v a 2s .c  o  m

    JsonNode jsonNode = null;
    if (_file.canRead()) {
        try {
            jsonNode = _objectMapper.readTree(_file);
        } catch (final IOException e) {
            throw Throwables.propagate(e);
        }
    } else if (builder._file.exists()) {
        LOGGER.warn().setMessage("Cannot read file").addData("file", _file).log();
    } else {
        LOGGER.debug().setMessage("File does not exist").addData("file", _file).log();
    }
    _jsonNode = Optional.ofNullable(jsonNode);
}

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

@POST
@Path("{infrastructureId}/instances/scripts")
@Consumes(MediaType.APPLICATION_JSON)// www. j a v a 2 s . c o  m
@Produces(MediaType.APPLICATION_JSON)
public Response executeScript(@PathParam("infrastructureId") String infrastructureId,
        @QueryParam("instanceId") String instanceId, @QueryParam("instanceTag") String instanceTag,
        final String instanceScriptJson) {

    InstanceScript instanceScript = JacksonUtil.convertFromJson(instanceScriptJson, InstanceScript.class);

    final List<ScriptResult> scriptResults = Optional.ofNullable(instanceId)
            .map(i -> Lists.newArrayList(instanceScriptService.executeScriptOnInstance(infrastructureId,
                    instanceId, instanceScript)))
            .orElseGet(() -> Lists.newArrayList(instanceScriptService
                    .executeScriptOnInstanceTag(infrastructureId, instanceTag, instanceScript)));

    return Response.ok(scriptResults).build();
}

From source file:com.arpnetworking.configuration.jackson.BaseJacksonConfiguration.java

/**
 * {@inheritDoc}//from ww w.  ja  v a  2s. c o  m
 */
@Override
public <T> Optional<T> getPropertyAs(final String name, final Class<? extends T> clazz)
        throws IllegalArgumentException {
    final Optional<String> property = getProperty(name);
    if (!property.isPresent()) {
        return Optional.empty();
    }
    try {
        return Optional.ofNullable(_objectMapper.readValue(property.get(), clazz));
    } catch (final IOException e) {
        throw new IllegalArgumentException(
                String.format("Unable to construct object from configuration; name=%s, class=%s, property=%s",
                        name, clazz, property),
                e);
    }
}

From source file:com.github.ljtfreitas.restify.spring.configure.RestifyableType.java

public Optional<String> endpoint() {
    return Optional.ofNullable(restifyable.endpoint()).filter(endpoint -> !endpoint.isEmpty());
}

From source file:org.ambraproject.wombat.service.remote.AbstractRemoteService.java

protected AbstractRemoteService(HttpClientConnectionManager connectionManager) {
    this.connectionManager = Optional.ofNullable(connectionManager);
}

From source file:com.example.app.profile.model.terminology.FallbackProfileTermProvider.java

@Override
public TextSource client() {
    return isBlank(Optional.ofNullable(getProfileTermProvider()).map(ProfileTermProvider::client).orElse(null))
            ? _defaultProfileTermProvider.client()
            : getProfileTermProvider().client();
}

From source file:com.kazuki43zoo.jpetstore.service.OrderService.java

@Transactional
public Order getOrder(String username, int orderId) {
    Order order = Optional.ofNullable(orderMapper.getOrder(orderId))
            .filter(x -> x.getUsername().equals(username))
            .orElseThrow(() -> new ResourceNotFoundException("Order", orderId));
    order.setLines(orderMapper.getOrderLines(orderId));
    order.getLines().forEach(x -> {/*from   w w  w.  j  a  v a2s. c  om*/
        Item item = itemMapper.getItem(x.getItemId());
        item.setQuantity(itemMapper.getInventoryQuantity(x.getItemId()));
        x.setItem(item);
    });
    return order;
}

From source file:org.eclipse.hono.service.auth.device.X509AuthProvider.java

/**
 * Creates a {@link SubjectDnCredentials} instance from information provided by a
 * device in its client (X.509) certificate.
 * <p>/*  w  ww.ja  v a2  s .c  om*/
 * The JSON object passed in is required to contain a <em>subject-dn</em> property.
 * If the <em>singleTenant</em> service config property is {@code false}, then the
 * object is also required to contain a <em>tenant-id</em> property, otherwise
 * the default tenant is used.
 * 
 * @param authInfo The authentication information provided by the device.
 * @return The credentials or {@code null} if the authentication information
 *         does not contain a tenant ID and subject DN.
 * @throws NullPointerException if the authentication info is {@code null}.
 */
@Override
protected DeviceCredentials getCredentials(final JsonObject authInfo) {

    Objects.requireNonNull(authInfo);
    try {
        final String tenantId = Optional
                .ofNullable(authInfo.getString(CredentialsConstants.FIELD_PAYLOAD_TENANT_ID)).orElseGet(() -> {
                    if (config.isSingleTenant()) {
                        return Constants.DEFAULT_TENANT;
                    } else {
                        return null;
                    }
                });
        final String subjectDn = authInfo.getString(CredentialsConstants.FIELD_PAYLOAD_SUBJECT_DN);
        if (tenantId == null || subjectDn == null) {
            return null;
        } else {
            return SubjectDnCredentials.create(tenantId, subjectDn);
        }
    } catch (ClassCastException e) {
        return null;
    }
}