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.macrossx.wechat.impl.WechatMenuHelper.java

@Override
public Optional<WechatMenu> getMenu() {
    try {// www.j a  v a2  s . c o  m
        Optional<WechatAccessToken> token = wechatHelper.getAccessToken();
        if (token.isPresent()) {
            WechatAccessToken accessToken = token.get();

            HttpGet httpGet = new HttpGet();
            httpGet.setURI(
                    new URI(MessageFormat.format(WechatConstants.MENU_GET_URL, accessToken.getAccess_token())));
            return new WechatHttpClient().send(httpGet, WechatMenu.class);
        }
    } catch (URISyntaxException e) {
        log.info(e.getMessage());
    }
    return Optional.empty();
}

From source file:com.epam.training.service.impl.DefaultSergiiService.java

@Override
public void createLogo(final String logoCode) {
    final Optional<CatalogUnawareMediaModel> existingLogo = findExistingLogo(logoCode);

    final CatalogUnawareMediaModel media = existingLogo.isPresent() ? existingLogo.get()
            : modelService.create(CatalogUnawareMediaModel.class);
    media.setCode(logoCode);/*from  w  w  w .j a  v  a 2  s .c o m*/
    media.setRealFileName("sap-hybris-platform.png");
    modelService.save(media);

    mediaService.setStreamForMedia(media, getImageStream());
}

From source file:com.javaeeeee.repositories.UsersRepositoryTest.java

/**
 * Method tests happy path./*from   w w  w.  j a  v a2  s  .c om*/
 */
@Test
public void findByUsernameAndPasswordShouldReturnUser() {
    final String name = "Phil";
    final String password = "1";
    entityManager.persist(new User(name, password));
    Optional<User> optional = usersRepository.findByUsernameAndPassword(name, password);

    Assert.assertTrue(optional.isPresent());
}

From source file:com.epam.catgenome.controller.vo.externaldb.NCBIVariationVO.java

@JsonProperty(value = "gene_summary")
public String getGene() {
    List<NCBIShortVarVO.NCBIGeneSummaryVO> genes = ncbiShortVar.getGenes();
    Optional<NCBIShortVarVO.NCBIGeneSummaryVO> first = genes.stream().findFirst();
    return first.isPresent() ? String.format("%s (%s)", first.get().getName(), first.get().getGeneId()) : null;
}

From source file:org.openwms.tms.routing.ActivitiMatrix.java

private Optional<Action> findByLocationGroup(Route route, LocationGroupVO locationGroup) {
    Optional<Action> cp = repository.findByRouteAndLocationGroupName(route, locationGroup.getName());
    if (!cp.isPresent() && locationGroup.hasLink("_parent")) {
        cp = findByLocationGroup(route, findLocationGroup(locationGroup.getLink("_parent")));
    }/*w ww  .  j a  v a 2 s  .  c o m*/
    return cp;
}

From source file:com.blackducksoftware.integration.hub.detect.detector.gradle.GradleInspectorManager.java

public String getGradleInspector() throws DetectorException {
    if (!hasResolvedInspector) {
        hasResolvedInspector = true;/*from w ww. jav  a 2  s. c  o m*/
        try {
            final File airGapPath = deriveGradleAirGapDir();
            final File generatedGradleScriptFile = directoryManager.getSharedFile(GRADLE_DIR_NAME,
                    GENERATED_GRADLE_SCRIPT_NAME);
            GradleScriptCreator gradleScriptCreator = new GradleScriptCreator(detectConfiguration,
                    configuration);
            if (airGapPath == null) {
                Optional<String> version = findVersion();
                if (version.isPresent()) {
                    logger.info("Resolved the gradle inspector version: " + version.get());
                    generatedGradleScriptPath = gradleScriptCreator
                            .generateOnlineScript(generatedGradleScriptFile, version.get());
                } else {
                    throw new DetectorException(
                            "Unable to find the gradle inspector version from artifactory.");
                }
            } else {
                generatedGradleScriptPath = gradleScriptCreator.generateAirGapScript(generatedGradleScriptFile,
                        airGapPath.getCanonicalPath());
            }
        } catch (final Exception e) {
            throw new DetectorException(e);
        }
        if (generatedGradleScriptPath == null) {
            throw new DetectorException("Unable to initialize the gradle inspector.");
        } else {
            logger.trace("Derived generated gradle script path: " + generatedGradleScriptPath);
        }
    } else {
        logger.debug("Already attempted to resolve the gradle inspector script, will not attempt again.");
    }
    if (StringUtils.isBlank(generatedGradleScriptPath)) {
        throw new DetectorException("Unable to find or create the gradle inspector script.");
    }
    return generatedGradleScriptPath;
}

