Example usage for java.util Optional orElse

List of usage examples for java.util Optional orElse

Introduction

In this page you can find the example usage for java.util Optional orElse.

Prototype

public T orElse(T other) 

Source Link

Document

If a value is present, returns the value, otherwise returns other .

Usage

From source file:com.ikanow.aleph2.aleph2_rest_utils.RestCrudFunctions.java

private static <T> Response handleQueryRequest(final Optional<String> query_json,
        final Optional<String> query_id, final ICrudService<T> crud_service, final Class<T> clazz,
        Optional<Long> limit) {
    //get id or a query object that was posted
    //TODO switch to query_id.map().orElse() ... just making a quick swap for the moment
    if (query_id.isPresent()) {
        //ID query
        try {/*from  ww  w .j av a2  s .c om*/
            final String id = query_id.get();
            _logger.debug("id: " + id);
            return Response.ok(RestUtils.convertObjectToJson(crud_service.getObjectById(id).get()).toString())
                    .build();
        } catch (JsonProcessingException | InterruptedException | ExecutionException e) {
            return Response.status(Status.BAD_REQUEST)
                    .entity(ErrorUtils.getLongForm("Error converting input stream to string: {0}", e)).build();
        }
    } else if (query_json.isPresent()) {
        //Body Query
        try {
            final String json = query_json.get();
            _logger.debug("query: " + json);
            final QueryComponent<T> query = RestUtils.convertStringToQueryComponent(json, clazz, limit);
            return Response
                    .ok(RestUtils.convertCursorToJson(crud_service.getObjectsBySpec(query).get()).toString())
                    .build();
        } catch (Exception e) {
            return Response.status(Status.BAD_REQUEST)
                    .entity(ErrorUtils.getLongForm("Error converting input stream to string: {0}", e)).build();
        }
    } else {
        //empty query, does a getall using limit (or 10)
        try {
            _logger.debug("empty query, get all");
            final SingleQueryComponent<T> query = JsonNode.class.isAssignableFrom(clazz)
                    ? (SingleQueryComponent<T>) CrudUtils.allOf()
                    : CrudUtils.allOf(clazz);
            final Cursor<T> cursor = crud_service.getObjectsBySpec(query.limit(limit.orElse(10L))).get();
            return Response.ok(RestUtils.convertCursorToJson(cursor).toString()).build();
        } catch (JsonProcessingException | InterruptedException | ExecutionException e) {
            return Response.status(Status.BAD_REQUEST)
                    .entity(ErrorUtils.getLongForm("Error converting input stream to string: {0}", e)).build();
        }
    }
}

From source file:com.arpnetworking.metrics.common.tailer.StatefulTailer.java

private Optional<Boolean> compareByHash(final Optional<String> prefixHash, final int prefixLength) {
    final int appliedLength;
    if (_hash.isPresent()) {
        appliedLength = REQUIRED_BYTES_FOR_HASH;
    } else {//from w ww . j  av a2s .co  m
        appliedLength = prefixLength;
    }
    try (final SeekableByteChannel reader = Files.newByteChannel(_file, StandardOpenOption.READ)) {
        final Optional<String> filePrefixHash = computeHash(reader, appliedLength);

        LOGGER.trace().setMessage("Comparing hashes").addData("hash1", prefixHash)
                .addData("filePrefixHash", filePrefixHash).addData("size", appliedLength).log();

        return Optional.of(Objects.equals(_hash.orElse(prefixHash.orElse(null)), filePrefixHash.orElse(null)));
    } catch (final IOException e) {
        return Optional.empty();
    }
}

From source file:com.orange.ngsi2.server.Ngsi2BaseController.java

/**
 * Endpoint get /v2/entities/{entityId}/attrs/{attrName}
 * @param entityId the entity ID/*from  ww w .java  2 s  . co m*/
 * @param attrName the attribute name
 * @param type an optional type of entity
 * @return the attribute and http status 200 (ok) or 409 (conflict)
 * @throws Exception
 */
