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:org.mylab.artifactoryclient.ArtifactoryClient.java

public Optional<ArtifactJSONResults> listAllParserArtifacts() {
    String jsonResponse = invokePost("/api/search/aql", "items.find({\"repo\":{\"$eq\":\"parsers\"}})");

    ObjectMapper mapper = new ObjectMapper();
    ArtifactJSONResults results = null;/* w ww . j a va2 s  .  c o  m*/
    try {
        results = mapper.readValue(jsonResponse, ArtifactJSONResults.class);
    } catch (IOException ex) {
        java.util.logging.Logger.getLogger(ArtifactoryClient.class.getName()).log(Level.SEVERE, null, ex);
    }
    return Optional.ofNullable(results);
}

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

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

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

public Map<String, Value> getObject() {
    return unmodifiableMap(Optional.ofNullable(delegate.get("object")).filter(JsonNode::isObject)
            .map(object -> stream(spliteratorUnknownSize(object.fields(), Spliterator.ORDERED), false).collect(
                    Collectors.toMap(Map.Entry::getKey, entry -> ValueFactory.createValue(entry.getValue()))))
            .orElse(Collections.<String, Value>emptyMap()));
}

From source file:org.n52.iceland.coding.encode.ResponseWriterRepository.java

@SuppressWarnings("unchecked")
public <T> ResponseWriter<T> getWriter(Class<? extends T> clazz) {
    ResponseWriterKey key = new ResponseWriterKey(clazz);
    if (!writersByClass.containsKey(key)) {
        Set<Class<?>> compatible = Sets.newHashSet();
        for (ResponseWriterKey c : writersByClass.keySet()) {
            if (ClassHelper.getSimiliarity(c.getType(), clazz) >= 0) {
                compatible.add(c.getType());
            }/*ww w.j av  a 2 s .com*/
        }
        writersByClass.put(key, writersByClass.get(chooseWriter(compatible, clazz)));
    }
    Producer<ResponseWriter<?>> producer = writersByClass.get(key);
    return (ResponseWriter<T>) Optional.ofNullable(producer).map(Producer::get).orElse(null);
}

From source file:org.dhatim.dropwizard.jwt.cookie.authentication.DefaultJwtCookiePrincipal.java

/**
 * Get a collection of all the roles this principal is in
 *
 * @return the roles/* w  w  w .  j  a va  2  s .  c  o  m*/
 */
public Collection<String> getRoles() {
    return Optional.ofNullable(claims.get(ROLES)).map(Collection.class::cast).orElse(Collections.emptyList());
}

From source file:com.largecode.interview.rustem.service.UsersServiceImpl.java

@Override
public void deleteUser(Long id) {
    LOGGER.debug("Delete user by id ={}", id);
    Optional<User> userInDb = Optional.ofNullable(userRepository.findOne(id));
    userInDb.ifPresent((user) -> {// w ww  .j  a v  a  2  s.co  m
        userRepository.delete(user);
    });
    userInDb.orElseThrow(
            () -> new NoSuchElementException(String.format("User=%s not found for deleting.", id)));

}

From source file:com.ikanow.aleph2.analytics.services.PassthroughService.java

@Override
public void onStageInitialize(IEnrichmentModuleContext context, DataBucketBean bucket,
        EnrichmentControlMetadataBean control, final Tuple2<ProcessingStage, ProcessingStage> previous_next,
        final Optional<List<String>> next_grouping_fields) {
    logger.debug("BatchEnrichmentModule.onStageInitialize:" + context + ", DataBucketBean:" + bucket
            + ", prev_next:" + previous_next);
    this._context = context;
    this._bucket = bucket;
    this._previous_next = previous_next;

    _output = Optional.ofNullable(control.config()).map(cfg -> cfg.get(OUTPUT_TO_FIELDNAME))
            .map(s -> s.toString()).filter(s -> !s.isEmpty()).orElse(OUTPUT_TO_INTERNAL);
}

From source file:io.knotx.mocks.adapter.MockAdapterHandler.java

protected String getContentType(ClientRequest request) {
    return Optional.ofNullable(MimeMapping.getMimeTypeForFilename(request.getPath())).orElse(DEFAULT_MIME);
}

From source file:io.fabric8.spring.cloud.discovery.KubernetesDiscoveryClient.java

@Override
public List<ServiceInstance> getInstances(String serviceId) {
    Assert.notNull(serviceId, "[Assertion failed] - the object argument must be null");
    return Optional.ofNullable(client.endpoints().withName(serviceId).get()).orElse(new Endpoints())
            .getSubsets().stream()//  www.j a  v a  2  s . co  m
            .flatMap(s -> s.getAddresses().stream()
                    .map(a -> (ServiceInstance) new KubernetesServiceInstance(serviceId, a,
                            s.getPorts().stream().findFirst().orElseThrow(IllegalStateException::new), false)))
            .collect(Collectors.toList());

}

From source file:gov.ca.cwds.cals.util.PlacementHomeUtil.java

private static StringBuilder composeSecondPartOfFacilityName(Optional<ApplicantDTO> firstApplicant,
        ApplicantDTO secondApplicant) {//w w w.jav  a  2  s  .  com
    StringBuilder sbForSecondApplicant = new StringBuilder();
    Optional<String> secondLastName = Optional.ofNullable(secondApplicant.getLastName());
    Optional<String> secondFirstName = Optional.ofNullable(secondApplicant.getFirstName());
    if (firstApplicant.isPresent() && secondLastName.isPresent()
            && !secondLastName.get().equals(firstApplicant.get().getLastName())) {
        sbForSecondApplicant.append(secondLastName.get());
        if (secondFirstName.isPresent()) {
            sbForSecondApplicant.append(", ");
        }
    }
    secondFirstName.ifPresent(sbForSecondApplicant::append);
    return sbForSecondApplicant;
}