List of usage examples for java.util Optional orElse
public T orElse(T other)
From source file:org.onosproject.net.optical.intent.impl.compiler.OpticalCircuitIntentCompiler.java
private Optional<OchPort> findAvailableOchPort(ConnectPoint oduPort, OduSignalType ochPortSignalType) { // First see if the port mappings are constrained ConnectPoint ochCP = staticPort(oduPort); if (ochCP != null) { OchPort ochPort = (OchPort) deviceService.getPort(ochCP.deviceId(), ochCP.port()); Optional<IntentId> intentId = resourceService .getResourceAllocations(Resources.discrete(ochCP.deviceId(), ochCP.port()).id()).stream() .map(ResourceAllocation::consumerId).map(ResourceHelper::getIntentId).flatMap(Tools::stream) .findAny();/*from www . ja va2 s. c om*/ if (isAvailable(intentId.orElse(null))) { return Optional.of(ochPort); } return Optional.empty(); } // No port constraints, so find any port that works List<Port> ports = deviceService.getPorts(oduPort.deviceId()); for (Port port : ports) { if (!(port instanceof OchPort)) { continue; } // This should be the first allocation on the OCH port if (!resourceService.isAvailable(Resources.discrete(oduPort.deviceId(), port.number()).resource())) { continue; } // OchPort is required to have the requested oduSignalType if (((OchPort) port).signalType() != ochPortSignalType) { continue; } Optional<IntentId> intentId = resourceService .getResourceAllocations(Resources.discrete(oduPort.deviceId(), port.number()).id()).stream() .map(ResourceAllocation::consumerId).map(ResourceHelper::getIntentId).flatMap(Tools::stream) .findAny(); if (isAvailable(intentId.orElse(null))) { return Optional.of((OchPort) port); } } return Optional.empty(); }
From source file:com.intuit.wasabi.repository.cassandra.impl.CassandraPagesRepository.java
Stream<AppPage> getAppPagesFromCassandra(Application.Name applicationName) { Optional<Iterator<AppPage>> optionalResult = Optional.empty(); try {/*from ww w . j a v a2 s . c o m*/ optionalResult = Optional .ofNullable(appPageIndexAccessor.selectBy(applicationName.toString()).iterator()); } catch (ReadTimeoutException | UnavailableException | NoHostAvailableException e) { throw new RepositoryException( "Could not retrieve the pages and its associated experiments for application:\"" + applicationName + "\"", e); } return StreamSupport.stream(Spliterators.spliteratorUnknownSize( optionalResult.orElse(Collections.emptyIterator()), Spliterator.ORDERED), false); }
From source file:com.ikanow.aleph2.analytics.services.BatchEnrichmentContext.java
@Override public <S> ICrudService<S> getBucketObjectStore(final Class<S> clazz, final Optional<DataBucketBean> bucket, final Optional<String> collection, final Optional<StateDirectoryType> type) { // Translate default to enrichment, and handle bucket store being the module not the analytic technology if (type.isPresent() && (StateDirectoryType.library == type.get())) { throw new RuntimeException( ErrorUtils.get(ErrorUtils.INVALID_CONFIG_ERROR, "getBucketObjectStore", "library")); } else {//from ww w .j a va 2 s . c om Optional<StateDirectoryType> translated_type = Optional .ofNullable(type.orElse(StateDirectoryType.enrichment)); return _delegate.get().getBucketObjectStore(clazz, bucket, collection, translated_type); } }
From source file:alfio.controller.ReservationController.java
@RequestMapping(value = "/event/{eventName}/reservation/{reservationId}/waitingPayment", method = RequestMethod.GET) public String showWaitingPaymentPage(@PathVariable("eventName") String eventName, @PathVariable("reservationId") String reservationId, Model model, Locale locale) { Optional<Event> event = eventRepository.findOptionalByShortName(eventName); if (!event.isPresent()) { return "redirect:/"; }/*from w ww.j ava2s .co m*/ Optional<TicketReservation> reservation = ticketReservationManager.findById(reservationId); TicketReservationStatus status = reservation.map(TicketReservation::getStatus) .orElse(TicketReservationStatus.PENDING); if (reservation.isPresent() && status == TicketReservationStatus.OFFLINE_PAYMENT) { Event ev = event.get(); TicketReservation ticketReservation = reservation.get(); OrderSummary orderSummary = ticketReservationManager.orderSummaryForReservationId(reservationId, ev, locale); model.addAttribute("totalPrice", orderSummary.getTotalPrice()); model.addAttribute("emailAddress", organizationRepository.getById(ev.getOrganizationId()).getEmail()); model.addAttribute("reservation", ticketReservation); model.addAttribute("paymentReason", ev.getShortName() + " " + ticketReservationManager.getShortReservationID(ev, reservationId)); model.addAttribute("pageTitle", "reservation-page-waiting.header.title"); model.addAttribute("bankAccount", configurationManager .getStringConfigValue( Configuration.from(ev.getOrganizationId(), ev.getId(), BANK_ACCOUNT_NR)) .orElse("")); Optional<String> maybeAccountOwner = configurationManager.getStringConfigValue( Configuration.from(ev.getOrganizationId(), ev.getId(), BANK_ACCOUNT_OWNER)); model.addAttribute("hasBankAccountOwnerSet", maybeAccountOwner.isPresent()); model.addAttribute("bankAccountOwner", Arrays.asList(maybeAccountOwner.orElse("").split("\n"))); model.addAttribute("expires", ZonedDateTime.ofInstant(ticketReservation.getValidity().toInstant(), ev.getZoneId())); model.addAttribute("event", ev); return "/event/reservation-waiting-for-payment"; } return redirectReservation(reservation, eventName, reservationId); }
From source file:org.onosproject.store.ecmap.EventuallyConsistentMapImpl.java
private V removeAndNotify(K key, V value) { Timestamp timestamp = timestampProvider.apply(key, value); Optional<MapValue<V>> tombstone = tombstonesDisabled || timestamp == null ? Optional.empty() : Optional.of(MapValue.tombstone(timestamp)); MapValue<V> previousValue = removeInternal(key, Optional.ofNullable(value), tombstone); if (previousValue != null) { notifyPeers(new UpdateEntry<>(key, tombstone.orElse(null)), peerUpdateFunction.apply(key, previousValue.get())); if (previousValue.isAlive()) { notifyListeners(new EventuallyConsistentMapEvent<>(mapName, REMOVE, key, previousValue.get())); }/*from www. java 2s .co m*/ } return previousValue != null ? previousValue.get() : null; }
From source file:com.spotify.heroic.suggest.elasticsearch.ElasticsearchSuggestModule.java
@JsonCreator public ElasticsearchSuggestModule(@JsonProperty("id") Optional<String> id, @JsonProperty("groups") Optional<Groups> groups, @JsonProperty("connection") Optional<ConnectionModule> connection, @JsonProperty("writesPerSecond") Optional<Double> writesPerSecond, @JsonProperty("rateLimitSlowStartSeconds") Optional<Long> rateLimitSlowStartSeconds, @JsonProperty("writeCacheDurationMinutes") Optional<Long> writeCacheDurationMinutes, @JsonProperty("templateName") Optional<String> templateName, @JsonProperty("backendType") Optional<String> backendType, @JsonProperty("configure") Optional<Boolean> configure) { this.id = id; this.groups = groups.orElseGet(Groups::empty).or(DEFAULT_GROUP); this.connection = connection.orElseGet(ConnectionModule::buildDefault); this.writesPerSecond = writesPerSecond.orElse(DEFAULT_WRITES_PER_SECOND); this.rateLimitSlowStartSeconds = rateLimitSlowStartSeconds.orElse(DEFAULT_RATE_LIMIT_SLOW_START_SECONDS); this.writeCacheDurationMinutes = writeCacheDurationMinutes.orElse(DEFAULT_WRITES_CACHE_DURATION_MINUTES); this.templateName = templateName.orElse(DEFAULT_TEMPLATE_NAME); this.backendType = backendType.orElse(DEFAULT_BACKEND_TYPE); this.type = backendType.map(this::lookupBackendType).orElse(defaultSetup); this.configure = configure.orElse(DEFAULT_CONFIGURE); }
From source file:net.sf.jabref.groups.EntryTableTransferHandler.java
/** * Take a set of filenames. Those with names indicating bib files are opened as such if possible. All other files we * will attempt to import into the current database. * * @param fileNames The names of the files to open. * @param dropRow success status for the operation *///from w ww . jav a 2 s . c o m private void loadOrImportFiles(String[] fileNames, int dropRow) { OpenDatabaseAction openAction = new OpenDatabaseAction(frame, false); List<String> notBibFiles = new ArrayList<>(); List<String> bibFiles = new ArrayList<>(); for (String fileName : fileNames) { // Find the file's extension, if any: Optional<String> extension = FileUtil.getFileExtension(fileName); ExternalFileType fileType; if (extension.isPresent() && "bib".equals(extension.get())) { // we assume that it is a BibTeX file. // When a user wants to import something with file extension "bib", but which is not a BibTeX file, he should use "file -> import" bibFiles.add(fileName); continue; } fileType = ExternalFileTypes.getInstance().getExternalFileTypeByExt(extension.orElse("")); /* * This is a linkable file. If the user dropped it on an entry, we * should offer options for autolinking to this files: * * TODO we should offer an option to highlight the row the user is on too. */ if ((fileType != null) && (dropRow >= 0)) { /* * TODO: make this an instance variable? */ DroppedFileHandler dfh = new DroppedFileHandler(frame, panel); dfh.handleDroppedfile(fileName, fileType, entryTable, dropRow); continue; } notBibFiles.add(fileName); } openAction.openFilesAsStringList(bibFiles, true); if (!notBibFiles.isEmpty()) { // Import into new if entryTable==null, otherwise into current // database: ImportMenuItem importer = new ImportMenuItem(frame, entryTable == null); importer.automatedImport(notBibFiles); } }
From source file:net.sf.jabref.model.entry.BibEntry.java
/** * Will return the publication date of the given bibtex entry conforming to ISO 8601, i.e. either YYYY or YYYY-MM. * * @return will return the publication date of the entry or null if no year was found. *//*from w w w.j av a 2 s. c o m*/ public Optional<String> getPublicationDate() { if (!hasField(FieldName.YEAR)) { return Optional.empty(); } Optional<String> year = getFieldOptional(FieldName.YEAR); Optional<String> monthString = getFieldOptional(FieldName.MONTH); if (monthString.isPresent()) { MonthUtil.Month month = MonthUtil.getMonth(monthString.get()); if (month.isValid()) { return Optional.of(year.orElse("") + "-" + month.twoDigitNumber); } } return year; }
From source file:net.sf.jabref.gui.groups.EntryTableTransferHandler.java
/** * Take a set of filenames. Those with names indicating bib files are opened as such if possible. All other files we * will attempt to import into the current database. * * @param fileNames The names of the files to open. * @param dropRow success status for the operation */// w ww . j av a2 s. co m private void loadOrImportFiles(List<String> fileNames, int dropRow) { OpenDatabaseAction openAction = new OpenDatabaseAction(frame, false); List<String> notBibFiles = new ArrayList<>(); List<String> bibFiles = new ArrayList<>(); for (String fileName : fileNames) { // Find the file's extension, if any: Optional<String> extension = FileUtil.getFileExtension(fileName); Optional<ExternalFileType> fileType; if (extension.isPresent() && "bib".equals(extension.get())) { // we assume that it is a BibTeX file. // When a user wants to import something with file extension "bib", but which is not a BibTeX file, he should use "file -> import" bibFiles.add(fileName); continue; } fileType = ExternalFileTypes.getInstance().getExternalFileTypeByExt(extension.orElse("")); /* * This is a linkable file. If the user dropped it on an entry, we * should offer options for autolinking to this files: * * TODO we should offer an option to highlight the row the user is on too. */ if ((fileType.isPresent()) && (dropRow >= 0)) { /* * TODO: make this an instance variable? */ DroppedFileHandler dfh = new DroppedFileHandler(frame, panel); dfh.handleDroppedfile(fileName, fileType.get(), entryTable, dropRow); continue; } notBibFiles.add(fileName); } openAction.openFilesAsStringList(bibFiles, true); if (!notBibFiles.isEmpty()) { // Import into new if entryTable==null, otherwise into current // database: ImportMenuItem importer = new ImportMenuItem(frame, entryTable == null); importer.automatedImport(notBibFiles); } }
From source file:org.roda.core.plugins.plugins.PluginHelper.java
private static Optional<String> createGhost(String ancestor, Optional<String> parent, ModelService model, IndexService index, String jobId) throws NotFoundException, GenericException, RequestNotValidException, AlreadyExistsException, AuthorizationDeniedException { String username = getJobUsername(jobId, index); Permissions permissions = new Permissions(); permissions.setUserPermissions(username, new HashSet<>(Arrays.asList(Permissions.PermissionType.CREATE, Permissions.PermissionType.READ, Permissions.PermissionType.UPDATE, Permissions.PermissionType.DELETE, Permissions.PermissionType.GRANT))); boolean isGhost = true; AIP ghostAIP = model.createAIP(parent.orElse(null), "", permissions, Arrays.asList(ancestor), jobId, true, username, isGhost);/*from w w w . j av a2 s . c om*/ return Optional.ofNullable(ghostAIP.getId()); }