@RequestMapping(method = RequestMethod.GET, value = { "/entities/{entityId}/attrs/{attrName}" })
final public ResponseEntity<Attribute> retrieveAttributeByEntityIdEndpoint(@PathVariable String entityId,
        @PathVariable String attrName, @RequestParam Optional<String> type) throws Exception {

    validateSyntax(entityId, type.orElse(null), attrName);
    return new ResponseEntity<>(retrieveAttributeByEntityId(entityId, attrName, type.orElse(null)),
            HttpStatus.OK);
}

From source file:com.orange.ngsi2.server.Ngsi2BaseController.java

/**
 * Endpoint delete /v2/entities/{entityId}/attrs/{attrName}
 * @param entityId the entity ID/* w  ww  .  j a v  a2 s  .c om*/
 * @param attrName the attribute name
 * @param type an optional type of entity
 * @return http status 204 (no content)
 * @throws Exception
 */
@RequestMapping(method = RequestMethod.DELETE, value = { "/entities/{entityId}/attrs/{attrName}" })
final public ResponseEntity removeAttributeByEntityIdEndpoint(@PathVariable String entityId,
        @PathVariable String attrName, @RequestParam Optional<String> type) throws Exception {

    validateSyntax(entityId, type.orElse(null), attrName);
    removeAttributeByEntityId(entityId, attrName, type.orElse(null));
    return new ResponseEntity(HttpStatus.NO_CONTENT);
}

From source file:com.orange.ngsi2.server.Ngsi2BaseController.java

/**
 * Endpoint get /v2/entities/{entityId}/attrs/{attrName}/value
 * @param entityId the entity ID/*from   w  w  w.j  av  a 2 s  .  c  om*/
 * @param attrName the attribute name
 * @param type an optional type of entity
 * @return the value and http status 200 (ok) or 409 (conflict)
 * @throws Exception
 */
@RequestMapping(method = RequestMethod.GET, value = {
        "/entities/{entityId}/attrs/{attrName}/value" }, produces = MediaType.TEXT_PLAIN_VALUE)
final public ResponseEntity<String> retrievePlainTextAttributeValueEndpoint(@PathVariable String entityId,
        @PathVariable String attrName, @RequestParam Optional<String> type) throws Exception {

    validateSyntax(entityId, type.orElse(null), attrName);
    Object value = retrieveAttributeValue(entityId, attrName, type.orElse(null));
    return new ResponseEntity<>(objectMapper.writeValueAsString(value), HttpStatus.OK);
}

From source file:com.orange.ngsi2.server.Ngsi2BaseController.java

/**
 * Endpoint get /v2/entities/{entityId}/attrs/{attrName}/value
 * @param entityId the entity ID/* ww w . j av a  2s .co m*/
 * @param attrName the attribute name
 * @param type an optional type of entity
 * @return the value and http status 200 (ok) or 409 (conflict)
 * @throws Exception
 */
@RequestMapping(method = RequestMethod.GET, value = {
        "/entities/{entityId}/attrs/{attrName}/value" }, produces = MediaType.APPLICATION_JSON_VALUE)
final public ResponseEntity<Object> retrieveAttributeValueEndpoint(@PathVariable String entityId,
        @PathVariable String attrName, @RequestParam Optional<String> type) throws Exception {

    validateSyntax(entityId, type.orElse(null), attrName);
    Object value = retrieveAttributeValue(entityId, attrName, type.orElse(null));
    if ((value == null) || (value instanceof String) || (value instanceof Number)
            || (value instanceof Boolean)) {
        throw new NotAcceptableException();
    }
    return new ResponseEntity<>(value, HttpStatus.OK);
}

From source file:fr.mtlx.odm.spring.SpringOperationsImpl.java

