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:at.gridtec.lambda4j.function.bi.BiFunction2.java

/**
 * Lifts a partial {@link BiFunction} into a total {@link BiFunction2} that returns an {@link Optional} result.
 *
 * @param <T> The type of the first argument to the function
 * @param <U> The type of the second argument to the function
 * @param <R> The type of return value from the function
 * @param partial A function that is only defined for some values in its domain
 * @return A partial {@code BiFunction} lifted into a total {@code BiFunction2} that returns an {@code Optional}
 * result.//w w w.  jav a 2 s. c  o m
 * @throws NullPointerException If given argument is {@code null}
 */
@Nonnull
static <T, U, R> BiFunction2<T, U, Optional<R>> lift(
        @Nonnull final BiFunction<? super T, ? super U, ? extends R> partial) {
    Objects.requireNonNull(partial);
    return (t, u) -> Optional.ofNullable(partial.apply(t, u));
}

From source file:com.homeadvisor.kafdrop.config.ServiceDiscoveryConfiguration.java

public Map<String, Object> serviceDetails(Integer serverPort) {
    Map<String, Object> details = new LinkedHashMap<>();

    Optional.ofNullable(infoEndpoint.invoke()).ifPresent(
            infoMap -> Optional.ofNullable((Map<String, Object>) infoMap.get("build")).ifPresent(buildInfo -> {
                details.put("serviceName", buildInfo.get("artifact"));
                details.put("serviceDescription", buildInfo.get("description"));
                details.put("serviceVersion", buildInfo.get("version"));
            }));//from w  ww.j av a 2s. com

    final String name = (String) details.getOrDefault("serviceName", "kafdrop");

    String host = null;
    try {
        host = InetAddress.getLocalHost().getHostName();
    } catch (UnknownHostException e) {
        host = "<unknown>";
    }

    details.put("id", Stream.of(name, host, UUID.randomUUID().toString()).collect(Collectors.joining("_")));
    details.put("name", name);
    details.put("host", host);
    details.put("jmxPort", JmxUtils.getJmxPort(environment));
    details.put("jmxHealthMBean", jmxDomain + ":name=" + healthCheckBeanName() + ",type="
            + ClassUtils.getShortName(HealthCheckConfiguration.HealthCheck.class));
    details.put("port", serverPort);

    return details;
}

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

private Optional<String> consumes() {
    String[] produces = Optional.ofNullable(mapping).map(m -> m.consumes()).filter(p -> p.length <= 1)
            .orElseThrow(() -> new IllegalArgumentException(
                    "[consumes] parameter (of @RequestMapping annotation) " + "must have only single value."));

    return (produces.length == 0) ? Optional.empty()
            : Optional.ofNullable(produces[0]).filter(p -> !p.isEmpty())
                    .map(p -> HttpHeaders.CONTENT_TYPE + "=" + p);
}

From source file:com.elytradev.thermionics.api.impl.RotaryGridRecipe.java

public RotaryGridRecipe(ItemStack result, float torque, float revolutions, Object... ingredients) {
    HashMap<Character, Object> ingredientList = new HashMap<>();
    ArrayList<String> arrangement = new ArrayList<>();

    @Nullable/*from  w w  w.j  a va 2  s  .  co  m*/
    Character lastKey = null;
    for (Object o : ingredients) {
        if (o instanceof String) {
            if (lastKey != null) {
                //any tuple<Character, String> found in the sequence is an ingredient identifier
                ingredientList.put(lastKey, o);
            } else {
                //any non-Character-prefixed String is a recipe line identifier
                arrangement.add((String) o);
            }
            lastKey = null;
        } else if (o instanceof Character) {
            Validate.isTrue(lastKey == null, "Orphaned character key '%1$c' in recipe!",
                    Optional.ofNullable(lastKey));
            lastKey = (Character) o;
        } else if (o instanceof ItemStack) {
            Validate.notNull(lastKey, "ItemStack '%1$s' in recipe must be prefixed with a Character key!", o);
            ingredientList.put(lastKey, o);
            lastKey = null;
        }
    }
    int arrangementHeight = Math.min(3, arrangement.size());
    for (int y = 0; y < arrangementHeight; y++) {
        for (int x = 0; x < Math.min(3, arrangement.get(y).length()); x++) {
            char ch = arrangement.get(y).charAt(x);
            @Nullable
            Object ingredient = ingredientList.get(ch);
            //System.out.println("Storing "+ingredient+" for character '"+ch+"' at location "+x+","+y);
            this.ingredients[y * 3 + x] = ingredient;
        }
    }

    this.result = result;
    this.torque = torque;
    this.revolutions = revolutions;

    this.explanation = "{result:\"" + result + "\" recipe:\"";
    for (int i = 0; i < arrangement.size(); i++) {
        explanation += arrangement.get(i);
        if (i != arrangement.size() - 1)
            explanation += " | ";
    }
    this.explanation += "\"}";
}

From source file:de.adorsys.multibanking.hbci.job.ScaRequiredJob.java

