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:de.jfachwert.post.Postfach.java

/**
 * Erzeugt ein Postfach.//from  w  w w  .  j a  v  a  2 s.c  o  m
 * 
 * @param nummer positive Zahl oder leer
 * @param ort Ort
 */
public Postfach(Optional<BigInteger> nummer, Ort ort) {
    this.nummer = nummer.orElse(null);
    this.ort = ort;
    if (this.nummer == null) {
        verify(ort);
    } else {
        verify(nummer.get(), ort);
    }
}

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

@ExtDirectMethod(value = ExtDirectMethodType.TREE_LOAD, group = "optional")
public List<Node> treeLoad2(@RequestParam("node") Optional<String> node, HttpServletResponse response,
        @RequestHeader Optional<Boolean> aHeader, HttpServletRequest request) {

    return RemoteProviderTreeLoad.createTreeList(node.get(),
            ":" + aHeader.orElse(true) + ";" + (response != null) + ";" + (request != null));
}

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

private Optional<String> resolveServerGroupNameForInstance(String instanceId, String account, String region,
        String cloudProvider) {/*from w  w w  . j a  v  a2  s  .  c  o  m*/
    List<Map> searchResults = (List<Map>) oortHelper.getSearchResults(instanceId, "instances", cloudProvider)
            .get(0).getOrDefault("results", new ArrayList<>());
    Optional<Map> instance = searchResults.stream()
            .filter(r -> account.equals(r.get("account")) && region.equals(r.get("region"))).findFirst();
    // instance not found, assume it's already terminated, what could go wrong
    return Optional.ofNullable((String) instance.orElse(new HashMap<>()).get("serverGroup"));
}

From source file:com.pinterest.rocksplicator.controller.resource.Clusters.java

/**
 * Loads sst files from s3 into a given cluster.
 *
 * @param clusterName name of the cluster
 * @param segmentName name of the segment
 * @param s3Bucket    S3 bucket name//from   w w w  .j ava 2s.  co m
 * @param s3Prefix    prefix of the S3 path
 * @param concurrency maximum number of hosts concurrently loading
 * @param rateLimit   s3 download size limit in mb
 */
@POST
@Path("/loadData/{clusterName : [a-zA-Z0-9\\-_]+}")
public void loadData(@PathParam("clusterName") String clusterName,
        @NotEmpty @QueryParam("segmentName") String segmentName,
        @NotEmpty @QueryParam("s3Bucket") String s3Bucket, @NotEmpty @QueryParam("s3Prefix") String s3Prefix,
        @QueryParam("concurrency") Optional<Integer> concurrency,
        @QueryParam("rateLimit") Optional<Integer> rateLimit) {
    try {
        TaskBase task = new LoadSSTTask(segmentName, s3Bucket, s3Prefix, concurrency.orElse(20),
                rateLimit.orElse(64)).getEntity();
        taskQueue.enqueueTask(task, clusterName, 0);
    } catch (JsonProcessingException e) {
        throw new WebApplicationException(e);
    }
}

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

@ExtDirectMethod(value = ExtDirectMethodType.POLL, group = "optional")
public Optional<String> opoll5(@RequestParam(value = "id", required = false) Optional<Integer> id,
        Optional<String> dummy, @CookieValue Optional<String> cookie) {
    return Optional.of(id.orElse(23) + ";" + dummy.orElse("dummy") + ";" + cookie.orElse("cookie"));
}

From source file:com.ikanow.aleph2.data_model.utils.TimeUtils.java

/** Attempts to parse a (typically recurring) time  
 * @param human_readable_duration - Uses some simple regexes (1h,d, 1month etc), and Natty (try examples http://natty.joestelmach.com/try.jsp#)
 * @param base_date - for relative date, locks the date to this origin (mainly for testing in this case?)
 * @return the machine readable duration, or an error
 *///from   w w w. j  av  a 2 s  . c o m
