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:pzalejko.iot.hardware.home.core.service.sender.InternalMqttRemoteCallback.java

@Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
    LOG.debug(LogMessages.RECEIVED_MESSAGE, topic, message);

    final Optional<EventType> eventType = Optional.ofNullable(eventTopicMapper.getEventType(topic));
    eventType.ifPresent(t -> {/*from   w w  w  .j a  v  a2  s .  c o m*/
        final Serializable data = eventConverter.convertIn(t, message.getPayload());
        eventBus.postRemote(data, t);
    });
}

From source file:curly.artifact.ArtifactServiceImpl.java

@Loggable
@Override//from w  ww .  ja  v a  2 s.c o m
@HystrixCommand(fallbackMethod = "defaultFindAll")
public Observable<Optional<Page<Artifact>>> findAll(Pageable pageable) {
    log.trace("Finding for page {}", pageable.getPageNumber());
    return new ObservableResult<Optional<Page<Artifact>>>() {
        @Override
        public Optional<Page<Artifact>> invoke() {
            return Optional.ofNullable(repository.findAll(pageable));
        }
    };
}

From source file:org.ow2.proactive.connector.iaas.cache.InstanceCache.java

public void deleteInfrastructureInstance(Infrastructure infrastructure, Instance instance) {
    Map<String, Set<Instance>> tempInstances = cloneCreatedInstances();
    Optional.ofNullable(tempInstances.get(infrastructure.getId()))
            .ifPresent(instances -> instances.remove(instance));
    createdInstances = ImmutableMap.copyOf(tempInstances);
}

From source file:com.netflix.spinnaker.kork.astyanax.EurekaHostSupplier.java

@Override
public List<Host> get() {
    return Optional.ofNullable(discoveryClient.getApplication(applicationName)).map(Application::getInstances)
            .map(List::stream).map(ss -> ss.filter(EurekaHostSupplier::isUp).map(EurekaHostSupplier::buildHost)
                    .collect(Collectors.toList()))
            .orElse(Collections.emptyList());
}

From source file:io.fabric8.spring.cloud.kubernetes.zipkin.ZipkinKubernetesAutoConfiguration.java

private static List<ServiceInstance> getInstances(KubernetesClient client, String name, String namespace) {
    Assert.notNull(name, "[Assertion failed] - the service name must not be null");

    return Optional.ofNullable(client.endpoints().inNamespace(namespace).withName(name).get())
            .orElse(new Endpoints()).getSubsets().stream()
            .flatMap(s -> s.getAddresses().stream()
                    .map(a -> (ServiceInstance) new KubernetesServiceInstance(name, a,
                            s.getPorts().stream().findFirst().orElseThrow(IllegalStateException::new), false)))
            .collect(Collectors.toList());
}

From source file:io.gravitee.repository.redis.management.RedisMembershipRepository.java

@Override
public Optional<Membership> findById(String userId, MembershipReferenceType referenceType, String referenceId)
        throws TechnicalException {
    return Optional
            .ofNullable(convert(membershipRedisRepository.findById(userId, referenceType.name(), referenceId)));
}

From source file:fi.helsinki.opintoni.integration.unisport.UnisportRestClient.java

@Override
public Optional<UnisportUser> getUnisportUserByPrincipal(String username) {
    UnisportUser unisportUser = null;//from  w  ww .j ava 2  s.co m
    try {
        unisportUser = restTemplate
                .exchange("{baseUrl}/api/v1/{locale}/ext/opintoni/authorization?eppn={userName}",
                        HttpMethod.GET, null, new ParameterizedTypeReference<UnisportUser>() {
                        }, baseUrl, new Locale("en"), username)
                .getBody();

    } catch (HttpStatusCodeException e) {
        if (!e.getStatusCode().equals(HttpStatus.NOT_FOUND)) {
            throw e;
        }
    }
    return Optional.ofNullable(unisportUser);
}

From source file:org.apache.ambari.view.web.service.PackageServiceImpl.java

@Override
public Optional<Package> getPackage(Long id) {
    return Optional.ofNullable(packageRepository.findOne(id));
}

From source file:io.github.carlomicieli.footballdb.starter.parsers.Parser.java

public Optional<T> parse(String path, PathBuilder pathBuilder) {
    Validate.notBlank(path, "A path value is required.");

    String url = pathBuilder.build(path);
    Document doc = documentsDownloader.from(url).orElseThrow(DocumentNotFoundException::new);

    return Optional.ofNullable(parseDocument(doc));
}

From source file:keywhiz.auth.cookie.CookieAuthenticator.java

private Optional<UserCookieData> getUserCookieData(Cookie sessionCookie) {
    byte[] ciphertext = Base64.getDecoder().decode(sessionCookie.getValue());
    UserCookieData cookieData = null;//from  w  w w  .  j  a va 2s  .  c  o m

    try {
        cookieData = mapper.readValue(encryptor.decrypt(ciphertext), UserCookieData.class);
        if (cookieData.getExpiration().isBefore(ZonedDateTime.now())) {
            cookieData = null;
        }
    } catch (AEADBadTagException e) {
        logger.warn("Cookie with bad MAC detected");
    } catch (Exception e) {
        /* this cookie ain't gettin decrypted, it's bad */ }

    return Optional.ofNullable(cookieData);
}