List of usage examples for java.util Optional ofNullable
@SuppressWarnings("unchecked") public static <T> Optional<T> ofNullable(T value)
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 w w w . ja v a 2 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:eu.interedition.collatex.tools.CollationPipe.java
public static void start(CommandLine commandLine) throws Exception { List<SimpleWitness> witnesses = null; Function<String, Stream<String>> tokenizer = SimplePatternTokenizer.BY_WS_OR_PUNCT; Function<String, String> normalizer = SimpleTokenNormalizers.LC_TRIM_WS; Comparator<Token> comparator = new EqualityTokenComparator(); CollationAlgorithm collationAlgorithm = null; boolean joined = true; final String[] witnessSpecs = commandLine.getArgs(); final InputStream[] inputStreams = new InputStream[witnessSpecs.length]; for (int wc = 0, wl = witnessSpecs.length; wc < wl; wc++) { try {// ww w.ja v a 2s . co m inputStreams[wc] = argumentToInputStream(witnessSpecs[wc]); } catch (MalformedURLException urlEx) { throw new ParseException("Invalid resource: " + witnessSpecs[wc]); } } if (inputStreams.length < 1) { throw new ParseException("No input resource(s) given"); } else if (inputStreams.length < 2) { try (InputStream inputStream = inputStreams[0]) { final SimpleCollation collation = JsonProcessor.read(inputStream); witnesses = collation.getWitnesses(); collationAlgorithm = collation.getAlgorithm(); joined = collation.isJoined(); } } final String script = commandLine.getOptionValue("s"); try { final PluginScript pluginScript = (script == null ? PluginScript.read("<internal>", new StringReader("")) : PluginScript.read(argumentToInput(script))); tokenizer = Optional.ofNullable(pluginScript.tokenizer()).orElse(tokenizer); normalizer = Optional.ofNullable(pluginScript.normalizer()).orElse(normalizer); comparator = Optional.ofNullable(pluginScript.comparator()).orElse(comparator); } catch (IOException e) { throw new ParseException("Failed to read script '" + script + "' - " + e.getMessage()); } switch (commandLine.getOptionValue("a", "").toLowerCase()) { case "needleman-wunsch": collationAlgorithm = CollationAlgorithmFactory.needlemanWunsch(comparator); break; case "medite": collationAlgorithm = CollationAlgorithmFactory.medite(comparator, SimpleToken.TOKEN_MATCH_EVALUATOR); break; case "gst": collationAlgorithm = CollationAlgorithmFactory.greedyStringTiling(comparator, 2); break; default: collationAlgorithm = Optional.ofNullable(collationAlgorithm) .orElse(CollationAlgorithmFactory.dekker(comparator)); break; } if (witnesses == null) { final Charset inputCharset = Charset .forName(commandLine.getOptionValue("ie", StandardCharsets.UTF_8.name())); final boolean xmlMode = commandLine.hasOption("xml"); final XPathExpression tokenXPath = XPathFactory.newInstance().newXPath() .compile(commandLine.getOptionValue("xp", "//text()")); witnesses = new ArrayList<>(inputStreams.length); for (int wc = 0, wl = inputStreams.length; wc < wl; wc++) { try (InputStream stream = inputStreams[wc]) { final String sigil = "w" + (wc + 1); if (!xmlMode) { final BufferedReader reader = new BufferedReader( new InputStreamReader(stream, inputCharset)); final StringWriter writer = new StringWriter(); final char[] buf = new char[1024]; while (reader.read(buf) != -1) { writer.write(buf); } witnesses.add(new SimpleWitness(sigil, writer.toString(), tokenizer, normalizer)); } else { final DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance() .newDocumentBuilder(); final Document document = documentBuilder.parse(stream); document.normalizeDocument(); final SimpleWitness witness = new SimpleWitness(sigil); final NodeList tokenNodes = (NodeList) tokenXPath.evaluate(document, XPathConstants.NODESET); final List<Token> tokens = new ArrayList<>(tokenNodes.getLength()); for (int nc = 0; nc < tokenNodes.getLength(); nc++) { final String tokenText = tokenNodes.item(nc).getTextContent(); tokens.add(new SimpleToken(witness, tokenText, normalizer.apply(tokenText))); } witness.setTokens(tokens); witnesses.add(witness); } } } } final VariantGraph variantGraph = new VariantGraph(); collationAlgorithm.collate(variantGraph, witnesses); if (joined && !commandLine.hasOption("t")) { VariantGraph.JOIN.apply(variantGraph); } final String output = commandLine.getOptionValue("o", "-"); final Charset outputCharset = Charset .forName(commandLine.getOptionValue("oe", StandardCharsets.UTF_8.name())); final String outputFormat = commandLine.getOptionValue("f", "json").toLowerCase(); try (PrintWriter out = argumentToOutput(output, outputCharset)) { final SimpleVariantGraphSerializer serializer = new SimpleVariantGraphSerializer(variantGraph); if ("csv".equals(outputFormat)) { serializer.toCsv(out); } else if ("dot".equals(outputFormat)) { serializer.toDot(out); } else if ("graphml".equals(outputFormat) || "tei".equals(outputFormat)) { XMLStreamWriter xml = null; try { xml = XMLOutputFactory.newInstance().createXMLStreamWriter(out); xml.writeStartDocument(outputCharset.name(), "1.0"); if ("graphml".equals(outputFormat)) { serializer.toGraphML(xml); } else { serializer.toTEI(xml); } xml.writeEndDocument(); } catch (XMLStreamException e) { throw new IOException(e); } finally { if (xml != null) { try { xml.close(); } catch (XMLStreamException e) { // ignored } } } } else { JsonProcessor.write(variantGraph, out); } } }
From source file:org.ng200.openolympus.services.ContestSecurityService.java
public void assertSuperuserOrTaskAllowed(final Principal principal, final Task task) { this.assertSuperuserOrTaskAllowed(Optional.ofNullable(principal) .map(p -> this.userRepository.findByUsername(p.getName())).orElse(null), task); }
From source file:com.baasbox.service.scripting.ScriptingService.java
private static ODocument updateStorageLocked(String name, boolean before, JsonCallback updaterFn) throws ScriptException { final ScriptsDao dao = ScriptsDao.getInstance(); ODocument script = null;// ww w . j a v a2 s . c om try { script = dao.getByNameLocked(name); if (script == null) throw new ScriptException("Script not found"); ODocument retScript = before ? script.copy() : script; ODocument storage = script.<ODocument>field(ScriptsDao.LOCAL_STORAGE); Optional<ODocument> storage1 = Optional.ofNullable(storage); JsonNode current = storage1.map(ODocument::toJSON).map(Json.mapper()::readTreeOrMissing) .orElse(NullNode.getInstance()); if (current.isMissingNode()) throw new ScriptEvalException("Error reading local storage as json"); JsonNode updated = updaterFn.call(current); ODocument result; if (updated == null || updated.isNull()) { script.removeField(ScriptsDao.LOCAL_STORAGE); } else { result = new ODocument().fromJSON(updated.toString()); script.field(ScriptsDao.LOCAL_STORAGE, result); } dao.save(script); ODocument field = retScript.field(ScriptsDao.LOCAL_STORAGE); return field; } finally { if (script != null) { script.unlock(); } } }
From source file:com.michellemay.profiles.ProfilesFactory.java
private Profile createProfile(ProfileConfig profileConfig) { if (StringUtils.isBlank(profileConfig.name)) { throw new IllegalArgumentException("Blank profile name!"); }/*from ww w. j av a 2 s .c o m*/ Mapping tempMapping = null; if (profileConfig.mapping != null) { if (StringUtils.isBlank(profileConfig.mapping) || !mappingsFactory.getMappings().containsKey(profileConfig.mapping)) { throw new IllegalStateException("Mapping '" + profileConfig.mapping + "' does not exists!"); } tempMapping = mappingsFactory.getMappings().get(profileConfig.mapping); } Optional<Mapping> defaultMapping = Optional.ofNullable(tempMapping); if (profileConfig.domains == null || profileConfig.domains.isEmpty()) { throw new IllegalArgumentException("Profile must have non-empty domains list!"); } ArrayList<Pattern> domains = Lists.newArrayList(); profileConfig.domains.forEach((patternStr) -> { // Domain names are case insensitive. domains.add(Pattern.compile(patternStr, Pattern.CASE_INSENSITIVE)); }); ArrayList<Matcher> matchers = Lists.newArrayList(); profileConfig.matchers.forEach((matcherRef) -> { String mappingName = matcherRef.mapping; Optional<Mapping> localMapping = Optional.empty(); if (!StringUtils.isBlank(mappingName)) { if (!mappingsFactory.getMappings().containsKey(mappingName)) { throw new IllegalStateException("Mapping '" + mappingName + "' does not exists!"); } localMapping = Optional.of(mappingsFactory.getMappings().get(mappingName)); } String matcherName = matcherRef.matcher; if (StringUtils.isBlank(matcherName) || !matchersFactory.getMatchers().containsKey(matcherName)) { throw new IllegalStateException("Matcher '" + matcherName + "' does not exists!"); } Matcher matcher = matchersFactory.getMatchers().get(matcherName); // Validate that a matcher has a mapping. // Select in order of appearance: localMapping, defaultMapping, matcher.mapping. Optional<Mapping> finalMapping = Stream.of(localMapping, defaultMapping, matcher.getMapping()) .filter(Optional::isPresent).findFirst() .orElseThrow(() -> new IllegalStateException("Matcher '" + matcherName + "' does not have a valid mapping! (Profile '" + profileConfig.name + "')")); matchers.add(matcher.shallowCopyWithMapping(finalMapping)); }); return new Profile(profileConfig.name).withDomains(domains).withMatchers(matchers); }
From source file:com.github.ljtfreitas.restify.http.spring.contract.metadata.reflection.SpringWebJavaTypeMetadata.java
public String[] paths() { ArrayList<String> paths = new ArrayList<>(); Optional.ofNullable(parent).map(p -> p.paths()).ifPresent(array -> Collections.addAll(paths, array)); mapping.flatMap(m -> m.path()).ifPresent(p -> paths.add(p)); return paths.toArray(new String[0]); }
From source file:com.netflix.genie.common.internal.dto.v4.Criterion.java
/** * Get the name of the resource desired if it exists. * * @return {@link Optional} wrapping the name *//*w w w.j a va2 s . c o m*/ public Optional<String> getName() { return Optional.ofNullable(this.name); }
From source file:org.openmhealth.schema.domain.omh.AdditionalPropertySupport.java
/** * Gets an additional property.//www .j a v a2 s. co m * * @param name the name of the additional property to retrieve * @return the property value, if present */ default Optional<Object> getAdditionalProperty(String name) { checkNotNull(name, "A name hasn't been specified."); checkArgument(!name.isEmpty(), "An empty name has been specified."); return Optional.ofNullable(getAdditionalProperties().get(name)); }
From source file:com.fredhopper.connector.index.provider.AbstractAttributeProvider.java
protected void addValues(final Table<Optional<String>, Optional<Locale>, String> table, final Locale locale, final Object values, final MetaAttributeData metaAttribute) { if (values != null) { final Optional<Locale> loc = locale != null ? Optional.of(locale) : Optional.empty(); if (values instanceof Collection) { for (final Object value : (Collection) values) { final Optional<String> valueId = Optional .ofNullable(generateAttributeValueId(metaAttribute, value)); table.put(valueId, loc, value.toString()); }/*from www .ja v a2s. c o m*/ } else { final Optional<String> valueId = Optional .ofNullable(generateAttributeValueId(metaAttribute, values)); table.put(valueId, loc, values.toString()); } } }
From source file:org.lendingclub.mercator.docker.DockerRestClient.java
public Optional<String> getSwarmClusterId() { return Optional.ofNullable(getInfo().path("Swarm").path("Cluster").path("ID").asText(null)); }