public List<T> search(final Name base, final SearchControls controls, final String filter,
        final Optional<DirContextProcessor> processor) throws javax.naming.SizeLimitExceededException {

    final SpringSessionImpl session = getSession();

    final TypeSafeCache<DirContextOperations> contextCache = session.getContextCache();

    final ContextMapper<T> cm = new AbstractContextMapper<T>() {
        @Override//from   w ww. j av  a2  s  .  co  m
        protected T doMapFromContext(final DirContextOperations ctx) {
            final Name dn = ctx.getDn();

            contextCache.store(dn, ctx);

            final Object object = session.getFromCacheStack(persistentClass, dn).orElseGet(() -> {

                T entry = contextMapper.doMapFromContext(ctx);

                entryCache.store(dn, entry);

                return entry;

            });

            return typeChecker.convert(object);
        }
    };

    try {
        return operations.search(base, filter, controls, cm, processor.orElse(nullDirContextProcessor));
    } catch (SizeLimitExceededException ex) {
        throw new javax.naming.SizeLimitExceededException(ex.getExplanation());
    }
}

From source file:sx.blah.discord.DiscordClient.java

/**
  * Changes the bot's presence//from www .j  ava  2s.c om
  * 
  * @param isIdle Set to true to make the bot idle or false for it to be online
  * @param gameID The (optional) gameID of the game the bot is playing
  */
public void updatePresence(boolean isIdle, Optional<Long> gameID) {
    String json = "{\"op\":3,\"d\":{\"idle_since\":" + (isIdle ? System.currentTimeMillis() : "null")
            + ",\"game_id\":" + (gameID.isPresent() ? gameID.get() : "null") + "}}";
    Discord4J.logger.debug(json);

    ws.send(json);

    getOurUser().setPresence(isIdle ? Presences.IDLE : Presences.ONLINE);
    getOurUser().setGameID(gameID.orElse(null));
}

From source file:org.ow2.proactive.connector.iaas.cloud.provider.azure.AzureProvider.java

private VirtualMachine.DefinitionStages.WithLinuxCreateManaged configureLinuxVirtualMachine(Azure azureService,
        String instanceTag, Region region, ResourceGroup resourceGroup, InstanceCredentials instanceCredentials,
        VirtualMachineCustomImage image, Creatable<NetworkInterface> creatableNetworkInterface) {
    // Retrieve optional credentials
    Optional<String> optionalUsername = Optional.ofNullable(instanceCredentials)
            .map(InstanceCredentials::getUsername);
    Optional<String> optionalPassword = Optional.ofNullable(instanceCredentials)
            .map(InstanceCredentials::getPassword);
    Optional<String> optionalPublicKey = Optional.ofNullable(instanceCredentials)
            .map(InstanceCredentials::getPublicKey);

    // Prepare the VM without credentials
    VirtualMachine.DefinitionStages.WithLinuxRootPasswordOrPublicKeyManaged creatableVMWithoutCredentials = azureService
            .virtualMachines().define(instanceTag).withRegion(region).withExistingResourceGroup(resourceGroup)
            .withNewPrimaryNetworkInterface(creatableNetworkInterface).withLinuxCustomImage(image.id())
            .withRootUsername(optionalUsername.orElse(DEFAULT_USERNAME));

    // Set the credentials (whether password or SSH key)
    return optionalPublicKey.map(creatableVMWithoutCredentials::withSsh).orElseGet(
            () -> creatableVMWithoutCredentials.withRootPassword(optionalPassword.orElse(DEFAULT_PASSWORD)));
}

From source file:com.orange.ngsi2.server.Ngsi2BaseController.java

/**
 * Endpoint put /v2/entities/{entityId}/attrs/{attrName}/value
 * @param entityId the entity ID//from  ww  w.j  ava 2s .c o  m
 * @param attrName the attribute name
 * @param type an optional type of entity
 * @return http status 204 (No Content) or 409 (conflict)
 * @throws Exception
 */
@RequestMapping(method = RequestMethod.PUT, value = {
        "/entities/{entityId}/attrs/{attrName}/value" }, consumes = MediaType.APPLICATION_JSON_VALUE)
final public ResponseEntity updateAttributeValueEndpoint(@PathVariable String entityId,
        @PathVariable String attrName, @RequestParam Optional<String> type, @RequestBody Object value)
        throws Exception {

    validateSyntax(entityId, type.orElse(null), attrName);
    updateAttributeValue(entityId, attrName, type.orElse(null), value);
    return new ResponseEntity(HttpStatus.NO_CONTENT);
}