Example usage for java.util Optional of

List of usage examples for java.util Optional of

Introduction

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

Prototype

public static <T> Optional<T> of(T value) 

Source Link

Document

Returns an Optional describing the given non- null value.

Usage

From source file:io.moo.propane.sources.ClasspathFileConfigurationSource.java

@Override
public Optional<ConfigData> read(final Class clazz) {

    try (InputStreamReader reader = new InputStreamReader(
            getClass().getClassLoader().getResourceAsStream(source))) {

        List<ConfigurationEntity> entities = new ArrayList<>();

        parse(getSource(), mapper.readTree(reader), new ArrayList<>(), entities, 0);

        return Optional.of(new ConfigData(getSource(), entities));

    } catch (IOException e) {
        LOG.error(e);//  w  w  w  . j a va  2 s.c  om
        return Optional.empty();
    }
}

From source file:org.ow2.proactive.workflow_catalog.rest.controller.WorkflowRevisionControllerTest.java

@Test
public void testList() throws Exception {
    Pageable mockedPageable = mock(Pageable.class);
    PagedResourcesAssembler mockedAssembler = mock(PagedResourcesAssembler.class);
    workflowRevisionController.list(BUCKET_ID, WF_ID, Optional.empty(), mockedPageable, mockedAssembler);
    verify(workflowRevisionService, times(1)).listWorkflows(BUCKET_ID, Optional.of(WF_ID), Optional.empty(),
            mockedPageable, mockedAssembler);
}

From source file:org.zalando.logbook.httpclient.Request.java

@Override
public String getContentType() {
    return Optional.of(request).map(request -> request.getFirstHeader("Content-Type")).map(Header::getValue)
            .orElse("");
}

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

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

    Optional<DOI> doi = DOI.build(entry.getField("doi"));

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

        // 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 ww .  j ava 2  s.  c  o m
                }
                // 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;
}

From source file:jobhunter.persistence.Persistence.java

private Optional<Profile> _readProfile(final File file) {

    try (ZipFile zfile = new ZipFile(file)) {
        l.debug("Reading profile from JHF File");
        final InputStream in = zfile.getInputStream(new ZipEntry("profile.xml"));

        MessageDigest md = MessageDigest.getInstance("MD5");
        DigestInputStream dis = new DigestInputStream(in, md);

        final Object obj = xstream.fromXML(dis);

        updateLastMod(file, md);//from   w  ww  .j  a  v a 2  s  .c om

        return Optional.of((Profile) obj);
    } catch (Exception e) {
        l.error("Failed to read file: {}", e.getMessage());
    }

    return Optional.empty();
}

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

void connect(String host, Integer port, String protocol) {
    try {//  ww  w.j av a 2 s  . 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:com.ejisto.util.collector.FieldNode.java

public Optional<FieldNode> findDirectParent(MockedField mockedField) {
    String difference = difference(path, mockedField.getComparisonKey());
    if (isNotEmpty(difference) && difference.substring(1).equals(mockedField.getFieldName())) {
        return Optional.of(this);
    }//ww  w  . j  av  a2  s . c  om
    return children.stream().filter(c -> c.isParentOf(mockedField)).map(c -> c.findDirectParent(mockedField))
            .filter(Optional::isPresent).map(Optional::get).findAny();
}

From source file:it.polimi.diceH2020.SPACE4Cloud.shared.inputData.old.InstanceData_old.java

public InstanceData_old(String id, int gamma, String provider, List<JobClass_old> classes,
        Map<String, List<TypeVM>> types, Map<TypeVMJobClassKey, Profile_old> profiles) {
    this.id = id;
    this.setGamma(gamma);
    this.setProvider(provider);
    this.scenario = Optional.of(Scenarios.PublicPeakWorkload);
    lstClass = classes;/*from  w w w.ja  v  a2  s  .  c  o  m*/
    mapTypeVMs = Optional.of(types);
    mapProfiles = profiles;
}

From source file:ninja.eivind.hotsreplayuploader.versions.ReleaseManager.java

public Optional<GitHubRelease> getNewerVersionIfAny() {
    final ReleaseComparator releaseComparator = new ReleaseComparator();
    try {/*from w w w  .  j ava 2s .c  o m*/
        final List<GitHubRelease> latest = getLatest();
        latest.sort(releaseComparator);

        final GitHubRelease latestRelease = latest.get(0);
        final int compare = releaseComparator.compare(currentRelease, latestRelease);
        if (!latest.isEmpty() && compare > 0) {
            LOG.info("Newer  release is: " + latestRelease);
            return Optional.of(latestRelease);
        } else {
            LOG.info(currentRelease + " is the newest version.");
        }
    } catch (IOException e) {
        LOG.error("Unable to get latest versions", e);
    }
    return Optional.empty();
}

From source file:org.openmhealth.shim.misfit.mapper.MisfitPhysicalActivityDataPointMapper.java

@Override
public Optional<DataPoint<PhysicalActivity>> asDataPoint(JsonNode sessionNode) {

    checkNotNull(sessionNode);//from   w  ww  . j av  a2 s .co m

    String activityName = asRequiredString(sessionNode, "activityType");

    PhysicalActivity.Builder builder = new PhysicalActivity.Builder(activityName);

    Optional<Double> distance = asOptionalDouble(sessionNode, "distance");

    if (distance.isPresent()) {
        builder.setDistance(new LengthUnitValue(MILE, distance.get()));
    }

    Optional<OffsetDateTime> startDateTime = asOptionalOffsetDateTime(sessionNode, "startTime");
    Optional<Double> durationInSec = asOptionalDouble(sessionNode, "duration");

    if (startDateTime.isPresent() && durationInSec.isPresent()) {
        DurationUnitValue durationUnitValue = new DurationUnitValue(SECOND, durationInSec.get());
        builder.setEffectiveTimeFrame(ofStartDateTimeAndDuration(startDateTime.get(), durationUnitValue));
    }

    asOptionalBigDecimal(sessionNode, "calories")
            .ifPresent(calories -> builder.setCaloriesBurned(new KcalUnitValue(KILOCALORIE, 96.8)));

    PhysicalActivity measure = builder.build();

    Optional<String> externalId = asOptionalString(sessionNode, "id");

    return Optional.of(newDataPoint(measure, RESOURCE_API_SOURCE_NAME, externalId.orElse(null), null));
}