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:com.arpnetworking.configuration.jackson.HoconFileSource.java

private HoconFileSource(final Builder builder) {
    super(builder);
    _file = builder._file;//w  w  w  . jav  a  2  s.c  o  m

    JsonNode jsonNode = null;
    if (_file.canRead()) {
        try {
            final Config config = ConfigFactory.parseFile(_file);
            final String hoconAsJson = config.resolve().root().render(ConfigRenderOptions.concise());
            jsonNode = _objectMapper.readTree(hoconAsJson);
        } 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:com.temenos.useragent.generic.mediatype.JsonPayloadHandler.java

@Override
public void setPayload(String payload) {
    if (payload == null) {
        throw new IllegalArgumentException("Payload is null");
    }//from  ww  w  .j a  v  a 2 s.co  m
    if (payload.isEmpty()) {
        return;
    }
    jsonResponse = Optional.ofNullable((Object) new JSONTokener(payload).nextValue());
}

From source file:com.github.ljtfreitas.restify.http.spring.contract.metadata.reflection.SpringWebRequestMappingMetadata.java

private Optional<String> produces() {
    return Optional.ofNullable(mapping).map(m -> m.produces()).filter(c -> c.length >= 1)
            .map(h -> Arrays.stream(h).filter(c -> c != null && !c.isEmpty()).collect(Collectors.joining(", ")))
            .map(c -> HttpHeaders.ACCEPT + "=" + c);
}

From source file:com.devicehive.auth.rest.HttpAuthenticationFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;

    Optional<String> authHeader = Optional.ofNullable(httpRequest.getHeader(HttpHeaders.AUTHORIZATION));

    String resourcePath = new UrlPathHelper().getPathWithinApplication(httpRequest);
    logger.debug("Security intercepted request to {}", resourcePath);

    try {//  w  w  w.  ja  v  a 2  s  .co m
        if (authHeader.isPresent()) {
            String header = authHeader.get();
            if (header.startsWith(Constants.BASIC_AUTH_SCHEME)) {
                processBasicAuth(header);
            } else if (header.startsWith(Constants.TOKEN_SCHEME)) {
                processJwtAuth(authHeader.get().substring(6).trim());
            }
        } else {
            processAnonymousAuth();
        }

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication instanceof AbstractAuthenticationToken) {
            MDC.put("usrinf", authentication.getName());
            HiveAuthentication.HiveAuthDetails details = createUserDetails(httpRequest);
            ((AbstractAuthenticationToken) authentication).setDetails(details);
        }

        chain.doFilter(request, response);
    } catch (InternalAuthenticationServiceException e) {
        SecurityContextHolder.clearContext();
        logger.error("Internal authentication service exception", e);
        httpResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    } catch (AuthenticationException e) {
        SecurityContextHolder.clearContext();
        httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, e.getMessage());
    } finally {
        MDC.remove("usrinf");
    }
}

From source file:org.camunda.bpm.spring.boot.starter.configuration.impl.custom.EnterLicenseKeyConfiguration.java

protected Optional<String> readLicenseKeyFromDatasource(Connection connection) throws SQLException {
    final ResultSet resultSet = connection.createStatement().executeQuery(getSql(SELECT_SQL));
    return resultSet.next() ? Optional.ofNullable(resultSet.getString(1)) : Optional.empty();
}

From source file:io.github.pellse.decorator.GeneratedDecorator.java

public GeneratedDecorator(Decorator<I, ? extends I> next, T delegateTarget, Class<I> commonDelegateType,
        DelegateGenerator<I> generator, ClassLoader classLoader) {
    super(next);/*from  w w w.  j av a 2s .c  o  m*/
    this.delegateTarget = delegateTarget;
    this.commonDelegateType = commonDelegateType;
    this.generator = Optional.ofNullable(generator).orElseGet(ByteBuddyClassDelegateGenerator<I>::new);
    this.classLoader = classLoader;
}

From source file:it.greenvulcano.gvesb.virtual.utils.MimeMessageHelper.java

public static Map<String, List<String>> getMessageRecipients(MimeMessage mimeMessage)
        throws MessagingException {

    Map<String, List<String>> recipients = new LinkedHashMap<>();

    Optional.ofNullable(mimeMessage.getRecipients(RecipientType.TO))
            .ifPresent(a -> recipients.put("TO", Stream.of(a).map(InternetAddress.class::cast)
                    .map(InternetAddress::getAddress).collect(Collectors.toList())));

    Optional.ofNullable(mimeMessage.getRecipients(RecipientType.CC))
            .ifPresent(a -> recipients.put("CC", Stream.of(a).map(InternetAddress.class::cast)
                    .map(InternetAddress::getAddress).collect(Collectors.toList())));

    Optional.ofNullable(mimeMessage.getRecipients(RecipientType.BCC))
            .ifPresent(a -> recipients.put("BCC", Stream.of(a).map(InternetAddress.class::cast)
                    .map(InternetAddress::getAddress).collect(Collectors.toList())));

    return recipients;

}

From source file:io.tourniquet.junit.http.rules.ResponseStubbing.java

/**
 * Sets the resource that should be requested via GET, as in <pre>
 *     GET /pathToResource HTTP/1.1//w w w. j  av a2  s . c  o m
 * </pre>
 * In case you mix resource paths with and without queries, that the paths without query should be defined after
 * paths with queries as these will also match requests with queries defined. For example:<br>
 * <pre>on(GET).resource(&quot;/path?query=example&quot;).respond(&quot;Answer1&quot;);
 * on(GET).resource(&quot;/path&quot;).respond(&quot;DefaultAnswer&quot;);
 * </pre>
 *
 * @param resource
 *         the path to the resource
 *
 * @return this stubbing
 */
public ResponseStubbing resource(final String resource) {

    this.path = Optional.ofNullable(resource);
    return this;
}

From source file:net.codestory.http.Request.java

default String header(String name, String defaultValue) {
    return Optional.ofNullable(header(name)).orElse(defaultValue);
}