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.ow2.proactive.connector.iaas.cloud.provider.jclouds.JCloudsComputeServiceBuilder.java

public ComputeService buildComputeServiceFromInfrastructure(Infrastructure infrastructure) {
    Iterable<Module> modules = ImmutableSet.of(new SshjSshClientModule());
    ContextBuilder contextBuilder = ContextBuilder.newBuilder(infrastructure.getType())

            .credentials(infrastructure.getCredentials().getUsername(),
                    infrastructure.getCredentials().getPassword())
            .modules(modules).overrides(getTimeoutPolicy());

    Optional.ofNullable(infrastructure.getEndpoint()).filter(endPoint -> !endPoint.isEmpty())
            .ifPresent(endPoint -> contextBuilder.endpoint(endPoint));

    return contextBuilder.buildView(ComputeServiceContext.class).getComputeService();
}

From source file:gov.ca.cwds.cals.service.FacilityInspectionService.java

@UnitOfWork(value = CMS)
protected String getFacilityLicenseNo(String facilityId) {
    return Optional.ofNullable(placementHomeService.find(facilityId)).map(PlacementHome::getLicenseNo)
            .orElse(null);// w w  w .java2  s  .co m
}

From source file:org.basinmc.maven.plugins.minecraft.access.TransformationType.java

/**
 * Retrieves the altered visibility for a field of a specific name (if any).
 *//*w  w w  .  j a  va2s  .co m*/
@Nonnull
public Optional<Visibility> getFieldVisibility(@Nonnull String fieldName) {
    return Optional.ofNullable(this.fields.get(fieldName));
}

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

@POST
@Consumes(MediaType.APPLICATION_JSON)// w  ww  . j a  va 2s . c om
@Produces("application/json")
@Path("{infrastructureId}/keypairs")
public Response createKeyPair(@PathParam("infrastructureId") String infrastructureId,
        final String instanceJson) {
    Instance instance = JacksonUtil.convertFromJson(instanceJson, Instance.class);
    SimpleImmutableEntry<String, String> privateKey = keyPairService.createKeyPair(infrastructureId, instance);
    return Optional.ofNullable(privateKey).map(privateKeyResponse -> Response.ok(privateKeyResponse).build())
            .orElse(Response.serverError().build());
}

From source file:ac.simons.tweetarchive.tweets.TweetStorageService.java

@Transactional
public TweetEntity store(final Status status, final String rawContent) {
    final Optional<TweetEntity> existingTweet = this.tweetRepository.findOne(status.getId());
    if (existingTweet.isPresent()) {
        final TweetEntity rv = existingTweet.get();
        log.warn("Tweet with status {} already existed...", rv.getId());
        return rv;
    }/*from  www.jav  a 2 s. c  o  m*/

    final TweetEntity tweet = new TweetEntity(status.getId(), status.getUser().getId(),
            status.getUser().getScreenName(), status.getCreatedAt().toInstant().atZone(ZoneId.of("UTC")),
            extractContent(status), extractSource(status), rawContent);
    tweet.setCountryCode(Optional.ofNullable(status.getPlace()).map(Place::getCountryCode).orElse(null));
    if (status.getInReplyToStatusId() != -1L && status.getInReplyToUserId() != -1L
            && status.getInReplyToScreenName() != null) {
        tweet.setInReplyTo(new InReplyTo(status.getInReplyToStatusId(), status.getInReplyToScreenName(),
                status.getInReplyToUserId()));
    }
    tweet.setLang(status.getLang());
    tweet.setLocation(Optional.ofNullable(status.getGeoLocation())
            .map(g -> new TweetEntity.Location(g.getLatitude(), g.getLongitude())).orElse(null));
    // TODO Handle quoted tweets
    return this.tweetRepository.save(tweet);
}

From source file:io.gravitee.repository.jdbc.JdbcUserRepository.java

public Optional<User> findByEmail(String email) throws TechnicalException {
    return Optional.ofNullable(userJpaConverter.convertTo(internalJpaUserRepository.findByEmail(email)));
}

From source file:io.curly.gathering.list.GatheringStorage.java

@HystrixCommand
public Observable<Optional<GatheringList>> findOne(String id, User principal) {
    return new ObservableResult<Optional<GatheringList>>() {
        @Override/*  w w  w . ja  v  a2  s  .c om*/
        public Optional<GatheringList> invoke() {
            return Optional.ofNullable(repository.findByOwnerAndId(principal.getId(), id));
        }
    };
}

From source file:pt.sapo.pai.vip.VipServlet.java

private void processRequest(HttpServletRequest request, HttpServletResponse response,
        Supplier<HttpRequestBase> supplier) throws ServletException, IOException {
    try (OutputStream out = response.getOutputStream(); CloseableHttpClient http = builder.build()) {
        Optional.ofNullable(servers[rand.nextInt(2)]).map(server -> server.split(":"))
                .map(parts -> Tuple.of(parts[0], Integer.valueOf(parts[1]))).ifPresent(server -> {
                    try {
                        HttpRequestBase method = supplier.get();
                        method.setURI(new URI(request.getScheme(), null, server._1, server._2,
                                request.getRequestURI(), request.getQueryString(), null));
                        HttpResponse rsp = http.execute(method);
                        Collections.list(request.getHeaderNames())
                                .forEach(name -> Collections.list(request.getHeaders(name))
                                        .forEach(value -> method.setHeader(name, value)));
                        response.setStatus(rsp.getStatusLine().getStatusCode());
                        response.setContentType(rsp.getFirstHeader(HttpHeaders.CONTENT_TYPE).getValue());
                        IOUtils.copy(rsp.getEntity().getContent(), out);
                    } catch (IOException | URISyntaxException ex) {
                        log.error(null, ex);
                    }//from w  w  w . j  ava 2s .co m
                });
    }
}

From source file:com.temenos.useragent.generic.mediatype.JsonEntityHandler.java

@Override
public String getValue(String fqPropertyName) {
    List<String> pathParts = Arrays.asList(flattenPropertyName(fqPropertyName));
    Optional<JSONObject> parent = navigateJsonObjectforPropertyPath(Optional.ofNullable(jsonObject),
            pathParts.subList(0, pathParts.size() - 1), fqPropertyName, false);
    String lastPathPart = pathParts.get(pathParts.size() - 1);
    if (parent.isPresent()) {
        if (isPropertyNameWithIndex(lastPathPart)) {
            JSONArray jsonArr = parent.get().optJSONArray(extractPropertyName(lastPathPart));
            if (jsonArr != null) {
                return jsonArr.opt(extractIndex(lastPathPart)) != null
                        ? String.valueOf(jsonArr.opt(extractIndex(lastPathPart)))
                        : null;//from   ww  w. j  a  va2s. c  o m
            }
        } else {
            return parent.get().opt(lastPathPart) != null ? String.valueOf(parent.get().opt(lastPathPart))
                    : null;
        }
    }
    return null;
}

From source file:org.ow2.proactive.connector.iaas.service.InstanceScriptService.java

public List<ScriptResult> executeScriptOnInstanceTag(String infrastructureId, String instanceTag,
        InstanceScript instanceScript) {

    return Optional.ofNullable(infrastructureService.getInfrastructure(infrastructureId))
            .map(infrastructure -> cloudManager.executeScriptOnInstanceTag(infrastructure, instanceTag,
                    instanceScript))//ww  w  .  j  a v a2  s .  com
            .orElseThrow(() -> new NotFoundException(
                    "infrastructure id  : " + infrastructureId + " does not exists"));

}