public static Validation<String, Duration> getDuration(final String human_readable_duration,
        Optional<Date> base_date) {
    // There's a few different cases:
    // - the validation from getTimePeriod
    // - a slightly more complicated version <N><p> where <p> == period from the above
    // - use Natty for more complex expressions

    final Validation<String, ChronoUnit> first_attempt = getTimePeriod(human_readable_duration);
    if (first_attempt.isSuccess()) {
        return Validation
                .success(Duration.of(first_attempt.success().getDuration().getSeconds(), ChronoUnit.SECONDS));
    } else { // Slightly more complex version
        final Matcher m = date_parser.matcher(human_readable_duration);
        if (m.matches()) {
            final Validation<String, Duration> candidate_ret = getTimePeriod(m.group(2)).map(cu -> {
                final LocalDateTime now = LocalDateTime.now();
                return Duration.between(now, now.plus(Integer.parseInt(m.group(1)), cu));
            });

            if (candidate_ret.isSuccess())
                return candidate_ret;
        }
    }
    // If we're here then try Natty
    final Date now = base_date.orElse(new Date());
    return getSchedule(human_readable_duration, Optional.of(now)).map(d -> {
        final long duration = d.getTime() - now.getTime();
        return Duration.of(duration, ChronoUnit.MILLIS);
    });
}

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

@ExtDirectMethod(value = ExtDirectMethodType.SSE, group = "optional")
public SSEvent sse2(@RequestParam(value = "id") Optional<Integer> id, @CookieValue Optional<String> cookie) {
    SSEvent event = new SSEvent();
    event.setId("2");
    event.setData(id.orElse(-1) + ";" + cookie.orElse("defaultCookieValue"));
    return event;
}

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

@OptionalNamedMethod
public Optional<ResultObject> namedMethod2(HttpSession session,
        @RequestParam(value = "lastName") Optional<String> name,
        @RequestParam(value = "theAge") Optional<Integer> age, Optional<Boolean> active) {
    assertThat(session).isNotNull();/*from  w w  w  .  j  a va  2 s . co m*/
    return Optional.of(new ResultObject(name.get(), age.orElse(21), active.orElse(true)));
}

From source file:net.sf.jabref.model.database.BibDatabase.java

/**
 * Returns the text stored in the given field of the given bibtex entry
 * which belongs to the given database.//from ww w .j a  va 2s.c o m
 * <p>
 * If a database is given, this function will try to resolve any string
 * references in the field-value.
 * Also, if a database is given, this function will try to find values for
 * unset fields in the entry linked by the "crossref" field, if any.
 *
 * @param field    The field to return the value of.
 * @param entry    maybenull
 *                 The bibtex entry which contains the field.
 * @param database maybenull
 *                 The database of the bibtex entry.
 * @return The resolved field value or null if not found.
 */
public static String getResolvedField(String field, BibEntry entry, BibDatabase database) {
    if ("bibtextype".equals(field)) {
        return EntryUtil.capitalizeFirst(entry.getType());
    }

    // TODO: Changed this to also consider alias fields, which is the expected
    // behavior for the preview layout and for the check whatever all fields are present.
    // But there might be unwanted side-effects?!
    Optional<String> result = entry.getFieldOrAlias(field);

    // If this field is not set, and the entry has a crossref, try to look up the
    // field in the referred entry: Do not do this for the bibtex key.
    if (!result.isPresent() && (database != null) && !field.equals(BibEntry.KEY_FIELD)) {
        Optional<String> crossrefKey = entry.getFieldOptional(FieldName.CROSSREF);
        if (crossrefKey.isPresent()) {
            Optional<BibEntry> referred = database.getEntryByKey(crossrefKey.get());
            if (referred.isPresent()) {
                // Ok, we found the referred entry. Get the field value from that
                // entry. If it is unset there, too, stop looking:
                result = referred.get().getFieldOptional(field);
            }
        }
    }

    return BibDatabase.getText(result.orElse(null), database);
}

From source file:org.jboss.tools.openshift.internal.core.server.debug.OpenShiftDebugUtils.java

public ILaunchConfiguration getRemoteDebuggerLaunchConfiguration(IServer server) throws CoreException {
    ILaunchConfigurationType launchConfigurationType = launchManager
            .getLaunchConfigurationType(ID_REMOTE_JAVA_APPLICATION);
    ILaunchConfiguration[] launchConfigs = launchManager.getLaunchConfigurations(launchConfigurationType);
    String name = getRemoteDebuggerLaunchConfigurationName(server);
    Optional<ILaunchConfiguration> maybeLaunch = Stream.of(launchConfigs)
            .filter(lc -> name.equals(lc.getName())).findFirst();

    return maybeLaunch.orElse(null);
}