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.javaeeeee.components.JpaAuthenticationProvider.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    Optional<User> optional = usersRepository.findByUsernameAndPassword(authentication.getName(),
            authentication.getCredentials().toString());
    if (optional.isPresent()) {
        return new UsernamePasswordAuthenticationToken(authentication.getPrincipal(),
                authentication.getCredentials(), authentication.getAuthorities());

    } else {/*from   w  ww  .  ja  v a  2s. c o  m*/
        throw new AuthenticationCredentialsNotFoundException("Wrong credentials.");
    }
}

From source file:org.homiefund.api.service.impl.InviteServiceImpl.java

@Override
@Transactional/*from w  w w  .j a v a 2 s. c  o m*/
public Long inviteRegistered(UserDTO user, String inviteToken) throws IllegalArgumentException {
    Optional<Invitation> optionalInvite = invitationDAO.getByHash(inviteToken);

    if (!optionalInvite.isPresent()) {
        throw new IllegalArgumentException("Attempting to accept wrong invitation.");
    } else {
        Invitation invite = optionalInvite.get();
        if (!invite.getValid()) {
            throw new IllegalArgumentException("Attempting to accept invite which is already invalid.");
        } else {
            if (!user.getEmail().equals(invite.getEmail())) {
                throw new AccessDeniedException("Your email is not matching email in invitation");
            } else {
                User userDB = userDAO.getById(user.getId());
                Home home = invite.getHome();
                home.getMembers().add(userDB);

                homeDAO.update(home);
                invite.setValid(false);

                invitationDAO.update(invite);
                applicationEventPublisher.publishEvent(new UserJoinsHome(this,
                        mapper.map(userDB, UserDTO.class), mapper.map(home, HomeDTO.class)));

                return home.getId();
            }
        }
    }
}

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

<T> Optional<T> get(String path, Class<T> clazz, Optional<Map<String, String>> params) {
    try {/*from  w  w  w.  jav  a 2s  . com*/
        WebTarget resource = rootContext.path(path);
        if (params.isPresent()) {
            for (Map.Entry<String, String> entry : params.get().entrySet()) {
                resource = resource.queryParam(entry.getKey(), entry.getValue());
            }
        }
        return Optional.of(resource.request(MediaType.APPLICATION_JSON_TYPE).get(clazz));
    } catch (ProcessingException | NotFoundException e) {
        LOGGER.error("Failed to get the resource {} and convert it to {}", path, clazz.getName());
    }
    return empty();
}

From source file:com.openshift.internal.restclient.model.image.ImageStreamImport.java

@Override
public String getImageJsonFor(String tag) {
    ModelNode images = get(STATUS_IMAGES);
    if (images.isDefined() && StringUtils.isNotBlank(tag)) {
        Optional<ModelNode> node = images.asList().stream().filter(n -> tag.equals(asString(n, TAG)))
                .findFirst();/*from   www  . j av a2  s.c  om*/
        if (node.isPresent()) {
            return node.get().toJSONString(true);
        }
    }
    return null;
}

From source file:com.uber.hoodie.utilities.sources.HiveIncrPullSource.java

@Override
public Pair<Optional<JavaRDD<GenericRecord>>, String> fetchNewData(Optional<String> lastCheckpointStr,
        long maxInputBytes) {
    try {//from   ww w  .  ja  v a  2 s.c  om
        // find the source commit to pull
        Optional<String> commitToPull = findCommitToPull(lastCheckpointStr);

        if (!commitToPull.isPresent()) {
            return new ImmutablePair<>(Optional.empty(),
                    lastCheckpointStr.isPresent() ? lastCheckpointStr.get() : "");
        }

        // read the files out.
        List<FileStatus> commitDeltaFiles = Arrays
                .asList(fs.listStatus(new Path(incrPullRootPath, commitToPull.get())));
        String pathStr = commitDeltaFiles.stream().map(f -> f.getPath().toString())
                .collect(Collectors.joining(","));
        String schemaStr = schemaProvider.getSourceSchema().toString();
        final AvroConvertor avroConvertor = new AvroConvertor(schemaStr);
        return new ImmutablePair<>(
                Optional.of(DFSSource.fromFiles(dataFormat, avroConvertor, pathStr, sparkContext)),
                String.valueOf(commitToPull.get()));
    } catch (IOException ioe) {
        throw new HoodieIOException("Unable to read from source from checkpoint: " + lastCheckpointStr, ioe);
    }
}

From source file:com.epam.ta.reportportal.ws.resolver.ActiveUserWebArgumentResolver.java

