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.WechatMessageHelper.java

@Override
public Optional<WecahtMessageTemplateRespObj> sendTemplate(WechatMessageTemplate template) {
    try {//from   w w  w.j av  a 2s.co  m
        Optional<WechatAccessToken> token = wechatHelper.getAccessToken();
        if (token.isPresent()) {
            WechatAccessToken accessToken = token.get();
            HttpPost httpPost = new HttpPost();
            System.out.println(new Gson().toJson(template));
            httpPost.setEntity(new StringEntity(new Gson().toJson(template), "utf-8"));
            httpPost.setURI(new URI(MessageFormat.format(WechatConstants.MESSAGE_TEMPLATE_SEND_URL,
                    accessToken.getAccess_token())));
            return new WechatHttpClient().send(httpPost, WecahtMessageTemplateRespObj.class);
        }
    } catch (URISyntaxException e) {
        log.info(e.getMessage());
    }
    return Optional.empty();
}

From source file:org.apache.ambari.view.web.controller.PackageController.java

@GetMapping
public PackageWrapper.SearchResponse getAll(@RequestParam("like") Optional<String> like) {
    if (!like.isPresent()) {
        log.error("Cannot search packages without a search string");
        throw new RuntimeException("No packages found");
    }/*from   ww w.  ja va  2s.com*/

    String query = "%" + like.get() + "%";
    List<Package> packages = service.getPackagesLike(query);
    return new PackageWrapper.SearchResponse(packages);
}

From source file:org.springsource.restbucks.payment.CreditCardRepositoryIntegrationTest.java

@Test
public void createsCreditCard() {

    CreditCard creditCard = repository.save(createCreditCard());

    Optional<CreditCard> result = repository.findByNumber(creditCard.getNumber());

    assertThat(result.isPresent(), is(true));
    assertThat(result.get(), is(creditCard));
}

From source file:org.openmhealth.shim.fitbit.mapper.FitbitBodyMassIndexDataPointMapper.java

@Override
protected Optional<DataPoint<BodyMassIndex>> asDataPoint(JsonNode node) {

    TypedUnitValue<BodyMassIndexUnit> bmiValue = new TypedUnitValue<>(KILOGRAMS_PER_SQUARE_METER,
            asRequiredDouble(node, "bmi"));

    BodyMassIndex.Builder builder = new BodyMassIndex.Builder(bmiValue);

    Optional<OffsetDateTime> dateTime = combineDateTimeAndTimezone(node);

    if (dateTime.isPresent()) {
        builder.setEffectiveTimeFrame(dateTime.get());
    }/* w w w .j  av  a  2 s  . c om*/

    Optional<Long> externalId = asOptionalLong(node, "logId");

    return Optional.of(newDataPoint(builder.build(), externalId.orElse(null)));
}

From source file:mc.feature.ast.ASTTest.java

@Test
public void testFileNameInSourcePosition() {
    String grammarToTest = "src/test/resources/mc/grammar/SimpleGrammarWithConcept.mc4";

    Path model = Paths.get(new File(grammarToTest).getAbsolutePath());

    MontiCoreScript mc = new MontiCoreScript();
    Optional<ASTMCGrammar> ast = mc.parseGrammar(model);
    assertTrue(ast.isPresent());
    ASTMCGrammar clonedAst = ast.get().deepClone();
    assertTrue(clonedAst.get_SourcePositionStart().getFileName().isPresent());
    assertEquals("SimpleGrammarWithConcept.mc4",
            FilenameUtils.getName(clonedAst.get_SourcePositionStart().getFileName().get()));
}

From source file:pitayaa.nail.msg.core.license.controller.LicenseController.java

