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:alfio.controller.DynamicResourcesController.java

@RequestMapping("/resources/js/google-analytics")
public void getGoogleAnalyticsScript(HttpSession session, HttpServletResponse response,
        @RequestParam("e") Integer eventId) throws IOException {
    response.setContentType("application/javascript");
    Optional<Event> ev = Optional.ofNullable(eventId)
            .flatMap(id -> Optional.ofNullable(eventRepository.findById(id)));
    ConfigurationPathKey pathKey = ev//from  www .j a v  a 2 s.  c  o  m
            .map(e -> Configuration.from(e.getOrganizationId(), e.getId(), GOOGLE_ANALYTICS_KEY))
            .orElseGet(() -> Configuration.getSystemConfiguration(GOOGLE_ANALYTICS_KEY));
    final Optional<String> id = configurationManager.getStringConfigValue(pathKey);
    final String script;
    ConfigurationPathKey anonymousPathKey = ev
            .map(e -> Configuration.from(e.getOrganizationId(), e.getId(), GOOGLE_ANALYTICS_ANONYMOUS_MODE))
            .orElseGet(() -> Configuration.getSystemConfiguration(GOOGLE_ANALYTICS_ANONYMOUS_MODE));
    if (id.isPresent() && configurationManager.getBooleanConfigValue(anonymousPathKey, true)) {
        String trackingId = Optional
                .ofNullable(StringUtils.trimToNull((String) session.getAttribute("GA_TRACKING_ID")))
                .orElseGet(() -> UUID.randomUUID().toString());
        Map<String, Object> model = new HashMap<>();
        model.put("clientId", trackingId);
        model.put("account", id.get());
        script = templateManager.renderTemplate(TemplateResource.GOOGLE_ANALYTICS, model, Locale.ENGLISH);
    } else {
        script = id.map(x -> String.format(GOOGLE_ANALYTICS_SCRIPT, x)).orElse(EMPTY);
    }
    response.getWriter().write(script);
}

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

private String[] mappedHeaders() {
    return Optional.ofNullable(mapping).map(m -> m.headers()).orElseGet(() -> new String[0]);
}

From source file:org.obiba.mica.micaConfig.service.OpalCredentialService.java

public void createOrUpdateOpalCredential(String opalUrl, String username, String password) {
    OpalCredential credential = Optional.ofNullable(repository.findOne(opalUrl)).map(c -> {
        if (c.getAuthType() == AuthType.CERTIFICATE)
            keyStoreService.deleteKeyPair(OpalService.OPAL_KEYSTORE, opalUrl);
        c.setAuthType(AuthType.USERNAME);
        c.setUsername(username);//from  w  ww  .j a v  a 2 s  .  c  o m
        c.setPassword(micaConfigService.encrypt(password));

        return c;
    }).orElse(new OpalCredential(opalUrl, AuthType.USERNAME, username, micaConfigService.encrypt(password)));

    repository.save(credential);
}

From source file:com.microsoft.azure.hdinsight.sdk.rest.ObjectConvertUtils.java

public static <T> Optional<List<T>> convertJsonToList(@NotNull String jsonString, Class<T> tClass)
        throws IOException {
    List<T> myLists = objectMapper.readValue(jsonString,
            TypeFactory.defaultInstance().constructCollectionType(List.class, tClass));
    return Optional.ofNullable(myLists);
}

From source file:alfio.model.modification.TicketWithStatistic.java

public LocalDateTime getTimestamp() {
    return Optional.ofNullable(ticketReservation.getConfirmationTimestamp()).map(dateMapper).orElse(null);
}

From source file:net.cyphoria.cylus.service.konto.DefaultKontoService.java

@Override
public Optional<Konto> findeKontoMitKontoNummer(final Integer kontoNummer) {
    return Optional.ofNullable(kontoRepository.findByKontoNummer(kontoNummer));
}

From source file:org.ow2.proactive.connector.iaas.service.InstanceService.java

public void deleteCreatedInstances(String infrastructureId) {
    Optional.ofNullable(infrastructureService.getInfrastructure(infrastructureId)).ifPresent(infrastructure -> {
        cloudManager.getAllInfrastructureInstances(infrastructure).stream().filter(
                instance -> instanceCache.getCreatedInstances().get(infrastructureId).contains(instance))
                .forEach(instance -> {
                    cloudManager.deleteInstance(infrastructure, instance.getId());
                    instanceCache.deleteInfrastructureInstance(infrastructure, instance);
                });/*from w  ww. j a v a2 s. co  m*/
    });
}

From source file:io.knotx.knot.action.domain.FormEntity.java

public Optional<String> url(String signal) {
    return Optional.ofNullable(signalToUrl.get(signal));
}

From source file:it.greenvulcano.gvesb.debug.DebuggerServlet.java

/**
 * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse)
 *//*from www  .  j  a v  a 2  s  .  c  o  m*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {

        StringBuffer sb = new StringBuffer();
        dump(request, sb);
        LOG.debug(sb.toString());

        DebugCommand debugOperation = Optional.ofNullable(request.getParameter("debugOperation"))
                .map(DebugCommand::valueOf).orElseThrow(IllegalArgumentException::new);

        PrintWriter writer = response.getWriter();

        Map<DebugKey, String> params = request.getParameterMap().keySet().stream().filter(KEYS::contains)
                .map(DebugKey::valueOf)
                .collect(Collectors.toMap(Function.identity(), k -> request.getParameter(k.name())));

        DebuggerObject dObj = gvDebugger.processCommand(debugOperation, params);

        if (dObj == null) {
            dObj = DebuggerObject.FAIL_DEBUGGER_OBJECT;
        }
        String debugOperationResponse = dObj.toXML();

        LOG.debug("Debug operation response: " + debugOperationResponse);
        writer.println(debugOperationResponse);
    } catch (IllegalArgumentException e) {
        LOG.error("Fail to process debug operation: missing or invalid value for parameter debugOperation");
        response.getWriter().println("Missing or invalid value for parameter debugOperation");
    } catch (Exception e) {
        LOG.error("Fail to process debug operation", e);
        throw new ServletException(e);
    }
}

From source file:com.rockagen.gnext.service.spring.AccountServImpl.java

/**
 * Offer the maximum priority of the list.
 *
 * @param list list//from  w  ww.j a v  a  2 s.com
 * @return Account
 */
private Optional<Account> filter(List<Account> list) {
    Account tmp = list.get(0);
    if (list.size() > 1) {
        tmp = list.stream().filter(x -> x.getStatus() == AccountStatus.OPEN)
                .min((a, b) -> a.getPriority().compareTo(b.getPriority())).get();
    }
    return Optional.ofNullable(tmp);

}