Example usage for java.util Optional get

List of usage examples for java.util Optional get

Introduction

In this page you can find the example usage for java.util Optional get.

Prototype

public T get() 

Source Link

Document

If a value is present, returns the value, otherwise throws NoSuchElementException .

Usage

From source file:com.ikanow.aleph2.aleph2_rest_utils.RestCrudFunctions.java

private static <T> Response handleDeleteRequest(final Optional<String> query_json,
        final Optional<String> query_id, final ICrudService<T> crud_service, final Class<T> clazz) {
    //get id or a query object that was posted
    if (query_id.isPresent()) {
        //ID delete
        try {/* w w w.  jav a2 s.  com*/
            final String id = query_id.get();
            _logger.debug("id: " + id);
            return Response.ok(RestUtils.convertSingleObjectToJson(crud_service.deleteObjectById(id).get(),
                    DELETE_SUCCESS_FIELD_NAME).toString()).build();
        } catch (InterruptedException | ExecutionException e) {
            return Response.status(Status.BAD_REQUEST)
                    .entity(ErrorUtils.getLongForm("Error converting input stream to string: {0}", e)).build();
        }
    } else if (query_json.isPresent()) {
        //Body delete
        try {
            final String json = query_json.get();
            _logger.debug("query: " + json);
            final QueryComponent<T> query = RestUtils.convertStringToQueryComponent(json, clazz,
                    Optional.empty());
            return Response.ok(RestUtils.convertSingleObjectToJson(crud_service.deleteObjectBySpec(query).get(),
                    DELETE_SUCCESS_FIELD_NAME).toString()).build();
        } catch (Exception e) {
            return Response.status(Status.BAD_REQUEST)
                    .entity(ErrorUtils.getLongForm("Error converting input stream to string: {0}", e)).build();
        }
    } else {
        //TODO actually we should probably just do something else when this is empty (like return first item, or search all and return limit 10, etc)
        return Response.status(Status.BAD_REQUEST)
                .entity("DELETE requires an id in the url or query in the body").build();
    }
}

From source file:com.github.horrorho.inflatabledonkey.cloud.clients.KeyBagClient.java

static Optional<KeyBag> keyBag(CloudKit.RecordRetrieveResponse response, ProtectionZone zone) {
    Optional<byte[]> keyBagData = field(response.getRecord(), "keybagData", zone::decrypt);
    if (!keyBagData.isPresent()) {
        logger.warn("-- keyBag() - failed to acquire key bag");
        return Optional.empty();
    }/* w w  w .  j  av  a 2  s  .  c om*/

    Optional<byte[]> secret = field(response.getRecord(), "secret", zone::decrypt);
    if (!secret.isPresent()) {
        logger.warn("-- keyBag() - failed to acquire key bag pass code");
        return Optional.empty();
    }

    KeyBag keyBag = KeyBagFactory.create(keyBagData.get(), secret.get());
    return Optional.of(keyBag);
}

From source file:com.epam.ta.reportportal.database.search.QueryBuilder.java

public static Function<FilterCondition, Criteria> filterConverter(CriteriaMap<?> map) {
    return filterCondition -> {
        Optional<CriteriaHolder> criteriaHolder = map
                .getCriteriaHolderUnchecked(filterCondition.getSearchCriteria());
        BusinessRule.expect(criteriaHolder, Preconditions.IS_PRESENT)
                .verify(ErrorType.INCORRECT_FILTER_PARAMETERS, Suppliers.formattedSupplier(
                        "Filter parameter {} is not defined", filterCondition.getSearchCriteria()));

        Criteria searchCriteria;//from  w ww .  j  a  v  a 2  s.  c  om
        if (criteriaHolder.get().isReference()) {
            searchCriteria = Criteria.where(criteriaHolder.get().getQueryCriteria().concat(REFERENCE_POSTFIX));
        } else {
            searchCriteria = Criteria.where(criteriaHolder.get().getQueryCriteria());
        }

        /* Does FilterCondition contains negative=true? */
        if (filterCondition.isNegative()) {
            searchCriteria = searchCriteria.not();
        }

        filterCondition.getCondition().addCondition(searchCriteria, filterCondition, criteriaHolder.get());

        return searchCriteria;
    };
}

From source file:com.formkiq.core.webflow.FlowManager.java

/**
 * Gets the SessionKey from the Execution Parameter.
 * @param webflowkey {@link String}//from   ww w. j  av  a 2 s . c o m
 * @return {@link Pair}
 */