@RequestMapping(value = "licenses/{ID}", method = RequestMethod.DELETE)
public @ResponseBody ResponseEntity<?> deleteLicense(@PathVariable("ID") UUID uid) throws Exception {

    // Find license
    Optional<License> optionalLicense = licenseService.findOne(uid);
    if (!optionalLicense.isPresent()) {
        return new ResponseEntity<>(HttpStatus.NOT_FOUND);
    }/* w ww  .  ja  va  2 s.  c o m*/
    // Delete license
    boolean isDelete = licenseService.deleteLicense(uid);

    // Get status
    HttpStatus status = (isDelete) ? HttpStatus.NO_CONTENT : HttpStatus.EXPECTATION_FAILED;

    // Return
    return new ResponseEntity<>(status);
}

From source file:sample.jsp.SampleJspApplication.java

@Bean
public JettyEmbeddedServletContainerFactory jettyEmbeddedServletContainerFactory() {
    clearJspSystemUris();/*from   w  w w . ja  v  a 2 s.  co m*/
    JettyEmbeddedServletContainerFactory jettyEmbeddedServletContainerFactory = new JettyEmbeddedServletContainerFactory() {
        @Override
        protected void postProcessWebAppContext(WebAppContext webAppContext) {
            super.postProcessWebAppContext(webAppContext);
            Optional<String> jarFile = jarFile();
            if (jarFile.isPresent()) {
                File tempDir = Files.createTempDir();
                webAppContext.setTempDirectory(tempDir);
                webAppContext.setContextPath("/");
                webAppContext.setPersistTempDirectory(true);
                webAppContext.setConfigurations(
                        ObjectArrays.concat(webAppContext.getConfigurations(), new WebInfConfiguration()));
                new Unzipper().unzip(jarFile.get(), tempDir, jspZipEntry());
                logger.info("JSP files extracted to directory: " + tempDir.getAbsolutePath());
                webAppContext.setWar(tempDir.getPath());
            } else {
                webAppContext.setWar(this.getClass().getResource("/").getPath());
            }
        }

    };
    jettyEmbeddedServletContainerFactory.addServerCustomizers(new JettyServerCustomizer() {
        @Override
        public void customize(Server server) {
            org.eclipse.jetty.webapp.Configuration.ClassList classlist = org.eclipse.jetty.webapp.Configuration.ClassList
                    .setServerDefault(server);
            classlist.addBefore("org.eclipse.jetty.webapp.JettyWebXmlConfiguration",
                    "org.eclipse.jetty.annotations.AnnotationConfiguration");

        }
    });
    return jettyEmbeddedServletContainerFactory;
}

From source file:keywhiz.auth.cookie.CookieAuthenticator.java

@Override
public Optional<User> authenticate(Cookie cookie) {
    User user = null;/*from w  w w.  j  a v  a  2  s .  c  o  m*/

    if (cookie != null) {
        Optional<UserCookieData> cookieData = getUserCookieData(cookie);
        if (cookieData.isPresent()) {
            user = cookieData.get().getUser();
        }
    }

    return Optional.ofNullable(user);
}

From source file:com.openthinks.webscheduler.controller.ProfileController.java

@Mapping("/index")
public String index(WebAttributers was) {

    Optional<User> currentUser = getCurrentUser(was);
    if (!currentUser.isPresent()) {
        was.addError(StaticDict.PAGE_ATTRIBUTE_ERROR_1, "Session timeout, please login again.",
                WebScope.REQUEST);/*from  w  ww .  j ava  2  s . co  m*/
        return StaticUtils.errorPage(was, PageMap.build());
    }
    was.storeRequest(StaticDict.PAGE_ATTRIBUTE_USER, currentUser.get());
    return "WEB-INF/jsp/profile.jsp";
}

From source file:bg.vitkinov.edu.services.JokeCategoryService.java

@RequestMapping(value = "/search/{name}", method = RequestMethod.GET)
public ResponseEntity<?> getCategoryByName(@PathVariable String name) {
    Optional<Category> category = repository.findByName(name);
    return category.isPresent() ? new ResponseEntity<>(category.get(), HttpStatus.OK)
            : new ResponseEntity<>(HttpStatus.NOT_FOUND);
}