@Override
public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer paramModelAndViewContainer,
        NativeWebRequest webRequest, WebDataBinderFactory paramWebDataBinderFactory) throws Exception {
    Authentication authentication = (Authentication) webRequest.getUserPrincipal();
    if (!authentication.getAuthorities().isEmpty()) {
        Optional<UserRole> userRole = UserRole
                .findByAuthority(authentication.getAuthorities().iterator().next().getAuthority());
        return userRole.isPresent() ? userRole.get() : WebArgumentResolver.UNRESOLVED;
    }/*from   w w  w.ja  v a  2 s .  c  om*/
    return WebArgumentResolver.UNRESOLVED;
}

From source file:io.kloudwork.controller.LoginController.java

public String postLogin(Request request, Response response) throws IOException, FileUploadException {
    boolean matched = false;

    Optional<User> userOptional = userRepository.findByUserName(request.queryParams("username"));

    if (userOptional.isPresent()) {
        String userPassword = userOptional.get().getPassword();
        matched = BCrypt.checkpw(request.queryParams("password"), userPassword);
    }//ww w  .  ja  v a 2s.  co m

    if (!matched) {
        throw Spark.halt(401);
    }

    User user = userOptional.get();

    final Session session = request.session();
    session.attribute("username", user.getUsername());
    session.attribute("csrf-token", generateCSRFToken(64));

    response.status(200);
    return "Logged in";
}

From source file:it.polimi.diceH2020.SPACE4CloudWS.core.DataProcessor.java

Pair<Optional<Double>, Long> simulateClass(@NonNull SolutionPerJob solPerJob) {
    Pair<Optional<Double>, Long> result = solverCache.evaluate(solPerJob);
    Optional<Double> optionalValue = result.getLeft();
    if (optionalValue.isPresent()) {
        String message = String.format(
                "%s-> A metric with %d VMs, %d Containers, and h = %d has been simulated: %f",
                solPerJob.getId(), solPerJob.getNumberVM(), solPerJob.getNumberContainers(),
                solPerJob.getNumberUsers(), optionalValue.get());
        logger.info(message);//from w w w.  j a  v a 2s .  c o m
    } else
        solverCache.invalidate(solPerJob);
    return result;
}

From source file:de.hybris.platform.chinesepspwechatpay.controllers.pages.WeChatPayController.java

@RequestMapping(value = "/pay/" + ORDER_CODE_PATH_VARIABLE_PATTERN)
public String process(@PathVariable final String orderCode,
        @RequestParam(value = "code", required = false) final String code, final HttpServletRequest request,
        final HttpServletResponse response, final Model model) throws CMSItemNotFoundException {
    try {/* w  w w.ja  va  2 s. co m*/
        if (StringUtils.isEmpty(code)) {
            new UserCodeRequestProcessor(weChatPayConfiguration, request, response).process();
            return null;
        }

        final Optional<OrderModel> optional = weChatPayOrderService.getOrderByCode(orderCode);
        if (!optional.isPresent()) {
            throw new WeChatPayException("Can't find order for code:" + orderCode);
        }

        final String openId = new OpenIdRequestProcessor(weChatPayConfiguration, weChatPayHttpClient, code)
                .process();
        final String baseUrl = siteBaseUrlResolutionService
                .getWebsiteUrlForSite(baseSiteService.getCurrentBaseSite(), true, "");
        final String prepayId = new UnifiedOrderRequestProcessor(weChatPayConfiguration, weChatPayHttpClient,
                openId, optional.get(), request.getRemoteAddr(), baseUrl).process();
        request.setAttribute("paymentData",
                new StartPaymentRequestProcessor(weChatPayConfiguration, prepayId).process());
        request.setAttribute("orderCode", orderCode);
        model.addAttribute("weChatPayTimeout", timeout);

        storeCmsPageInModel(model, getContentPageForLabelOrId(MULTI_CHECKOUT_SUMMARY_CMS_PAGE_LABEL));
        setUpMetaDataForContentPage(model, getContentPageForLabelOrId(MULTI_CHECKOUT_SUMMARY_CMS_PAGE_LABEL));

        return ControllerConstants.Views.Pages.Checkout.WeChatPayPage;
    } catch (final WeChatPayException e) {
        return REDIRECT_PREFIX + "/checkout/multi/summary/checkPaymentResult/" + orderCode;
    }
}

From source file:io.gravitee.gateway.env.GatewayConfigurationTest.java

@Test
public void shouldReturnEmptyTenant() {
    gatewayConfiguration.afterPropertiesSet();

    Optional<String> tenant = gatewayConfiguration.tenant();
    Assert.assertFalse(tenant.isPresent());
}