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:ai.grakn.engine.controller.SystemController.java

@GET
@Path("/metrics")
@ApiOperation(value = "Exposes internal metrics")
@ApiImplicitParams({//from   w w  w .  j av  a 2  s . co m
        @ApiImplicitParam(name = FORMAT, value = "prometheus", dataType = "string", paramType = "path") })
private String getMetrics(Request request, Response response) throws IOException {
    response.header(CACHE_CONTROL, "must-revalidate,no-cache,no-store");
    response.status(HttpServletResponse.SC_OK);
    Optional<String> format = Optional.ofNullable(request.queryParams(FORMAT));
    String dFormat = format.orElse(JSON);
    if (dFormat.equals(PROMETHEUS)) {
        // Prometheus format for the metrics
        response.type(PROMETHEUS_CONTENT_TYPE);
        final Writer writer1 = new StringWriter();
        TextFormat.write004(writer1, this.prometheusRegistry.metricFamilySamples());
        return writer1.toString();
    } else if (dFormat.equals(JSON)) {
        // Json/Dropwizard format
        response.type(APPLICATION_JSON);
        final ObjectWriter writer = mapper.writer();
        try (ByteArrayOutputStream output = new ByteArrayOutputStream()) {
            writer.writeValue(output, this.metricRegistry);
            return new String(output.toByteArray(), "UTF-8");
        }
    } else {
        throw new IllegalArgumentException("Unexpected format " + dFormat);
    }
}

From source file:com.ikanow.aleph2.search_service.elasticsearch.utils.ElasticsearchIndexUtils.java

/** Creates a mapping for the bucket - search service elements .. up to but not including the mapping + type
 *  NOTE: creates an embedded object that is {{, ie must be closed twice subsequently in order to be a well formed JSON object
 * @param bucket/*w w  w  .j a v a  2s.  c om*/
 * @return
 * @throws IOException 
 */
public static XContentBuilder getSearchServiceMapping(final DataBucketBean bucket,
        final Optional<String> secondary_buffer, final boolean is_primary,
        final ElasticsearchIndexServiceConfigBean schema_config, final Optional<XContentBuilder> to_embed,
        final ObjectMapper mapper) {
    try {
        final XContentBuilder start = to_embed.orElse(XContentFactory.jsonBuilder().startObject());

        // (Nullable)
        final ElasticsearchIndexServiceConfigBean.SearchIndexSchemaDefaultBean search_schema = schema_config
                .search_technology_override();

        //(very briefly Nullable)
        final JsonNode settings = Optional.ofNullable(search_schema).map(s -> s.settings())
                .map(o -> mapper.convertValue(o, JsonNode.class)).orElse(null);

        //(very briefly Nullable)
        final ObjectNode aliases = (ObjectNode) Optional.ofNullable(search_schema).map(s -> s.aliases())
                .map(o -> mapper.convertValue(o, JsonNode.class)).orElse(mapper.createObjectNode());

        if (is_primary) { // add the "read only" prefix alias
            aliases.set(
                    ElasticsearchContext.READ_PREFIX
                            + ElasticsearchIndexUtils.getBaseIndexName(bucket, Optional.empty()),
                    mapper.createObjectNode());
        }

        // Settings

        final String type_key = getTypeKey(bucket, mapper);

        return Lambdas.wrap_u(__ -> {
            if (null == settings) { // nothing to do
                return start;
            } else {
                return start.rawField("settings", settings.toString().getBytes());
            }
        })
                // Aliases
                .andThen(Lambdas.wrap_u(json -> {
                    if (!aliases.elements().hasNext()) { // nothing to do
                        return json;
                    } else {
                        return start.rawField("aliases", aliases.toString().getBytes());
                    }
                }))
                // Mappings and overrides
                .andThen(Lambdas.wrap_u(json -> json.startObject("mappings").startObject(type_key)))
                // Add the secondary buffer name to the metadata:
                .andThen(Lambdas.wrap_u(json -> {
                    return json.rawField(CUSTOM_META,
                            createMergedMeta(Either.right(mapper), bucket, is_primary, secondary_buffer)
                                    .toString().getBytes());
                }))
                // More mapping overrides
                .andThen(Lambdas.wrap_u(json -> {

                    return Optional.ofNullable(search_schema).map(ss -> ss.mapping_overrides())
                            .map(m -> m.getOrDefault(type_key, m.get("*"))).orElse(Collections.emptyMap())
                            .entrySet().stream().reduce(json, Lambdas.wrap_u((acc, kv) -> {
                                if (CUSTOM_META.equals(kv.getKey())) { // meta is a special case, merge my results in regardless
                                    return acc.rawField(kv.getKey(),
                                            createMergedMeta(
                                                    Either.left(
                                                            mapper.convertValue(kv.getValue(), JsonNode.class)),
                                                    bucket, is_primary, secondary_buffer).toString()
                                                            .getBytes());
                                } else {
                                    return acc.rawField(kv.getKey(), mapper
                                            .convertValue(kv.getValue(), JsonNode.class).toString().getBytes());
                                }
                            }), (acc1, acc2) -> acc1 // (can't actually ever happen)
                    );
                })).apply(null);
    } catch (IOException e) {
        //Handle fake "IOException"
        return null;
    }
}

From source file:com.devicehive.service.NetworkService.java