public static Pair<String, Integer> getExecutionSessionKey(final String webflowkey) {

    String s = null;
    Integer e = null;

    if (StringUtils.hasText(webflowkey)) {
        TokenizerService ts = new TokenizerServiceImpl(webflowkey);
        Optional<TokenizerToken> session = ts.nextToken();
        Optional<TokenizerToken> sessionNo = ts.nextToken();
        Optional<TokenizerToken> event = ts.nextToken();
        Optional<TokenizerToken> eventNo = ts.nextToken();

        boolean tokensPresent = session.isPresent() && sessionNo.isPresent() && event.isPresent()
                && eventNo.isPresent();

        if (tokensPresent && session.get().getType().equals(TokenType.STRING)
                && sessionNo.get().getType().equals(TokenType.INTEGER)
                && event.get().getType().equals(TokenType.STRING)
                && eventNo.get().getType().equals(TokenType.INTEGER)) {
            s = session.get().getValue() + sessionNo.get().getValue();
            e = Integer.valueOf(eventNo.get().getValue());
        }
    }

    return Pair.of(s, e);
}

From source file:com.wrmsr.wava.TestOutlining.java

public static Pair<Function, Function> inlineThatOneSwitch(Function function, int num) {
    Node body = function.getBody();

    LocalAnalysis loa = LocalAnalysis.analyze(body);
    ControlTransferAnalysis cfa = ControlTransferAnalysis.analyze(body);
    ValueTypeAnalysis vta = ValueTypeAnalysis.analyze(body, false);

    Map<Node, Optional<Node>> parentsByNode = Analyses.getParents(body);
    Map<Node, Integer> totalChildrenByNode = Analyses.getChildCounts(body);
    Map<Name, Node> nodesByName = Analyses.getNamedNodes(body);

    Node maxNode = body;/*from www . j a  va  2  s.c  om*/
    int maxDiff = 0;

    Node cur = body;
    while (true) {
        Optional<Node> maxChild = cur.getChildren().stream()
                .max((l, r) -> Integer.compare(totalChildrenByNode.get(l), totalChildrenByNode.get(r)));
        if (!maxChild.isPresent()) {
            break;
        }
        int diff = totalChildrenByNode.get(cur) - totalChildrenByNode.get(maxChild.get());
        if (diff > maxDiff) {
            maxNode = cur;
            maxDiff = diff;
        }
        cur = maxChild.get();
    }

    List<Node> alsdfj = new ArrayList<>(maxNode.getChildren());
    Collections.sort(alsdfj,
            (l, r) -> -Integer.compare(totalChildrenByNode.get(l), totalChildrenByNode.get(r)));

    Index externalRetControl;
    Index externalRetValue;
    List<Local> localList;

    if (function.getLocals().getLocalsByName().containsKey(Name.of("_external$control"))) {
        externalRetControl = function.getLocals().getLocal(Name.of("_external$control")).getIndex();
        externalRetValue = function.getLocals().getLocal(Name.of("_external$value")).getIndex();
        localList = function.getLocals().getList();
    } else {
        externalRetControl = Index.of(function.getLocals().getList().size());
        externalRetValue = Index.of(function.getLocals().getList().size() + 1);
        localList = ImmutableList.<Local>builder().addAll(function.getLocals().getList())
                .add(new Local(Name.of("_external$control"), externalRetControl, Type.I32))
                .add(new Local(Name.of("_external$value"), externalRetValue, Type.I64)).build();
    }

    Node node = maxNode;
    if (maxNode instanceof Switch) {
        Switch switchNode = (Switch) node;
        Optional<Switch.Entry> maxEntry = switchNode.getEntries().stream().max((l, r) -> Integer
                .compare(totalChildrenByNode.get(l.getBody()), totalChildrenByNode.get(r.getBody())));
        node = maxEntry.get().getBody();
    }

    Outlining.OutlinedFunction of = Outlining.outlineFunction(function, node,
            Name.of(function.getName().get() + "$outlined$" + num), externalRetControl, externalRetValue, loa,
            cfa, vta, parentsByNode, nodesByName);

    Function newFunc = new Function(function.getName(), function.getResult(), function.getArgCount(),
            new Locals(localList), Transforms.replaceNode(function.getBody(), node, of.getCallsite(), true));

    return ImmutablePair.of(newFunc, of.getFunction());
}

From source file:de.hybris.platform.acceleratorstorefrontcommons.tags.Functions.java

public static boolean isQuoteUserSalesRep() {
    final UserModel userModel = getQuoteUserIdentificationStrategy(getCurrentRequest()).getCurrentQuoteUser();
    final Optional<QuoteUserType> quoteUserTypeOptional = getQuoteUserTypeIdentificationStrategy(
            getCurrentRequest()).getCurrentQuoteUserType(userModel);
    return quoteUserTypeOptional.isPresent() && QuoteUserType.SELLER.equals(quoteUserTypeOptional.get());
}

