Example usage for java.util Optional isPresent

List of usage examples for java.util Optional isPresent

Introduction

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

Prototype

public boolean isPresent() 

Source Link

Document

If a value is present, returns true , otherwise false .

Usage

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

/**
 * Gets the SessionKey from the Execution Parameter.
 * @param webflowkey {@link String}/*  w ww.j a  va  2s  . 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:gov.ca.cwds.cals.util.PlacementHomeUtil.java

private static StringBuilder composeSecondPartOfFacilityName(Optional<ApplicantDTO> firstApplicant,
        ApplicantDTO secondApplicant) {//from   ww  w.jav  a  2s  . c om
    StringBuilder sbForSecondApplicant = new StringBuilder();
    Optional<String> secondLastName = Optional.ofNullable(secondApplicant.getLastName());
    Optional<String> secondFirstName = Optional.ofNullable(secondApplicant.getFirstName());
    if (firstApplicant.isPresent() && secondLastName.isPresent()
            && !secondLastName.get().equals(firstApplicant.get().getLastName())) {
        sbForSecondApplicant.append(secondLastName.get());
        if (secondFirstName.isPresent()) {
            sbForSecondApplicant.append(", ");
        }
    }
    secondFirstName.ifPresent(sbForSecondApplicant::append);
    return sbForSecondApplicant;
}

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

private static List<Comparator<BibEntry>> getSaveComparators(SavePreferences preferences, MetaData metaData) {

    List<Comparator<BibEntry>> comparators = new ArrayList<>();
    Optional<SaveOrderConfig> saveOrder = getSaveOrder(preferences, metaData);

    if (!saveOrder.isPresent()) {
        // Take care, using CrossRefEntry-Comparator, that referred entries occur after referring
        // ones. Apart from crossref requirements, entries will be sorted based on their creation order,
        // utilizing the fact that IDs used for entries are increasing, sortable numbers.
        comparators.add(new CrossRefEntryComparator());
        comparators.add(new IdComparator());
    } else {/*from ww w . j a  v a 2s  .c  o  m*/
        comparators.add(new CrossRefEntryComparator());

        comparators.add(new FieldComparator(saveOrder.get().sortCriteria[0]));
        comparators.add(new FieldComparator(saveOrder.get().sortCriteria[1]));
        comparators.add(new FieldComparator(saveOrder.get().sortCriteria[2]));

        comparators.add(new FieldComparator(BibEntry.KEY_FIELD));
    }

    return comparators;
}

From source file:io.github.retz.web.JobRequestHandler.java

static String schedule(spark.Request req, spark.Response res) throws IOException, InterruptedException {
    ScheduleRequest scheduleRequest = MAPPER.readValue(req.bodyAsBytes(), ScheduleRequest.class);
    res.type("application/json");
    Optional<Application> maybeApp = Applications.get(scheduleRequest.job().appid()); // TODO check owner right here
    if (!maybeApp.isPresent()) {
        // TODO: this warn log cannot be written in real stable release
        LOG.warn("No such application loaded: {}", scheduleRequest.job().appid());
        ErrorResponse response = new ErrorResponse("No such application: " + scheduleRequest.job().appid());
        res.status(404);//  w w  w.jav  a  2  s  . c om
        return MAPPER.writeValueAsString(response);

    } else if (maybeApp.get().enabled()) {

        validateOwner(req, maybeApp.get());

        Job job = scheduleRequest.job();
        if (scheduler.isPresent()) {
            if (!scheduler.get().validateJob(job)) {
                String msg = "Job " + job.toString() + " does not fit system limit "
                        + scheduler.get().maxJobSize();
                // TODO: this warn log cannot be written in real stable release
                LOG.warn(msg);
                halt(400, msg);
            }
        }

        job.schedule(JobQueue.issueJobId(), TimestampHelper.now());

        JobQueue.push(job);
        if (scheduler.isPresent() && driver.isPresent()) {
            LOG.info("Trying invocation from offer stock: {}", job);
            scheduler.get().maybeInvokeNow(driver.get(), job);

        }

        ScheduleResponse scheduleResponse = new ScheduleResponse(job);
        scheduleResponse.ok();
        LOG.info("Job '{}' at {} has been scheduled at {}.", job.cmd(), job.appid(), job.scheduled());

        res.status(201);
        return MAPPER.writeValueAsString(scheduleResponse);

    } else {
        // Application is currently disabled
        res.status(401);
        ErrorResponse response = new ErrorResponse("Application " + maybeApp.get().getAppid() + " is disabled");
        return MAPPER.writeValueAsString(response);
    }
}

From source file:net.sf.jabref.model.DuplicateCheck.java