From source file:com.streamsets.datacollector.classpath.ClasspathValidator.java

public ClasspathValidatorResult validate(Properties explicitWhitelist) {
    LOG.trace("Validating classpath for {}", name);
    ClasspathValidatorResult.Builder resultBuilder = new ClasspathValidatorResult.Builder(name);
    // Name of dependency -> Version(s) of the dependency -> Individual dependencies
    Map<String, Map<String, List<Dependency>>> dependecies = new HashMap<>();

    // (Re-)Parse all URLs (all dependencies)
    for (URL url : urls) {
        Optional<Dependency> parsed = DependencyParser.parseURL(url);

        if (!parsed.isPresent()) {
            resultBuilder.addUnparseablePath(url.toString());
            continue;
        }/*  w  w  w .j a  va  2s.  c  om*/

        Dependency dependency = parsed.get();
        LOG.trace("Parsed {} to dependency {} on version {}", dependency.getSourceName(), dependency.getName(),
                dependency.getVersion());

        dependecies.computeIfAbsent(dependency.getName(), (i) -> new HashMap<>())
                .computeIfAbsent(dependency.getVersion(), (i) -> new LinkedList<>()).add(dependency);
    }

    // And finally validate each dependency have allowed list of versions
    for (Map.Entry<String, Map<String, List<Dependency>>> entry : dependecies.entrySet()) {
        // Ideal the inner map with versions should have only one item, otherwise that is most likely a problem
        if (entry.getValue().size() > 1) {
            if (CollisionWhitelist.isWhitelisted(entry.getKey(), explicitWhitelist, entry.getValue())) {
                LOG.trace("Whitelisted dependency {} on versions {}", entry.getKey(),
                        StringUtils.join(entry.getValue().keySet(), ","));
                continue;
            }

            // No exceptions were applied, hence this is truly a collision
            resultBuilder.addVersionCollision(entry.getKey(), entry.getValue());
        }
    }

    return resultBuilder.build();
}

From source file:ac.simons.tweetarchive.tweets.TweetStorageService.java

@Transactional
public TweetEntity store(final Status status, final String rawContent) {
    final Optional<TweetEntity> existingTweet = this.tweetRepository.findOne(status.getId());
    if (existingTweet.isPresent()) {
        final TweetEntity rv = existingTweet.get();
        log.warn("Tweet with status {} already existed...", rv.getId());
        return rv;
    }/*from   w  ww .ja v  a2  s  .c  o  m*/

    final TweetEntity tweet = new TweetEntity(status.getId(), status.getUser().getId(),
            status.getUser().getScreenName(), status.getCreatedAt().toInstant().atZone(ZoneId.of("UTC")),
            extractContent(status), extractSource(status), rawContent);
    tweet.setCountryCode(Optional.ofNullable(status.getPlace()).map(Place::getCountryCode).orElse(null));
    if (status.getInReplyToStatusId() != -1L && status.getInReplyToUserId() != -1L
            && status.getInReplyToScreenName() != null) {
        tweet.setInReplyTo(new InReplyTo(status.getInReplyToStatusId(), status.getInReplyToScreenName(),
                status.getInReplyToUserId()));
    }
    tweet.setLang(status.getLang());
    tweet.setLocation(Optional.ofNullable(status.getGeoLocation())
            .map(g -> new TweetEntity.Location(g.getLatitude(), g.getLongitude())).orElse(null));
    // TODO Handle quoted tweets
    return this.tweetRepository.save(tweet);
}

From source file:se.uu.it.cs.recsys.semantic.ComputingDomainReasonerTest.java

/**
 * Test of getPrefLabel method, of class ComputingDomainReasoner.
 *//*from   www. j a va  2s  .  c om*/
@Test
public void testGetPrefLabel_No_Matching() throws Exception {

    final String domainId = "--10003350--";
    final Optional<String> result = this.reasoner.getPrefLabel(domainId);
    assertTrue(!result.isPresent());

}

From source file:com.blackducksoftware.integration.hub.detect.detector.gradle.GradleReportParserTest.java

private DetectCodeLocation build(final String resource) throws IOException {
    final File file = new File(resource);
    final GradleReportParser gradleReportParser = new GradleReportParser(new ExternalIdFactory());
    final Optional<DetectCodeLocation> result = gradleReportParser.parseDependencies(file);
    if (result.isPresent()) {
        return result.get();
    } else {//from  w  w  w.  j ava2 s . c  om
        return null;
    }
}