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.search_service.elasticsearch.utils.ElasticsearchIndexUtils.java

/** Creates a mapping for the bucket - temporal elements
 * @param bucket//from   w  w  w . ja v  a  2 s  . c  om
 * @return
 * @throws IOException 
 */
public static XContentBuilder getTemporalMapping(final DataBucketBean bucket,
        final Optional<XContentBuilder> to_embed) {
    try {
        final XContentBuilder start = to_embed.orElse(XContentFactory.jsonBuilder().startObject());
        if (!Optional.ofNullable(bucket.data_schema()).map(DataSchemaBean::temporal_schema)
                .filter(s -> Optional.ofNullable(s.enabled()).orElse(true)).isPresent())
            return start;

        // Nothing to be done here

        return start;
    } catch (IOException e) {
        //Handle fake "IOException"
        return null;
    }
}

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

@ExtDirectMethod(value = ExtDirectMethodType.STORE_MODIFY, group = "metadata")
public List<Row> update3(List<Row> rows, @MetadataParam(value = "id") Optional<Integer> id,
        final HttpServletRequest servletRequest) {
    assertThat(id.orElse(2)).isEqualTo(2);
    assertThat(servletRequest).isNotNull();
    return rows;//w  ww  .j  av  a  2 s .co  m
}

From source file:org.codice.ddf.admin.application.service.migratable.ProfileMigratable.java

private boolean restore(MigrationReport report, Optional<InputStream> ois) throws IOException {
    final InputStream is = ois.orElse(null);

    if (is == null) {
        throw new MigrationException("Import error: missing exported profile information.");
    }//from   ww w.j av  a  2 s .c o m
    final JsonProfile jprofile = JsonUtils.fromJson(IOUtils.toString(is, StandardCharsets.UTF_8),
            JsonProfile.class);

    for (int i = 1; i < ProfileMigratable.ATTEMPT_COUNT; i++) {
        LOGGER.debug("importing system profile (attempt {} out of {})", i, ProfileMigratable.ATTEMPT_COUNT);
        final Boolean result = restore(report, jprofile, false);

        if (result != null) {
            return result;
        }
    }
    LOGGER.debug("verifying system profile", ProfileMigratable.ATTEMPT_COUNT, ProfileMigratable.ATTEMPT_COUNT);
    final Boolean result = restore(report, jprofile, true);

    if (result != null) {
        return result;
    }
    // if we get here then we had more tasks to execute after having tried so many times!!!
    throw new IllegalStateException("too many attempts to import profile");
}

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

@ExtDirectMethod(value = ExtDirectMethodType.TREE_LOAD, group = "metadata")
public List<Node> treeLoad3(@RequestParam("node") String node,
        @RequestParam(defaultValue = "defaultValue") String foo,
        @MetadataParam(value = "id") Optional<Integer> id) {
    return RemoteProviderTreeLoad.createTreeList(node, ":" + foo + ";" + id.orElse(23));
}

From source file:org.openmhealth.shim.googlefit.mapper.GoogleFitPhysicalActivityDataPointMapper.java

/**
 * Maps a JSON response node from the Google Fit API to a {@link PhysicalActivity} measure.
 *
 * @param listNode an individual datapoint from the array in the Google Fit response
 * @return a {@link DataPoint} object containing a {@link PhysicalActivity} measure with the appropriate values from
 * the JSON node parameter, wrapped as an {@link Optional}
 *///from w  ww .  j  a  va  2  s .c om
@Override
protected Optional<DataPoint<PhysicalActivity>> asDataPoint(JsonNode listNode) {

    JsonNode listValueNode = asRequiredNode(listNode, "value");
    long activityTypeId = asRequiredLong(listValueNode.get(0), "intVal");

    // This means that the activity was actually sleep, which should be captured using sleep duration, or
    // stationary, which should not be captured as it is the absence of activity
    if (sleepActivityTypes.contains((int) activityTypeId)
            || stationaryActivityTypes.contains((int) activityTypeId)) {

        return Optional.empty();
    }

    String activityName = googleFitDataTypes.get((int) activityTypeId);
    PhysicalActivity.Builder physicalActivityBuilder = new PhysicalActivity.Builder(activityName);
    setEffectiveTimeFrameIfPresent(physicalActivityBuilder, listNode);
    PhysicalActivity physicalActivity = physicalActivityBuilder.build();
    Optional<String> originSourceId = asOptionalString(listNode, "originDataSourceId");
    return Optional.of(newDataPoint(physicalActivity, originSourceId.orElse(null)));

}

From source file:uk.gov.hmrc.controllers.HelloWorldController.java

@RequestMapping("/oauth20/callback")
public String callback(HttpSession session, @RequestParam("code") Optional<String> code,
        @RequestParam("error") Optional<String> error) {
    if (!code.isPresent()) {
        throw new RuntimeException("Couldn't get Authorization code: " + error.orElse("unknown_reason"));
    }//from w w  w  . j a  v a  2 s . c o m
    try {
        Token token = oauthService.getToken(code.get());
        session.setAttribute("userToken", token);
        return "redirect:/hello-user";
    } catch (Exception e) {
        throw new RuntimeException("Failed to get Token", e);
    }
}

From source file:sample.fa.ScriptRunnerApplication.java

private void executeScript(ActionEvent ae) {
    ScriptEngine se = (ScriptEngine) languagesModel.getSelectedItem();
    try (ByteArrayOutputStream baos = new ByteArrayOutputStream(); Writer w = new OutputStreamWriter(baos);) {
        se.getContext().setWriter(w);/* www  . jav  a 2  s .c o  m*/

        Optional<Object> result = Optional.ofNullable(se.eval(scriptContents.getText()));

        scriptResults.setText(baos.toString() + "\n>>>>>>\n" + result.orElse("-null-").toString());
    } catch (Exception e) {
        e.printStackTrace(System.out);
        scriptResults.setText(e.getClass().getName() + " - " + e.getMessage());
    }
}

From source file:org.jbb.members.impl.base.DefaultMemberService.java

@Override
public Optional<Member> getMemberWithUsername(Username username) {
    Optional<MemberEntity> member = memberRepository.findByUsername(username);
    return Optional.ofNullable(member.orElse(null));
}

From source file:org.codice.ddf.registry.schemabindings.helper.InternationalStringTypeHelper.java

/**
 * This is is a convenience method that pulls the string value from the InternationalStringType
 * This convenience method will use the locale to get the string from the LocalizedStringType
 *
 * @param internationalString the internationalStringType, null returns empty String
 * @return the String value pulled from the wrapped localizedString Empty string if a matching
 *     language tag is not found//  w ww  .j a  va 2 s .  c  o  m
 */
public String getString(InternationalStringType internationalString) {
    Optional<String> optionalString = Optional.empty();
    if (internationalString != null) {
        optionalString = getLocalizedString(internationalString.getLocalizedString());
    }

    return optionalString.orElse("");
}

From source file:org.jbb.members.impl.base.DefaultMemberService.java

@Override
public Optional<Member> getMemberWithDisplayedName(DisplayedName displayedName) {
    Optional<MemberEntity> member = memberRepository.findByDisplayedName(displayedName);
    return Optional.ofNullable(member.orElse(null));
}