private static int compareSingleField(String field, BibEntry one, BibEntry two) {
    Optional<String> optionalStringOne = one.getFieldOptional(field);
    Optional<String> optionalStringTwo = two.getFieldOptional(field);
    if (!optionalStringOne.isPresent()) {
        if (!optionalStringTwo.isPresent()) {
            return EMPTY_IN_BOTH;
        }//from   ww w .  j av a2  s .c  om
        return EMPTY_IN_ONE;
    } else if (!optionalStringTwo.isPresent()) {
        return EMPTY_IN_TWO;
    }

    // Both strings present
    String stringOne = optionalStringOne.get();
    String stringTwo = optionalStringTwo.get();

    if (InternalBibtexFields.getFieldExtras(field).contains(FieldProperties.PERSON_NAMES)) {
        // Specific for name fields.
        // Harmonise case:
        String authorOne = AuthorList.fixAuthorLastNameOnlyCommas(stringOne, false).replace(" and ", " ")
                .toLowerCase();
        String authorTwo = AuthorList.fixAuthorLastNameOnlyCommas(stringTwo, false).replace(" and ", " ")
                .toLowerCase();
        double similarity = DuplicateCheck.correlateByWords(authorOne, authorTwo);
        if (similarity > 0.8) {
            return EQUAL;
        }
        return NOT_EQUAL;
    } else if (FieldName.PAGES.equals(field)) {
        // Pages can be given with a variety of delimiters, "-", "--", " - ", " -- ".
        // We do a replace to harmonize these to a simple "-":
        // After this, a simple test for equality should be enough:
        stringOne = stringOne.replaceAll("[- ]+", "-");
        stringTwo = stringTwo.replaceAll("[- ]+", "-");
        if (stringOne.equals(stringTwo)) {
            return EQUAL;
        }
        return NOT_EQUAL;
    } else if (FieldName.JOURNAL.equals(field)) {
        // We do not attempt to harmonize abbreviation state of the journal names,
        // but we remove periods from the names in case they are abbreviated with
        // and without dots:
        stringOne = stringOne.replace(".", "").toLowerCase();
        stringTwo = stringTwo.replace(".", "").toLowerCase();
        double similarity = DuplicateCheck.correlateByWords(stringOne, stringTwo);
        if (similarity > 0.8) {
            return EQUAL;
        }
        return NOT_EQUAL;
    } else {
        stringOne = stringOne.toLowerCase();
        stringTwo = stringTwo.toLowerCase();
        double similarity = DuplicateCheck.correlateByWords(stringOne, stringTwo);
        if (similarity > 0.8) {
            return EQUAL;
        }
        return NOT_EQUAL;
    }
}

From source file:com.freiheit.fuava.sftp.util.FilenameUtil.java

/**
 * Returns the lastest date/time from a list of filenames.
 *///from w  w w . j a va2  s. c o  m
@CheckForNull
public static String extractLatestDateFromFilenames(final List<String> entryList, final FileType fileType,
        @Nullable final RemoteFileStatus status) throws ParseException {
    final Optional<String> maxDate = entryList.stream().filter(p -> p != null)
            .filter(f -> FilenameUtil.matchesSearchedFile(f, fileType, null, status))
            .max((a, b) -> Long.compare(getDateFromFilename(a), getDateFromFilename(b)));

    if (!maxDate.isPresent()) {
        return null; // no timestamp found
    }
    final String max = maxDate.get();

    return String.valueOf(getDateFromFilenameWithDelimiter(max));
}

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;//  w w  w  . ja va 2 s .co m
    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:com.formkiq.core.form.bean.ObjectBuilder.java

/**
 * Populate {@link FormJSON} from {@link Map}.
 * @param form {@link FormJSON}//from w ww.  j av  a2s  .com
 * @param values {@link Map}
 */
public static void populate(final FormJSON form, final Map<String, String> values) {

    if (values != null) {
        for (Map.Entry<String, String> e : values.entrySet()) {

            Optional<FormJSONField> op = findValueByKey(form, e.getKey());
            if (op.isPresent()) {
                if (e.getValue() != null) {
                    op.get().setValue(e.getValue());
                } else {
                    op.get().setValue("");
                }
            }
        }
    }
}

From source file:io.github.retz.web.JobRequestHandler.java

static String downloadFile(spark.Request req, spark.Response res) throws Exception {
    Optional<Job> job = getJobAndVerify(req);
    String file = req.queryParams("path");
    LOG.debug("download: path={}", file);

    if (job.isPresent() && job.get().url() != null) { // If url() is null, the job hasn't yet been started at Mesos
        MesosHTTPFetcher.downloadHTTPFile(job.get().url(), file,
                (Triad<Integer, String, Pair<Long, InputStream>> triad) -> {
                    Integer statusCode = triad.left();
                    res.status(statusCode);
                    if (statusCode == 200) {
                        Long length = triad.right().left();
                        InputStream io = triad.right().right();
                        Long maxFileSize = scheduler.get().maxFileSize();
                        if (length < 0) {
                            throw new IOException("content length is negative: " + length);
                        } else if (0 <= maxFileSize && maxFileSize < length) { // negative maxFileSize indicates no limit
                            throw new DownloadFileSizeExceeded(length, maxFileSize);
                        }//  ww  w . j  a  va  2s  . c om
                        res.raw().setHeader("Content-Length", length.toString());
                        LOG.debug("start streaming of {} bytes for {}", length, file);
                        IOUtils.copyLarge(io, res.raw().getOutputStream(), 0, length);
                        LOG.debug("end streaming for {}", file);
                    } else {
                        res.body(triad.center());
                    }
                });
        return "";
    } else {
        res.status(404);
        return "";
    }
}

From source file:alfio.manager.NotificationManager.java

private static Function<Map<String, String>, byte[]> receiptOrInvoiceFactory(EventRepository eventRepository,
        Function<Triple<Event, Locale, Map<String, Object>>, Optional<byte[]>> pdfGenerator) {
    return (model) -> {
        String reservationId = model.get("reservationId");
        Event event = eventRepository.findById(Integer.valueOf(model.get("eventId"), 10));
        Locale language = Json.fromJson(model.get("language"), Locale.class);

        Map<String, Object> reservationEmailModel = Json.fromJson(model.get("reservationEmailModel"),
                new TypeReference<Map<String, Object>>() {
                });/*from  w  w w.j  ava2s  .c o  m*/
        //FIXME hack: reservationEmailModel should be a minimal and typed container
        reservationEmailModel.put("event", event);
        Optional<byte[]> receipt = pdfGenerator.apply(Triple.of(event, language, reservationEmailModel));

        if (!receipt.isPresent()) {
            log.warn("was not able to generate the receipt for reservation id " + reservationId + " for locale "
                    + language);
        }
        return receipt.orElse(null);
    };
}