From source file:net.sf.jabref.exporter.BibDatabaseWriter.java

private static List<FieldChange> applySaveActions(List<BibEntry> toChange, MetaData metaData) {
    List<FieldChange> changes = new ArrayList<>();

    Optional<FieldFormatterCleanups> saveActions = metaData.getSaveActions();
    if (saveActions.isPresent()) {
        // save actions defined -> apply for every entry
        for (BibEntry entry : toChange) {
            changes.addAll(saveActions.get().applySaveActions(entry));
        }/*w w w . ja v  a2  s . c  o  m*/
    }

    return changes;
}

From source file:de.fosd.jdime.Main.java

/**
 * Parses the given <code>artifact</code> to an AST and attempts to find a node with the given <code>number</code>
 * in the tree. If found, the {@link DumpMode#PRETTY_PRINT_DUMP} will be used to dump the node to standard out.
 * If <code>scope</code> is not {@link KeyEnums.Type#NODE}, the method will walk up the tree to find a node that
 * fits the requested <code>scope</code> and dump it instead.
 *
 * @param artifact//from w  w w  .  j  a  va  2s .  c  om
 *         the <code>FileArtifact</code> to parse to an AST
 * @param number
 *         the number of the <code>artifact</code> in the AST to find
 * @param scope
 *         the scope to dump
 */
private static void inspectElement(FileArtifact artifact, int number, KeyEnums.Type scope) {
    ASTNodeArtifact astArtifact = new ASTNodeArtifact(artifact);
    Optional<Artifact<ASTNodeArtifact>> foundNode = astArtifact.find(number);

    if (foundNode.isPresent()) {
        Artifact<ASTNodeArtifact> element = foundNode.get();

        if (scope != KeyEnums.Type.NODE) {
            // walk tree upwards until scope fits
            while (scope != element.getType() && !element.isRoot()) {
                element = element.getParent();
            }
        }

        System.out.println(element.dump(DumpMode.PRETTY_PRINT_DUMP));
    } else {
        LOG.log(Level.WARNING, () -> "Could not find a node with number " + number + ".");
    }
}

From source file:com.spotify.styx.docker.KubernetesPodEventTranslator.java

private static Optional<Event> isInErrorState(WorkflowInstance workflowInstance, Pod pod) {
    final PodStatus status = pod.getStatus();
    final String phase = status.getPhase();

    switch (phase) {
    case "Pending":
        // check if one or more docker contains failed to pull their image, a possible silent error
        return status.getContainerStatuses().stream()
                .filter(IS_STYX_CONTAINER.and(KubernetesPodEventTranslator::hasPullImageError)).findAny()
                .map((x) -> Event.runError(workflowInstance,
                        "One or more containers failed to pull their image"));

    case "Succeeded":
    case "Failed":
        final Optional<ContainerStatus> containerStatusOpt = pod.getStatus().getContainerStatuses().stream()
                .filter(IS_STYX_CONTAINER).findFirst();

        if (!containerStatusOpt.isPresent()) {
            return Optional.of(Event.runError(workflowInstance, "Could not find our container in pod"));
        }/*from w w w.  j  av a  2s  .  c om*/

        final ContainerStatus containerStatus = containerStatusOpt.get();
        final ContainerStateTerminated terminated = containerStatus.getState().getTerminated();
        if (terminated == null) {
            return Optional.of(Event.runError(workflowInstance, "Unexpected null terminated status"));
        }
        return Optional.empty();

    case "Unknown":
        return Optional.of(Event.runError(workflowInstance, "Pod entered Unknown phase"));

    default:
        return Optional.empty();
    }
}

From source file:info.archinnov.achilles.internals.schema.SchemaValidator.java

public static void validateDefaultTTL(AbstractTableMetadata metadata, Optional<Integer> staticTTL,
        Class<?> entityClass) {
    if (staticTTL.isPresent()) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug(format("Validating table %s default TTL value", metadata.getName()));
        }//w ww . j  av  a  2 s .com
        final int defaultTimeToLive = metadata.getOptions().getDefaultTimeToLive();
        validateBeanMappingTrue(staticTTL.get().equals(defaultTimeToLive),
                "Default TTL '%s' declared on entity '%s' does not match detected default TTL '%s' in live schema",
                staticTTL.get(), entityClass.getCanonicalName(), defaultTimeToLive);
    }
}