List of usage examples for java.util Optional orElse
public T orElse(T other)
From source file:com.openlattice.authentication.Auth0AuthenticationConfiguration.java
@JsonCreator public Auth0AuthenticationConfiguration(@JsonProperty(ISSUER_FIELD) String issuer, @JsonProperty(AUDIENCE_FIELD) String audience, @JsonProperty(SECRET_FIELD) String secret, @JsonProperty(BASE64_ENCODED_SECRET_FIELD) Optional<Boolean> base64EncodedSecret, @JsonProperty(SIGNING_ALGORITHM_FIELD) String signingAlgorithm) { Preconditions.checkArgument(StringUtils.isNotBlank(issuer)); Preconditions.checkArgument(StringUtils.isNotBlank(audience)); Preconditions.checkArgument(StringUtils.isNotBlank(secret)); this.issuer = issuer; this.audience = audience; this.secret = secret; this.base64EncodedSecret = base64EncodedSecret.orElse(false); this.signingAlgorithm = signingAlgorithm; }
From source file:io.klerch.alexa.state.handler.AWSS3StateHandler.java
/** * {@inheritDoc}/*from w w w .j av a2 s . c o m*/ */ @Override public <TModel extends AlexaStateModel> Optional<TModel> readModel(final Class<TModel> modelClass, final String id) throws AlexaStateException { // if there is nothing for this model in the session ... final Optional<TModel> modelSession = super.readModel(modelClass, id); // create new model with given id. for now we assume a model exists for this id. we find out by // reading file from the bucket in the following lines. only if this is true model will be written back to session final TModel model = modelSession.orElse(createModel(modelClass, id)); // we need to remember if there will be something from S3 to be written to the model // in order to write those values back to the session at the end of this method Boolean modelChanged = false; // and if there are user-scoped fields ... if (model.hasUserScopedField() && fromS3FileContentsToModel(model, id, AlexaScope.USER)) { modelChanged = true; } // and if there are app-scoped fields ... if (model.hasApplicationScopedField() && fromS3FileContentsToModel(model, id, AlexaScope.APPLICATION)) { modelChanged = true; } // so if model changed from within something out of S3 we want this to be in the speechlet as well // this gives you access to user- and app-scoped attributes throughout a session without reading from S3 over and over again if (modelChanged) { super.writeModel(model); return Optional.of(model); } else { // if there was nothing received from S3 and there is nothing to return from session // then its not worth return the model. better indicate this model does not exist return modelSession.isPresent() ? Optional.of(model) : Optional.empty(); } }
From source file:com.ikanow.aleph2.enrichment.utils.services.JsScriptEngineService.java
@Override public void onObjectBatch(Stream<Tuple2<Long, IBatchRecord>> batch, Optional<Integer> batch_size, Optional<JsonNode> grouping_key) { try {//from w w w. ja v a 2 s. c o m final Supplier<Object> get_batch = () -> batch; final Supplier<Object> get_batch_record = () -> batch.map(x -> x._2().getJson()); ((Invocable) _engine.get()).invokeFunction("aleph2_global_handle_batch", get_batch, get_batch_record, batch_size.orElse(null), grouping_key.orElse(null)); } catch (Throwable e) { _logger.error(ErrorUtils.getLongForm("onObjectBatch: {0}", e)); final Level level = Lambdas.get(() -> { if (_mutable_first_error.isSet()) { return Level.DEBUG; } else { _mutable_first_error.set(false); return Level.ERROR; } }); _bucket_logger.optional() .ifPresent(l -> l.log(level, ErrorUtils.lazyBuildMessage(false, () -> this.getClass().getSimpleName() + "." + Optional.ofNullable(_control.get().name()).orElse("no_name"), () -> Optional.ofNullable(_control.get().name()).orElse("no_name") + ".onObjectBatch", () -> null, () -> ErrorUtils.get("Error on batch in job {0}: {1} (first_seen={2})", Optional.ofNullable(_control.get().name()).orElse("(no name)"), e.getMessage(), (level == Level.ERROR)), () -> ImmutableMap.<String, Object>of("full_error", ErrorUtils.getLongForm("{0}", e))))); if (_config.get().exit_on_error()) { throw new RuntimeException(e); } } }
From source file:com.github.larsq.spring.embeddedamqp.SimpleAmqpMessageContainer.java
public QueueInfo queueDeclare(Queue queue) { Optional<Queue> reference = queue(queue.getName()); consumers.computeIfAbsent(reference.orElse(queue), __ -> new ArrayList<>()); ConsumerSubscription defaultSubscription = new ConsumerSubscription(null, String.join(".", SYSTEM, queue.getName()), new QueueingConsumer(100, true)); consumers.get(reference.orElse(queue)).add(defaultSubscription); return new QueueInfo(this, queue.getName()); }
From source file:org.apache.nifi.schemaregistry.hortonworks.HortonworksSchemaRegistry.java
private String createErrorMessage(final String baseMessage, final Optional<String> schemaName, final Optional<String> branchName, final OptionalInt version) { final StringBuilder builder = new StringBuilder(baseMessage).append(" with name '") .append(schemaName.orElse("null")).append("'"); if (branchName.isPresent()) { builder.append(" and branch '").append(branchName.get()).append("'"); }//from w w w . j a v a 2 s.c o m if (version.isPresent()) { builder.append(" and version '").append(version.getAsInt()).append("'"); } return builder.toString(); }
From source file:com.google.cloud.tools.intellij.appengine.cloud.flexible.AppEngineFlexibleDeploymentEditor.java
private void updateServiceName() { Optional<String> service = APP_ENGINE_PROJECT_SERVICE.getServiceNameFromAppYaml(getAppYamlPath()); serviceLabel.setText(service.orElse(DEFAULT_SERVICE)); }
From source file:controllers.config.Config.java
/** * Overlays the hostclass configuration. * * @param rawHostclass the hostclass//from w ww. j a v a 2s . c o m * @return a hostclass configuration yaml response */ public F.Promise<Result> hostclass(final String rawHostclass) { final String rollerHostclass = Iterables .get(Splitter.on("-").trimResults().limit(2).omitEmptyStrings().split(rawHostclass), 0); final List<String> splitHostclass = Splitter.on("::").trimResults().limit(2).omitEmptyStrings() .splitToList(rawHostclass); final Optional<String> artemisHostclass = Optional.ofNullable(Iterables.get(splitHostclass, 1, null)); final Optional<String> rollerVersionedHostclass = Optional .ofNullable(Iterables.get(splitHostclass, 0, null)); LOGGER.info(String.format("Request for hostclass; rollerHostclass=%s, artemisHostclass=%s", rollerHostclass, artemisHostclass.orElse("[null]"))); return _configClient.getHostclassData(rollerVersionedHostclass.get()).map(hostclassOutput -> { if (artemisHostclass.isPresent()) { final Hostclass hostclass = Hostclass.getByName(artemisHostclass.get()); if (hostclass == null) { return notFound(); } overlayHostclass(hostclassOutput, hostclass); } return ok(YAML_MAPPER.writeValueAsString(hostclassOutput)); }); }
From source file:com.spankingrpgs.scarletmoon.characters.CrimsonGameCharacter.java
private void modifyRisque() { Optional<Equipment> underwear = getEquipment(CrimsonGlowEquipSlotNames.UNDERWEAR.name()); Optional<Equipment> lowerClothing = getEquipment(CrimsonGlowEquipSlotNames.LOWER.name()); int risque = getEquipment().stream() .filter(equipment -> !lowerClothing.isPresent() || !equipment.equals(underwear.orElse(null))) .mapToInt(Equipment::getRisque).sum(); setStatistic(SecondaryStatisticName.RISQUE.name(), risque); }
From source file:alfio.controller.api.ReservationApiController.java
@RequestMapping(value = "/event/{eventName}/ticket/{ticketIdentifier}/assign", method = RequestMethod.POST, headers = "X-Requested-With=XMLHttpRequest") public Map<String, Object> assignTicketToPerson(@PathVariable("eventName") String eventName, @PathVariable("ticketIdentifier") String ticketIdentifier, @RequestParam(value = "single-ticket", required = false, defaultValue = "false") boolean singleTicket, UpdateTicketOwnerForm updateTicketOwner, BindingResult bindingResult, HttpServletRequest request, Model model, Authentication authentication) throws Exception { Optional<UserDetails> userDetails = Optional.ofNullable(authentication).map(Authentication::getPrincipal) .filter(UserDetails.class::isInstance).map(UserDetails.class::cast); Optional<Triple<ValidationResult, Event, Ticket>> assignmentResult = ticketHelper.assignTicket(eventName, ticketIdentifier, updateTicketOwner, Optional.of(bindingResult), request, t -> { Locale requestLocale = RequestContextUtils.getLocale(request); model.addAttribute("ticketFieldConfiguration", ticketHelper.findTicketFieldConfigurationAndValue(t.getMiddle().getId(), t.getRight(), requestLocale)); model.addAttribute("value", t.getRight()); model.addAttribute("validationResult", t.getLeft()); model.addAttribute("countries", TicketHelper.getLocalizedCountries(requestLocale)); model.addAttribute("event", t.getMiddle()); model.addAttribute("useFirstAndLastName", t.getMiddle().mustUseFirstAndLastName()); model.addAttribute("availableLanguages", i18nManager.getEventLanguages(eventName).stream() .map(ContentLanguage.toLanguage(requestLocale)).collect(Collectors.toList())); String uuid = t.getRight().getUuid(); model.addAttribute("urlSuffix", singleTicket ? "ticket/" + uuid + "/view" : uuid); model.addAttribute("elementNamePrefix", ""); }, userDetails);//from w w w . j a v a 2 s . c o m Map<String, Object> result = new HashMap<>(); Optional<ValidationResult> validationResult = assignmentResult.map(Triple::getLeft); if (validationResult.isPresent() && validationResult.get().isSuccess()) { result.put("partial", templateManager.renderServletContextResource("/WEB-INF/templates/event/assign-ticket-result.ms", model.asMap(), request, TemplateManager.TemplateOutput.HTML)); } result.put("validationResult", validationResult.orElse( ValidationResult.failed(new ValidationResult.ErrorDescriptor("fullName", "error.fullname")))); return result; }
From source file:uk.nhs.fhir.render.NewMain.java
public NewMain(Path inputDirectory, Path outPath, Optional<String> newBaseURL, Optional<Set<String>> permittedMissingExtensionPrefixes, AbstractRendererEventHandler errorHandler, Optional<Set<String>> localQdomains) { this.rendererFileLocator = new DefaultRendererFileLocator(inputDirectory, makeRenderedArtefactTempDirectory(), outPath); this.newBaseURL = newBaseURL; this.permittedMissingExtensionPrefixes = permittedMissingExtensionPrefixes.orElse(Sets.newHashSet()); this.eventHandler = errorHandler; this.localQdomains = localQdomains.map(qdomains -> (Set<String>) ImmutableSet.copyOf(qdomains)); }