public AuthorisationCodeResponse requestAuthorizationCode(TransactionRequest sepaTransactionRequest) {
    HbciTanSubmit hbciTanSubmit = new HbciTanSubmit();

    AuthorisationCodeResponse response = new AuthorisationCodeResponse();
    response.setTanSubmit(hbciTanSubmit);

    Optional.ofNullable(sepaTransactionRequest.getTransaction()).ifPresent(sepaTransaction -> hbciTanSubmit
            .setOriginJobName(getHbciJobName(sepaTransaction.getTransactionType())));

    HbciCallback hbciCallback = new HbciCallback() {

        @Override//from w  w  w. j a v a  2 s .co m
        public void tanChallengeCallback(String orderRef, String challenge, String challengeHhdUc,
                HHDVersion.Type type) {
            //needed later for submitAuthorizationCode
            hbciTanSubmit.setOrderRef(orderRef);
            if (challenge != null) {
                response.setChallenge(TanChallenge.builder().title(challenge).data(challengeHhdUc).build());
            }
        }
    };

    HbciDialogRequest dialogRequest = HbciDialogRequest.builder()
            .bankCode(sepaTransactionRequest.getBankCode() != null ? sepaTransactionRequest.getBankCode()
                    : sepaTransactionRequest.getBankAccess().getBankCode())
            .customerId(sepaTransactionRequest.getBankAccess().getBankLogin())
            .login(sepaTransactionRequest.getBankAccess().getBankLogin2())
            .hbciPassportState(sepaTransactionRequest.getBankAccess().getHbciPassportState())
            .pin(sepaTransactionRequest.getPin()).callback(hbciCallback).build();
    dialogRequest.setProduct(Optional.ofNullable(sepaTransactionRequest.getProduct())
            .map(product -> new Product(product.getName(), product.getVersion())).orElse(null));
    dialogRequest.setBpd(sepaTransactionRequest.getBpd());

    HBCIDialog dialog = createDialog(null, dialogRequest);

    HBCITwoStepMechanism hbciTwoStepMechanism = dialog.getPassport().getBankTwostepMechanisms()
            .get(sepaTransactionRequest.getTanTransportType().getId());
    if (hbciTwoStepMechanism == null)
        throw new MultibankingException(INVALID_SCA_METHOD,
                "inavalid two stem mechanism: " + sepaTransactionRequest.getTanTransportType().getId());

    dialog.getPassport().setCurrentSecMechInfo(hbciTwoStepMechanism);

    AbstractHBCIJob hbciJob = createHbciJob(sepaTransactionRequest.getTransaction(), dialog.getPassport(),
            null);

    GVTAN2Step hktan = new GVTAN2Step(dialog.getPassport());
    hktan.setSegVersion(hbciTwoStepMechanism.getSegversion());

    if (hbciTwoStepMechanism.getProcess() == 1) {
        hbciTanSubmit.setSepaPain(hktanProcess1(hbciTwoStepMechanism, hbciJob, hktan));
        dialog.addTask(hktan, false);
    } else {
        hktanProcess2(dialog, hbciJob,
                getDebtorAccount(sepaTransactionRequest.getTransaction(), dialog.getPassport()), hktan);
    }

    if (dialog.getPassport().tanMediaNeeded()) {
        hktan.setParam("tanmedia", sepaTransactionRequest.getTanTransportType().getMedium());
    }

    HBCIExecStatus status = dialog.execute(false);
    if (!status.isOK()) {
        throw new MultibankingException(HBCI_ERROR, status.getDialogStatus().getErrorString());
    }

    hbciTanSubmit.setPassportState(new HbciPassport.State(dialog.getPassport()).toJson());
    hbciTanSubmit.setDialogId(dialog.getDialogID());
    hbciTanSubmit.setMsgNum(dialog.getMsgnum());
    hbciTanSubmit.setTwoStepMechanism(hbciTwoStepMechanism);
    Optional.ofNullable(hbciJob).ifPresent(abstractSEPAGV -> {
        hbciTanSubmit.setOriginLowLevelName(abstractSEPAGV.getJobName());
        hbciTanSubmit.setOriginSegVersion(abstractSEPAGV.getSegVersion());
        hbciTanSubmit.setHbciJobName(abstractSEPAGV.getHBCICode());
    });

    return response;
}

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

public static <T> Optional<String> convertObjectToJsonString(@NotNull T obj) {
    try {/*from  w  w w . j a  v  a  2  s.c  o  m*/
        return Optional.ofNullable(objectMapper.writeValueAsString(obj));
    } catch (JsonProcessingException e) {
        e.printStackTrace();
    }
    return Optional.empty();
}

From source file:com.arpnetworking.configuration.jackson.BaseJacksonConfiguration.java

/**
 * {@inheritDoc}//from  w  w w .j  a v a2s.  c om
 */
@Override
public <T> Optional<T> getAs(final Class<? extends T> clazz) throws IllegalArgumentException {
    final Optional<JsonNode> property = getJsonSource().getValue();
    if (!property.isPresent()) {
        return Optional.empty();
    }
    try {
        return Optional.ofNullable(_objectMapper.treeToValue(property.get(), clazz));
    } catch (final JsonProcessingException e) {
        throw new IllegalArgumentException(String.format(
                "Unable to construct object from configuration; class=%s, property=%s", clazz, property), e);
    }
}

From source file:com.mycompany.wolf.Router.java

private static String remoteAddress(Session session) {
    return Optional.ofNullable(session.getUserProperties().get("javax.websocket.endpoint.remoteAddress"))
            .map(Object::toString).orElse("?.?.?.?");
}

From source file:com.kazuki43zoo.jpetstore.service.OrderService.java

private int generateOrderId() {
    Sequence sequence = Optional.ofNullable(sequenceMapper.getSequence(ORDER_ID_SEQ_NAME))
            .orElseThrow(() -> new RuntimeException(
                    "Error: A null sequence was returned from the database (could not get next "
                            + ORDER_ID_SEQ_NAME + " sequence)."));
    sequenceMapper.incrementSequence(sequence.getName());
    return sequence.getNextId();
}

From source file:io.mapzone.arena.csw.catalog.CswMetadataDCMI.java

@Override
public Optional<Date> getCreated() {
    return Optional.ofNullable(record().modified).map(v -> v.toGregorianCalendar().getTime());
}