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:io.dfox.junit.http.JUnitHttpApplication.java

/**
 * Run the specified function using the context created by the specified path.
 *
 * @param path The path to the function/*from   www  . ja va  2 s .  c  om*/
 * @param func The function to execute using the runner and parsed path
 * @return The runner Summary
 * @throws InvalidPathException If the path is invalid
 */
public Summary run(final String path, final BiFunction<JUnitHttpRunner, Path, Summary> func)
        throws InvalidPathException {

    final Optional<Path> maybePath = Path.parse(path);

    if (maybePath.isPresent()) {
        Path testPath = maybePath.get();
        final JUnitHttpRunner runner = getRunner(testPath);
        return func.apply(runner, testPath);
    } else {
        throw new InvalidPathException(path);
    }
}

From source file:org.ulyssis.ipp.snapshot.CorrectionEvent.java

protected Snapshot doApply(Snapshot snapshot) {
    TeamStates oldTeamStates = snapshot.getTeamStates();
    Optional<TeamState> oldTeamState = oldTeamStates.getStateForTeam(teamNb);
    TeamState newTeamState;//from   w  w  w  .j  a v a 2s.co m
    if (oldTeamState.isPresent()) {
        newTeamState = oldTeamState.get().addCorrection(correction);
    } else {
        newTeamState = new TeamState().addCorrection(correction);
    }
    return Snapshot.builder(getTime(), snapshot)
            .withTeamStates(snapshot.getTeamStates().setStateForTeam(teamNb, newTeamState)).build();
}

From source file:com.googlesource.gerrit.plugins.lfs.fs.LfsFsContentServlet.java

@Override
protected void doHead(HttpServletRequest req, HttpServletResponse rsp) throws ServletException, IOException {
    String verifyId = req.getHeader(HttpHeaders.IF_NONE_MATCH);
    if (Strings.isNullOrEmpty(verifyId)) {
        doGet(req, rsp);//w  w w .j  a  va 2 s . c  o  m
        return;
    }

    Optional<AnyLongObjectId> obj = validateGetRequest(req, rsp);
    if (obj.isPresent() && obj.get().getName().equalsIgnoreCase(verifyId)) {
        rsp.addHeader(HttpHeaders.ETAG, obj.get().getName());
        rsp.setStatus(HttpStatus.SC_NOT_MODIFIED);
        return;
    }

    getObject(req, rsp, obj);
}

From source file:com.skelril.nitro.point.ValueMapping.java

public Optional<PointType> getValue(Collection<KeyType> key) {
    Validate.isTrue(!key.isEmpty());/*from  ww  w .j a va  2s. c  o  m*/
    Collection<PointValue<KeyType, PointType>> possibleMatches = valueMap
            .get(createIndexOf(key.iterator().next()));
    for (PointValue<KeyType, PointType> possibleMatch : possibleMatches) {
        Optional<PointType> optPoints = matches(key, possibleMatch.getSatisfiers(), possibleMatch.getPoints());
        if (optPoints.isPresent()) {
            return optPoints;
        }
    }
    return Optional.empty();
}

From source file:org.sonarqube.shell.commands.SonarSession.java

void connect(String host, Integer port, String protocol) {
    try {//from   ww  w.j  a v  a  2s.  com
        URI uri = new URL(protocol, host, port, "").toURI();
        consoleOut(String.format("Connecting to: %s", uri));
        rootContext = client.target(uri);
        Optional<Status> status = get("api/system/status", Status.class, empty());
        if (status.isPresent()) {
            consoleOut("Successfully connected to: " + rootContext.getUri());
            consoleOut("Server " + status.get().toString());
            return;
        }
        Optional<QualityGates> failover = get("api/qualitygates/list", QualityGates.class, empty());
        if (failover.isPresent()) {
            consoleOut("Successfully connected to: " + rootContext.getUri());
            return;
        }
    } catch (URISyntaxException | MalformedURLException e) {
        LOGGER.error("Failed to create URI", e);
    }
    disconnect(Optional.of("Server connection failed"));
}

From source file:lumbermill.internal.StringTemplateTest.java

@Test
public void testExtractSingleValue() {
    StringTemplate t = StringTemplate.compile("{field}");
    JsonEvent event = Codecs.TEXT_TO_JSON.from("Hello").put("field", "value");
    Optional<String> formattedString = t.format(event);
    assertThat(formattedString.isPresent()).isTrue();
    assertThat(formattedString.get()).isEqualTo("value");
}

From source file:no.asgari.civilization.server.model.PBF.java

/**
 * Returns the username of the player who is start of turn
 *//*from www. j av a 2 s  .co m*/
@JsonIgnore
public String getNameOfUsersTurn() {
    Optional<Playerhand> optional = players.stream().filter(Playerhand::isYourTurn).findFirst();

    if (optional.isPresent()) {
        return optional.get().getUsername();
    }

    return "";
}

From source file:com.devicehive.dao.rdbms.UserDaoRdbmsImpl.java

private Optional<UserVO> optionalUserConvertToVo(Optional<User> login) {
    if (login.isPresent()) {
        return Optional.ofNullable(User.convertToVo(login.get()));
    }//from w w  w .ja v  a  2 s  . c o m
    return Optional.empty();
}

From source file:com.teradata.benchto.driver.execution.ExecutionDriver.java

private boolean isTimeLimitEnded() {
    Optional<Duration> timeLimit = properties.getTimeLimit();
    return timeLimit.isPresent() && timeLimit.get().compareTo(Duration.between(startTime, nowUtc())) < 0;
}

From source file:net.sf.jabref.logic.fulltext.DoiResolution.java

@Override
public Optional<URL> findFullText(BibEntry entry) throws IOException {
    Objects.requireNonNull(entry);
    Optional<URL> pdfLink = Optional.empty();

    Optional<DOI> doi = entry.getFieldOptional(FieldName.DOI).flatMap(DOI::build);

    if (doi.isPresent()) {
        String sciLink = doi.get().getURIAsASCIIString();

        // follow all redirects and scan for a single pdf link
        if (!sciLink.isEmpty()) {
            try {
                Connection connection = Jsoup.connect(sciLink);
                connection.followRedirects(true);
                connection.ignoreHttpErrors(true);
                // some publishers are quite slow (default is 3s)
                connection.timeout(5000);

                Document html = connection.get();
                // scan for PDF
                Elements elements = html.body().select("[href]");
                List<Optional<URL>> links = new ArrayList<>();

                for (Element element : elements) {
                    String href = element.attr("abs:href");
                    // Only check if pdf is included in the link
                    // See https://github.com/lehner/LocalCopy for scrape ideas
                    if (href.contains("pdf") && MimeTypeDetector.isPdfContentType(href)) {
                        links.add(Optional.of(new URL(href)));
                    }//from w  w w  .  j a  v  a 2s.c  om
                }
                // return if only one link was found (high accuracy)
                if (links.size() == 1) {
                    LOGGER.info("Fulltext PDF found @ " + sciLink);
                    pdfLink = links.get(0);
                }
            } catch (IOException e) {
                LOGGER.warn("DoiResolution fetcher failed: ", e);
            }
        }
    }
    return pdfLink;
}