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.netflix.spinnaker.clouddriver.artifacts.config.TokenAuth.java

default Optional<String> getTokenAsString() {
    String token = null;//from  w  w w.jav  a 2  s.co m
    if (StringUtils.isNotEmpty(getTokenFile())) {
        token = CredentialReader.credentialsFromFile(getTokenFile());
    } else if (StringUtils.isNotEmpty(getToken())) {
        token = getToken();
    }

    return Optional.ofNullable(token);
}

From source file:my.school.spring.rest.controllers.UseSchedulesCondition.java

@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {

    final Map<String, Object> annotationAttributes = Optional
            .ofNullable(metadata.getAnnotationAttributes(UseSchedules.class.getName())).orElse(new HashMap<>());
    Boolean isScheduledInstance = (Boolean) annotationAttributes.getOrDefault("value", false);

    Boolean allowScheduled = Optional
            .ofNullable(context.getEnvironment().getProperty("setup.versionProvider.scheduled", Boolean.class))
            .orElse(false);//from   ww w . j ava 2  s .  c  o  m
    final boolean scheduled = Objects.equals(allowScheduled, isScheduledInstance);
    LOG.info("Application will reuse {} implementation of the VersionProvider",
            (scheduled) ? "SCHEDULED" : "NOT SCHEDULED");
    return scheduled;
}

From source file:fi.hsl.parkandride.front.RequestLoggingInterceptor.java

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {
    Optional.ofNullable((String) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE))
            .filter(s -> s.startsWith(UrlSchema.API)).ifPresent(urlPattern -> {
                final String source = request.getHeader(SOURCE_HEADER);
                logger.trace("Intercepted API call: <{}> for source <{}>", urlPattern, source);
                batchingRequestLogService.increment(new RequestLogKey(urlPattern, source, DateTime.now()));
            });//w  ww  . ja v  a 2  s  .c o m
    return super.preHandle(request, response, handler);
}

From source file:nl.knaw.huygens.alexandria.endpoint.annotation.AnnotationPrototype.java

public Optional<String> getLocator() {
    return Optional.ofNullable(locator);
}

From source file:org.zalando.stups.stupsback.admin.domain.ThumbsUpHandler.java

@HandleBeforeCreate
public void handleCreate(ThumbsUp likes) {

    final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

    if (authentication != null) {
        final Optional<Object> principal = Optional.ofNullable(authentication.getPrincipal());
        likes.setUsername(principal.orElse(new String("testuser")).toString());
    } else {/*from   w  ww  . java  2s  . c  om*/
        likes.setUsername("anonymous");
    }
}

From source file:org.vaadin.peholmst.samples.dddwebinar.domain.doctors.LicenseService.java

public Optional<License> selectBestLicense(Collection<Procedure> procedures, Collection<License> licenses) {
    Set<License> availableLicenses = licenses.stream().filter(
            l -> procedures.stream().allMatch(p -> p.getCategory().getLicenseTypes().containsKey(l.getType())))
            .collect(Collectors.toSet());
    if (availableLicenses.isEmpty()) {
        return Optional.empty();
    } else {/*from   w w  w .  j av a 2s.  c o  m*/
        License best = null;
        int bestRank = Integer.MAX_VALUE;
        for (License l : availableLicenses) {
            for (Procedure p : procedures) {
                int rank = p.getCategory().getLicenseTypes().get(l.getType());
                if (rank < bestRank) {
                    bestRank = rank;
                    best = l;
                }
            }
        }
        return Optional.ofNullable(best);
    }
}

From source file:com.speedment.examples.social.JSONUser.java

public static JSONUser parse(JSONObject user) {
    final JSONUser usr = new JSONUser();
    usr.id = Long.parseLong(user.get("id").toString());
    usr.mail = user.get("mail").toString();
    usr.firstname = mapToString(user, "firstName");
    usr.lastname = mapToString(user, "lastName");
    usr.avatar = Optional.ofNullable(user.get("avatar")).map(Object::toString).filter(s -> !s.isEmpty())
            .map(s -> fromBase64(s)).orElse(null);

    return usr;/*  w  ww  . jav a2s  .c o m*/
}

From source file:info.archinnov.achilles.internals.metamodel.index.IndexInfo.java

public IndexInfo(IndexType type, String name, String indexClassName, String indexOptions) {
    this.type = type;
    this.name = name;
    this.indexClassName = isNotBlank(indexClassName) ? Optional.ofNullable(indexClassName) : Optional.empty();
    this.indexOptions = isNotBlank(indexOptions) ? Optional.ofNullable(indexClassName) : Optional.empty();
}

From source file:it.greenvulcano.gvesb.datahandling.dbo.utils.ResultSetTransformer.java

public static JSONArray toJSONArray(ResultSet resultSet) throws SQLException {

    JSONArray queryResult = new JSONArray();

    int columns = resultSet.getMetaData().getColumnCount();
    List<String> names = new ArrayList<>(columns);
    for (int i = 1; i <= columns; i++) {
        names.add(resultSet.getMetaData().getColumnLabel(i));
    }/*from   w  w  w . j  ava  2s.  c  om*/

    while (resultSet.next()) {

        JSONObject obj = new JSONObject();
        for (String key : names) {

            Object jsonValue = parseValue(resultSet.getObject(key));

            if (key.contains(".")) {
                String[] hieararchy = key.split("\\.");

                JSONObject child = Optional.ofNullable(obj.optJSONObject(hieararchy[0]))
                        .orElse(new JSONObject());
                child.put(hieararchy[1], Optional.ofNullable(jsonValue).orElse(JSONObject.NULL));

                obj.put(hieararchy[0], child);
            } else {
                obj.put(key, Optional.ofNullable(jsonValue).orElse(JSONObject.NULL));
            }
        }

        queryResult.put(obj);
    }

    return queryResult;

}

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

@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    return Optional.ofNullable(accountMapper.getAccountByUsername(username)).map(AccountUserDetails::new)
            .orElseThrow(() -> new UsernameNotFoundException(username));
}