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:io.mapzone.arena.csw.catalog.CswMetadataDCMI.java

protected Optional<String> join(Collection<String> parts) {
    return Optional
            .ofNullable(parts != null && !parts.isEmpty() ? Joiner.on("\n\n").skipNulls().join(parts) : null);
}

From source file:com.javafxpert.wikibrowser.WikiLocatorController.java

@RequestMapping(method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Object> locatorEndpoint(@RequestParam(value = "id", defaultValue = "") String itemId,
        @RequestParam(value = "lang") String lang) {

    String language = wikiBrowserProperties.computeLang(lang);

    ItemInfo itemInfo = null;/*from  w  w  w .j av  a2 s  . com*/
    if (!itemId.equals("")) {
        itemInfo = id2Name(itemId, language);
    }

    return Optional.ofNullable(itemInfo).map(cr -> new ResponseEntity<>((Object) cr, HttpStatus.OK))
            .orElse(new ResponseEntity<>("Wikidata query unsuccessful", HttpStatus.INTERNAL_SERVER_ERROR));
}

From source file:com.kazuki43zoo.apistub.api.key.FixedLengthKeyExtractor.java

@Override
public List<Object> extract(HttpServletRequest request, byte[] requestBody, String... expressions) {
    if (requestBody == null || requestBody.length == 0) {
        return Collections.emptyList();
    }/*from  w  w  w  . j ava2 s  .c  o  m*/

    Charset defaultCharset = Optional.ofNullable(request.getContentType()).map(MediaType::parseMediaType)
            .map(MediaType::getCharset).orElse(StandardCharsets.UTF_8);

    return Stream.of(expressions).map(expression -> {
        String[] defines = StringUtils.splitByWholeSeparatorPreserveAllTokens(expression, ",");
        if (defines.length <= 2) {
            return null;
        }
        int offset = Integer.parseInt(defines[0].trim());
        int length = Integer.parseInt(defines[1].trim());
        String type = defines[2].trim().toLowerCase();
        final Charset charset;
        if (defines.length >= 4) {
            charset = Charset.forName(defines[3].trim());
        } else {
            charset = defaultCharset;
        }
        if (!(requestBody.length >= offset && requestBody.length >= offset + length)) {
            return null;
        }
        return Optional.ofNullable(FUNCTIONS.get(type)).orElseThrow(() -> new IllegalArgumentException(
                "A bad expression is detected. The specified type does not support. expression: '" + expression
                        + "', specified type: '" + type + "', allowing types: " + FUNCTIONS.keySet()))
                .apply(Arrays.copyOfRange(requestBody, offset, offset + length), charset);
    }).filter(Objects::nonNull).collect(Collectors.toList());
}

From source file:com.example.app.repository.ui.RepositoryItemValueEditor.java

@Nullable
@Override//from w  w  w.  jav  a  2 s  .com
public RI commitValue() throws MIWTException {
    RI result = super.commitValue();
    return Optional.ofNullable(result)
            .orElseThrow(() -> new IllegalStateException("Result RepositoryItem was null."));
}

From source file:co.runrightfast.vertx.orientdb.impl.OrientDBPoolServiceImpl.java

@Override
public Optional<ODatabaseDocumentTxSupplier> getODatabaseDocumentTxSupplier(final String name) {
    checkArgument(isNotBlank(name));/*from  w  w w . j a  va  2 s.  c  om*/
    return Optional.ofNullable(oDatabaseDocumentTxSuppliers.get(name));
}

From source file:com.github.ljtfreitas.restify.http.spring.contract.metadata.reflection.SpringWebJavaTypeMetadata.java

public SpringWebJavaTypeMetadata(Class<?> javaType) {
    isTrue(javaType.isInterface(), "Your type must be a Java interface.");
    isTrue(javaType.getInterfaces().length <= 1, "Only single inheritance is supported.");

    RequestMapping mapping = AnnotatedElementUtils.getMergedAnnotation(javaType, RequestMapping.class);
    if (mapping != null) {
        isTrue(mapping.value().length <= 1, "Only single path is allowed.");
        isTrue(mapping.method().length == 0,
                "You must not set the HTTP method at the class level, only at the method level.");
    }/*from  w ww .j  a  v  a2s.  co m*/

    this.mapping = Optional.ofNullable(mapping).map(m -> new SpringWebRequestMappingMetadata(m));
    this.javaType = javaType;
    this.parent = javaType.getInterfaces().length == 1
            ? new SpringWebJavaTypeMetadata(javaType.getInterfaces()[0])
            : null;
}

From source file:com.example.app.resource.model.ResourceDAO.java

/**
 * Get a Resource of the given Class for the given Id
 *
 * @param <R> the resource type//from w  w w.  j a  v a 2 s . com
 * @param clazz the Resource class
 * @param id the ID
 *
 * @return the resource
 */
@SuppressWarnings("unchecked")
public <R extends Resource> Optional<R> getResource(Class<R> clazz, Integer id) {
    return Optional.ofNullable((R) getSession().get(clazz, id));
}

From source file:com.cybernostics.jsp2thymeleaf.api.expressions.function.FunctionConverterSource.java

public Optional<ExpressionVisitor> converterFor(PrefixedName domTag) {
    return Optional.ofNullable(converterMap.get(domTag.getName()));
}

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

/**
 * Retrieves the altered visibility for a method of a specific name (if any).
 *//* w  w w . j  av a 2s.c om*/
@Nonnull
public Optional<Visibility> getMethodVisibility(@Nonnull String methodName) {
    return Optional.ofNullable(this.methods.get(methodName));
}

From source file:io.github.retz.web.JobRequestRouter.java

public static String getFile(spark.Request req, spark.Response res) throws IOException {
    int id = Integer.parseInt(req.params(":id"));

    String file = req.queryParams("path");
    long offset = Long.parseLong(req.queryParams("offset"));
    long length = Long.parseLong(req.queryParams("length"));
    Optional<Job> job = JobQueue.getJob(id);

    LOG.debug("get-file: id={}, path={}, offset={}, length={}", id, file, offset, length);
    res.type("application/json");

    Optional<FileContent> fileContent;
    if (job.isPresent() && job.get().url() != null // If url() is null, the job hasn't yet been started at Mesos
            && statHTTPFile(job.get().url(), file)) {
        String payload = fetchHTTPFile(job.get().url(), file, offset, length);
        LOG.debug("Payload length={}, offset={}", payload.length(), offset);
        // TODO: what the heck happens when a file is not UTF-8 encodable???? How Mesos works?
        fileContent = Optional.ofNullable(MAPPER.readValue(payload, FileContent.class));
    } else {//w  w w.j  a  va 2s. c o m
        fileContent = Optional.empty();
    }
    GetFileResponse getFileResponse = new GetFileResponse(job, fileContent);
    getFileResponse.ok();
    res.status(200);

    return MAPPER.writeValueAsString(getFileResponse);
}