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.azure.AzureServiceBuilder.java

public Azure buildServiceFromInfrastructure(Infrastructure infrastructure) {

    // Get credentials
    InfrastructureCredentials infrastructureCredentials = Optional.ofNullable(infrastructure.getCredentials())
            .orElseThrow(() -> new RuntimeException(
                    "ERROR missing infrastructure credentials from: " + infrastructure));
    String clientId = Optional.ofNullable(infrastructureCredentials.getUsername()).orElseThrow(
            () -> new RuntimeException("ERROR missing username/clientId credential from: " + infrastructure));
    String domain = Optional.ofNullable(infrastructureCredentials.getDomain()).orElseThrow(
            () -> new RuntimeException("ERROR missing domain/tenantId credential from: " + infrastructure));
    String secret = Optional.ofNullable(infrastructureCredentials.getPassword()).orElseThrow(
            () -> new RuntimeException("ERROR missing password/secret credential from: " + infrastructure));
    Optional<String> optionalSubscription = Optional.ofNullable(infrastructureCredentials.getSubscriptionId());

    AzureEnvironment environment = getAzureEnvironment(infrastructure);

    AzureTokenCredentials credentials = new ApplicationTokenCredentials(clientId, domain, secret, environment);
    Azure azure;//  w  w w .  java 2 s  .c o  m
    try {
        Azure.Authenticated authenticatedAzureService = Azure.configure().withLogLevel(LogLevel.NONE)
                .authenticate(credentials);
        if (optionalSubscription.isPresent()) {
            azure = authenticatedAzureService.withSubscription(optionalSubscription.get());
        } else {
            try {
                azure = authenticatedAzureService.withDefaultSubscription();
            } catch (CloudException | IOException e) {
                throw new RuntimeException(
                        "ERROR trying to create Azure service with default subscription ID: " + infrastructure,
                        e);
            }
        }
    } catch (Throwable throwable) {
        throw new RuntimeException(
                "ERROR something goes wrong while trying to create Azure service from infrastructure: "
                        + infrastructure,
                throwable);
    }

    return azure;
}

From source file:org.obiba.mica.study.rest.StudyStateResource.java

@GET
@Path("/projects")
public List<Projects.ProjectDto> projects() throws URISyntaxException {
    subjectAclService.checkPermission(resource, "VIEW", id);
    String opalUrl = Optional.ofNullable(studyService.findStudy(id)).map(BaseStudy::getOpal).orElse(null);

    return opalService.getProjectDtos(opalUrl);
}

From source file:net.pkhsolutions.pecsapp.model.PageModel.java

@NotNull
public Optional<Page> getEntity() {
    return Optional.ofNullable(entity);
}

From source file:com.ikanow.aleph2.logging.utils.LoggingUtils.java

/**
 * Builds a JsonNode log message object, contains fields for date, message, generated_by, bucket, subsystem, and severity
 * //www.j  a  v  a2  s .c om
 * @param level
 * @param bucket
 * @param message
 * @param isSystemMessage
 * @return
 */
public static JsonNode createLogObject(final Level level, final DataBucketBean bucket,
        final BasicMessageBean message, final boolean isSystemMessage, final String date_field,
        final String hostname) {
    return Optional.ofNullable(message.details()).map(d -> _mapper.convertValue(d, ObjectNode.class))
            .orElseGet(() -> _mapper.createObjectNode()).put(date_field, message.date().getTime())
            .put("message", message.message()).put("generated_by", isSystemMessage ? "system" : "user")
            .put("bucket", bucket.full_name()).put("subsystem", message.source())
            .put("command", message.command()).put("severity", level.toString()).put("hostname", hostname);
}

From source file:org.trustedanalytics.servicecatalog.service.rest.ServiceInstancesControllerHelpers.java

public void mergeServiceKeys(Collection<ServiceInstance> instances, Observable<ServiceKey> serviceKeys) {
    Map<UUID, List<ServiceKey>> serviceKeysIndex = createServiceKeysIndex(serviceKeys);

    instances.stream().forEach(i -> i
            .setServiceKeys(Optional.ofNullable(serviceKeysIndex.get(i.getGuid())).orElse(new ArrayList<>())));
}

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

public Optional<Api> findByName(String apiName) throws TechnicalException {
    return Optional.ofNullable(apiJpaConverter.convertTo(internalJpaApiRepository.findOne(apiName)));
}

From source file:com.ejisto.modules.repository.WebApplicationRepository.java

public Optional<WebApplication<?>> getRegisteredWebApplication(String containerId, String context) {
    if (StringUtils.isBlank(containerId)) {
        return Optional.empty();
    }//from   w  ww.  j av a2 s .  co  m
    return Optional.ofNullable(webApplications.get(containerId)).map(m -> m.get(context));
}

From source file:cn.edu.zjnu.acm.judge.service.LanguageService.java

@SpecialCall("problems/status.html")
public String getLanguageName(int languageId) {
    return Optional.ofNullable(languageMapper.findOne(languageId)).map(Language::getName)
            .orElse("unknown language " + languageId);
}

From source file:com.github.lukaszkusek.xml.comparator.diff.DifferenceInformation.java

public DifferenceInformation(Node node1, Node node2, String attributeName, DifferenceCode differenceCode) {
    Preconditions.checkArgument(differenceCode != null, "DifferenceCode cannot be null.");

    this.node1 = Optional.ofNullable(node1);
    this.node2 = Optional.ofNullable(node2);
    this.attributeName = attributeName;
    this.differenceCode = differenceCode;
}

From source file:com.epages.checkout.CartController.java

@PutMapping("/{cartId}")
public ResponseEntity<Resource<Cart>> addLineItem(@PathVariable Long cartId,
        @RequestBody @Valid AddLineItemRequest addLineItemRequest) {
    return Optional.ofNullable(cartRepository.findOne(cartId))
            .map(cart -> addLineItemOrIncrementQuantity(cart, addLineItemRequest))
            .map(cart -> cartRepository.saveAndFlush(cart))
            .map(cart -> new Resource<>(cart, entityLinks.linkForSingleResource(cart).withSelfRel()))
            .map(ResponseEntity::ok).orElse(ResponseEntity.notFound().build());
}