List of usage examples for java.util Optional filter
public Optional<T> filter(Predicate<? super T> predicate)
From source file:com.ikanow.aleph2.analytics.services.DeduplicationService.java
/** Compares the old and new records' timestamps (if either doesn't exist then assume we're leaving) * (so that if the time isn't present then doesn't hammer the DB) * @param timestamp_field//from w w w . j a v a2s. com * @param new_record * @param old_record * @return */ protected static boolean newRecordUpdatesOld(String timestamp_field, final JsonNode new_record, final JsonNode old_record) { final Optional<JsonNode> old_timestamp = JsonUtils.getProperty(timestamp_field, old_record); final Optional<JsonNode> new_timestamp = JsonUtils.getProperty(timestamp_field, new_record); final Optional<Tuple2<Long, Long>> maybe_old_new = old_timestamp .flatMap(old_ts -> getTimestampFromJsonNode(old_ts)) .flatMap(old_ts -> new_timestamp.flatMap(new_ts -> getTimestampFromJsonNode(new_ts)) .map(new_ts -> Tuples._2T(old_ts, new_ts))); return maybe_old_new.filter(old_new -> old_new._2() > old_new._1()).isPresent(); }
From source file:com.rockagen.gnext.service.spring.security.extension.ExAuthenticationProvider.java
/** * Create a new {@link org.springframework.security.core.userdetails.UserDetails} by uid * * @param uid uid/*from ww w .j ava 2 s. co m*/ * @param credentials Credentials(always was password) * @return {@link org.springframework.security.core.userdetails.UserDetails} * @throws org.springframework.security.authentication.BadCredentialsException if credentials invalid */ private UserDetails loadUser(String uid, String credentials) { // Not empty if (CommUtil.isBlank(uid) || CommUtil.isBlank(credentials)) { throw new BadCredentialsException(messages .getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials")); } // Load user Optional<AuthUser> u = authUserServ.load(uid); if (u.filter(x -> x.enabled()).isPresent()) { AuthUser user = u.get(); // Check credentials checkCredentials(user.getPassword(), credentials, user.getSalt()); // After authenticated handler afterAuthenticatedHandler(user); List<GrantedAuthority> authorities = new LinkedList<>(); Set<AuthGroup> groups = user.getGroups(); if (groups != null && groups.size() > 0) { groups.forEach(x -> x.getRoles() .forEach(y -> authorities.add(new SimpleGrantedAuthority(y.getName().trim())))); } return new User(user.getUid(), user.getPassword(), true, true, true, true, authorities); } else { throw new UsernameNotFoundException( messages.getMessage("", new Object[] { uid }, "User {0} has no GrantedAuthority")); } }
From source file:com.rockagen.gnext.service.spring.security.extension.ExTokenAuthentication.java
/** * <p>// w ww. ja v a 2s .c o m * <pre> * token = base64(expirationTime + ":" + uid) + "." + base64(hmac(expirationTime + ":" + uid + ":" + password)) * * expirationTime: The date and time when the token expires,expressed in milliseconds * uid: As identifiable to the UserDetailsService * password: That matches the one in the retrieved UserDetails * </pre> * </p> * * @param uid uid * @return new token,null if uid not exist or disabled */ public String newToken(String uid) { Optional<AuthUser> u = authUserServ.load(uid); if (u.filter(AuthUser::enabled).isPresent()) { String passwd = u.get().getPassword(); long expirationTime = System.currentTimeMillis() + expiredTime; String partA = expirationTime + ":" + uid; String partB = hmac(uid, String.valueOf(expirationTime), passwd); String token = CommUtil.encodeBase64(partA) + "." + CommUtil.encodeBase64(partB); return token; } return null; }
From source file:com.rockagen.gnext.service.spring.security.extension.ExTokenAuthentication.java
/** * Get {@link org.springframework.security.core.userdetails.UserDetails} from token * * @param token token/*from ww w .j a v a2 s .co m*/ * @return {@link org.springframework.security.core.userdetails.UserDetails} if token authenticated,otherwise return null */ public UserDetails getUserDetailsFromToken(String token) { if (authenticated(token)) { // Load user Optional<AuthUser> user = authUserServ.load(Token.getUidFromToken(token)); if (user.filter(AuthUser::enabled).isPresent()) { List<GrantedAuthority> authorities = new LinkedList<>(); Set<AuthGroup> groups = user.get().getGroups(); if (groups != null && groups.size() > 0) { groups.forEach(x -> x.getRoles() .forEach(y -> authorities.add(new SimpleGrantedAuthority(y.getName().trim())))); } return new User(user.get().getUid(), "***", authorities); } } return null; }
From source file:com.rockagen.gnext.service.spring.security.extension.ExTokenAuthentication.java
/** * Validate token//from w w w.j a v a 2 s .c o m * * @param token token * @see #newToken(String) * @return true if authenticated */ public boolean authenticated(String token) { if (token == null) { return false; } String[] parts = Token.parsePartAB(token); if (parts != null) { String partA = CommUtil.decodeBase64(parts[0]); String partB = CommUtil.decodeBase64(parts[1]); String[] userDetails = Token.getUidAndExpirationTime(partA); if (userDetails != null) { String uid = userDetails[0]; String expireTime = userDetails[1]; long now = System.currentTimeMillis(); try { // Not expired if (Long.parseLong(expireTime) > now) { Optional<AuthUser> u = authUserServ.load(uid); if (u.filter(AuthUser::enabled).isPresent()) { String passwd = u.get().getPassword(); String vhmac = hmac(uid, expireTime, passwd); return partB.equals(vhmac); } } } catch (Exception e) { log.error("Authenticate failed: because {}", e.getMessage()); } } } return false; }
From source file:alfio.controller.form.PaymentForm.java
public void validate(BindingResult bindingResult, TotalPrice reservationCost, Event event, List<TicketFieldConfiguration> fieldConf) { List<PaymentProxy> allowedPaymentMethods = event.getAllowedPaymentProxies(); Optional<PaymentProxy> paymentProxyOptional = Optional.ofNullable(paymentMethod); PaymentProxy paymentProxy = paymentProxyOptional.filter(allowedPaymentMethods::contains) .orElse(PaymentProxy.STRIPE); boolean priceGreaterThanZero = reservationCost.getPriceWithVAT() > 0; boolean multiplePaymentMethods = allowedPaymentMethods.size() > 1; if (multiplePaymentMethods && priceGreaterThanZero && !paymentProxyOptional.isPresent()) { bindingResult.reject(ErrorsCode.STEP_2_MISSING_PAYMENT_METHOD); } else if (priceGreaterThanZero && (paymentProxy == PaymentProxy.STRIPE && StringUtils.isBlank(stripeToken))) { bindingResult.reject(ErrorsCode.STEP_2_MISSING_STRIPE_TOKEN); }/*from ww w . j av a2 s .c o m*/ if (Objects.isNull(termAndConditionsAccepted) || !termAndConditionsAccepted) { bindingResult.reject(ErrorsCode.STEP_2_TERMS_NOT_ACCEPTED); } email = StringUtils.trim(email); fullName = StringUtils.trim(fullName); firstName = StringUtils.trim(firstName); lastName = StringUtils.trim(lastName); billingAddress = StringUtils.trim(billingAddress); ValidationUtils.rejectIfEmptyOrWhitespace(bindingResult, "email", ErrorsCode.STEP_2_EMPTY_EMAIL); rejectIfOverLength(bindingResult, "email", ErrorsCode.STEP_2_MAX_LENGTH_EMAIL, email, 255); if (event.mustUseFirstAndLastName()) { ValidationUtils.rejectIfEmptyOrWhitespace(bindingResult, "firstName", ErrorsCode.STEP_2_EMPTY_FIRSTNAME); rejectIfOverLength(bindingResult, "firstName", ErrorsCode.STEP_2_MAX_LENGTH_FIRSTNAME, fullName, 255); ValidationUtils.rejectIfEmptyOrWhitespace(bindingResult, "lastName", ErrorsCode.STEP_2_EMPTY_LASTNAME); rejectIfOverLength(bindingResult, "lastName", ErrorsCode.STEP_2_MAX_LENGTH_LASTNAME, fullName, 255); } else { ValidationUtils.rejectIfEmptyOrWhitespace(bindingResult, "fullName", ErrorsCode.STEP_2_EMPTY_FULLNAME); rejectIfOverLength(bindingResult, "fullName", ErrorsCode.STEP_2_MAX_LENGTH_FULLNAME, fullName, 255); } rejectIfOverLength(bindingResult, "billingAddress", ErrorsCode.STEP_2_MAX_LENGTH_BILLING_ADDRESS, billingAddress, 450); if (email != null && !email.contains("@") && !bindingResult.hasFieldErrors("email")) { bindingResult.rejectValue("email", ErrorsCode.STEP_2_INVALID_EMAIL); } if (hasPaypalTokens() && !PaypalManager.isValidHMAC(new CustomerName(fullName, firstName, lastName, event), email, billingAddress, hmac, event)) { bindingResult.reject(ErrorsCode.STEP_2_INVALID_HMAC); } if (!postponeAssignment) { boolean success = Optional.ofNullable(tickets).filter(m -> !m.isEmpty()).map(m -> m.entrySet().stream() .map(e -> Validator.validateTicketAssignment(e.getValue(), fieldConf, Optional.empty(), event))) .filter(s -> s.allMatch(ValidationResult::isSuccess)).isPresent(); if (!success) { bindingResult.reject(ErrorsCode.STEP_2_MISSING_ATTENDEE_DATA); } } }
From source file:com.rockagen.gnext.service.spring.security.extension.ExAuthenticationHandler.java
/** * Failure register//from ww w .j a va2 s . co m * * @param uid uid * @param request request */ private void failureRegister(String uid, HttpServletRequest request) { String currentIp = new ExWebAuthenticationDetails(request).getRemoteAddress(); Optional<AuthUser> u = authUserServ.load(uid); if (u.filter(AuthUser::enabled).isPresent()) { AuthUser user = u.get(); Date date = new Date(); long now = date.getTime(); // Failed attempts count ++ Integer failedAttempts = user.getFailedAttempts(); if (failedAttempts == null) { failedAttempts = 0; } user.setFailedAttempts(++failedAttempts); user.setLastSignInAt(user.getCurrentSignInAt()); user.setCurrentSignInAt(date); user.setLastSignInIp(user.getCurrentSignInIp()); user.setCurrentSignInIp(currentIp); Integer signCount = user.getSignInCount(); if (signCount == null) { signCount = 0; } user.setSignInCount(++signCount); // Referer String referer = request.getHeader(userReferer); user.setLastUserReferer(getReferer(referer)); if (user.getLastSignInAt() != null) { long lastTime = user.getLastSignInAt().getTime(); // auto lock if (user.getFailedAttempts() >= maxFailedAttempts && (now - lastTime) <= lockedTime) { // Locked user user.setLockedAt(date); user.setEnabled(0); } } authUserServ.add(user); // locked? if (user.getEnabled() < 1) { throw new DisabledException(messages.getMessage("AccountStatusUserDetailsChecker.locked")); } int onlyCount = maxFailedAttempts - user.getFailedAttempts(); throw new BadCredentialsException( messages.getMessage("AccountStatusUserDetailsChecker.onlyCount", new Object[] { onlyCount })); } else { throw new BadCredentialsException(messages .getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials")); } }
From source file:com.linagora.james.mailets.GuessClassificationMailet.java
private Optional<Integer> parseTimeout() throws MessagingException { try {// w ww .ja v a 2 s. c o m Optional<Integer> result = Optional.ofNullable(getInitParameter(TIMEOUT_IN_MS)).map(Integer::valueOf); if (result.filter(value -> value < 1).isPresent()) { throw new MessagingException("Non strictly positive timeout for " + TIMEOUT_IN_MS + ". Got " + getInitParameter(TIMEOUT_IN_MS)); } return result; } catch (NumberFormatException e) { throw new MessagingException("Expecting " + TIMEOUT_IN_MS + " to be a strictly positive integer. Got " + getInitParameter(TIMEOUT_IN_MS)); } }
From source file:alfio.manager.user.UserManager.java
public ValidationResult validateNewPassword(String username, String oldPassword, String newPassword, String newPasswordConfirm) { return userRepository.findByUsername(username).map(u -> { List<ValidationResult.ErrorDescriptor> errors = new ArrayList<>(); Optional<String> password = userRepository.findPasswordByUsername(username); if (!password.filter(p -> passwordEncoder.matches(oldPassword, p)).isPresent()) { errors.add(new ValidationResult.ErrorDescriptor("alfio.old-password-invalid", "wrong password")); }/* ww w . j av a 2s. c o m*/ if (!PasswordGenerator.isValid(newPassword)) { errors.add(new ValidationResult.ErrorDescriptor("alfio.new-password-invalid", "new password is not strong enough")); } if (!StringUtils.equals(newPassword, newPasswordConfirm)) { errors.add(new ValidationResult.ErrorDescriptor("alfio.new-password-does-not-match", "new password has not been confirmed")); } return ValidationResult.of(errors); }).orElseGet(ValidationResult::failed); }
From source file:it.polimi.diceH2020.SPACE4CloudWS.core.CoarseGrainedOptimizer.java
private List<Triple<Integer, Optional<Double>, Boolean>> alterUntilBreakPoint(SolutionPerJob solPerJob, Function<Integer, Integer> updateFunction, Function<Double, Double> fromResult, Predicate<Double> feasibilityCheck, Predicate<Double> stoppingCondition, BiPredicate<Double, Double> incrementCheck, Predicate<Integer> vmCheck) { List<Triple<Integer, Optional<Double>, Boolean>> lst = new ArrayList<>(); Optional<Double> previous = Optional.empty(); boolean shouldKeepGoing = true; while (shouldKeepGoing) { Pair<Optional<Double>, Long> simulatorResult = dataProcessor.simulateClass(solPerJob); Optional<Double> maybeResult = simulatorResult.getLeft(); Optional<Double> interestingMetric = maybeResult.map(fromResult); Integer nVM = solPerJob.getNumberVM(); lst.add(new ImmutableTriple<>(nVM, maybeResult, interestingMetric.filter(feasibilityCheck).isPresent())); boolean terminationCriterion = !checkState(); logger.trace("terminationCriterion is " + terminationCriterion + " after checkState()"); terminationCriterion |= vmCheck.test(nVM); logger.trace("terminationCriterion is " + terminationCriterion + " after vmCheck.test()"); terminationCriterion |= interestingMetric.filter(stoppingCondition).isPresent(); logger.trace("terminationCriterion is " + terminationCriterion + " after filter"); if (previous.isPresent() && interestingMetric.isPresent() && (dataService.getScenario().getTechnology() != Technology.STORM || interestingMetric.get() == 0.0)) { terminationCriterion |= incrementCheck.test(previous.get(), interestingMetric.get()); }//from ww w . jav a 2s. c o m shouldKeepGoing = !terminationCriterion; previous = interestingMetric; if (dataService.getScenario().getTechnology() == Technology.STORM) { logger.trace(interestingMetric.orElse(Double.NaN) + " vs. " + solPerJob.getJob().getU()); } else { logger.trace(interestingMetric.orElse(Double.NaN) + " vs. " + solPerJob.getJob().getD()); } if (shouldKeepGoing) { String message = String.format("class %s -> num VM: %d, simulator result: %f, metric: %f", solPerJob.getId(), nVM, maybeResult.orElse(Double.NaN), interestingMetric.orElse(Double.NaN)); logger.info(message); solPerJob.updateNumberVM(updateFunction.apply(nVM)); } } return lst; }