@Transactional
public NetworkVO createOrVerifyNetwork(Optional<NetworkVO> networkNullable) {
    //case network is not defined
    if (networkNullable == null || networkNullable.orElse(null) == null) {
        return null;
    }//from ww  w  .  j  a v a 2s . c o  m
    NetworkVO network = networkNullable.get();

    Optional<NetworkVO> storedOpt = findNetworkByIdOrName(network);
    if (storedOpt.isPresent()) {
        return validateNetworkKey(storedOpt.get(), network);
    } else {
        if (network.getId() != null) {
            throw new IllegalParametersException(Messages.INVALID_REQUEST_PARAMETERS);
        }
        boolean allowed = configurationService.getBoolean(ALLOW_NETWORK_AUTO_CREATE, false);
        if (allowed) {
            NetworkWithUsersAndDevicesVO newNetwork = new NetworkWithUsersAndDevicesVO(network);
            networkDao.persist(newNetwork);
            network.setId(newNetwork.getId());
        }
        return network;
    }
}

From source file:com.smoketurner.notification.api.Rule.java

/**
 * Constructor//from   w w  w.j  a v  a  2  s .c  o  m
 *
 * @param maxSize
 *            Maximum number of notifications to include in a roll-up
 * @param maxDuration
 *            Maximum time duration between the first and last notifications
 *            in a roll-up
 * @param matchOn
 *            Group notifications by a specific category
 */
@JsonCreator
private Rule(@JsonProperty(MAX_SIZE) final Optional<Integer> maxSize,
        @JsonProperty(MAX_DURATION) final Optional<String> maxDuration,
        @JsonProperty(MATCH_ON) final Optional<String> matchOn) {
    this.maxSize = maxSize.orElse(null);
    if (maxDuration.isPresent()) {
        this.maxDuration = Duration.parse(maxDuration.get());
    } else {
        this.maxDuration = null;
    }
    this.matchOn = matchOn.orElse(null);
}

From source file:io.gravitee.gateway.resource.internal.ResourceManagerImpl.java

@Override
public <T> T getResource(Class<T> requiredType) {
    Optional<T> resource = (Optional<T>) resources.values().stream()
            .filter(resourceEntry -> resourceEntry.getClass().isAssignableFrom(requiredType)).findFirst();

    return resource.orElse(null);
}

From source file:ch.ralscha.extdirectspring.provider.RemoteProviderOptional.java

@ExtDirectMethod(group = "optional", synchronizeOnSession = true)
public String method7(@RequestHeader(defaultValue = "default", required = false) Optional<String> header) {
    return header.orElse("this is the default");
}

From source file:ch.ralscha.extdirectspring.provider.RemoteProviderOptional.java

@ExtDirectMethod(value = ExtDirectMethodType.SSE, group = "optional")
public Optional<String> sse1(@RequestParam(value = "id") Optional<Integer> id, Optional<String> dummy) {
    return Optional.of(id.orElse(-1) + ":" + dummy.orElse("default_value"));
}

From source file:com.netflix.spinnaker.orca.clouddriver.utils.TrafficGuard.java

public void verifyInstanceTermination(String serverGroupNameFromStage, List<String> instanceIds, String account,
        Location location, String cloudProvider, String operationDescriptor) {
    Map<String, List<String>> instancesPerServerGroup = new HashMap<>();
    for (String instanceId : instanceIds) {
        String serverGroupName = serverGroupNameFromStage;
        if (serverGroupName == null) {
            Optional<String> resolvedServerGroupName = resolveServerGroupNameForInstance(instanceId, account,
                    location.getValue(), cloudProvider);
            serverGroupName = resolvedServerGroupName.orElse(null);
        }//from w w w. ja v  a  2 s .  com

        if (serverGroupName != null) {
            instancesPerServerGroup.computeIfAbsent(serverGroupName, serverGroup -> new ArrayList<>())
                    .add(instanceId);
        }
    }

    instancesPerServerGroup.entrySet().forEach(entry -> {
        String serverGroupName = entry.getKey();
        Names names = Names.parseName(serverGroupName);
        if (hasDisableLock(names.getCluster(), account, location)) {
            Optional<TargetServerGroup> targetServerGroup = oortHelper.getTargetServerGroup(account,
                    serverGroupName, location.getValue(), cloudProvider);

            targetServerGroup.ifPresent(serverGroup -> {
                Optional<Map> thisInstance = serverGroup.getInstances().stream()
                        .filter(i -> "Up".equals(i.get("healthState"))).findFirst();
                if (thisInstance.isPresent() && "Up".equals(thisInstance.get().get("healthState"))) {
                    long otherActiveInstances = serverGroup.getInstances().stream().filter(
                            i -> "Up".equals(i.get("healthState")) && !entry.getValue().contains(i.get("name")))
                            .count();
                    if (otherActiveInstances == 0) {
                        verifyOtherServerGroupsAreTakingTraffic(serverGroupName, location, account,
                                cloudProvider, operationDescriptor);
                    }
                }
            });
        }
    });
}

From source file:ch.ralscha.extdirectspring.provider.RemoteProviderOptional.java

@ExtDirectMethod(group = "optional")
public String method16(@CookieValue Optional<Integer> intCookie, @CookieValue Optional<Boolean> booleanCookie) {
    return intCookie.orElse(-1) + ";" + booleanCookie.orElse(false);
}

From source file:ch.ralscha.extdirectspring.provider.RemoteProviderOptional.java

@ExtDirectMethod(group = "optional")
public String method6(@RequestHeader(value = "anotherName", defaultValue = "default") Optional<String> header) {
    return header.orElse("another default");
}