List of usage examples for java.util Optional filter
public Optional<T> filter(Predicate<? super T> predicate)
From source file:fr.treeptik.cloudunit.controller.FileController.java
/** * Download a file into a container// w w w . ja v a 2 s.c o m * * @param containerId * @param applicationName * @param path * @param fileName * @param request * @param response * @throws ServiceException * @throws CheckException * @throws IOException * @returnoriginalName */ @RequestMapping(value = "/container/{containerId}/application/{applicationName}/path/{path}/fileName/{fileName:.*}", method = RequestMethod.GET) public void downloadFileFromContainer(@PathVariable final String containerId, @PathVariable final String applicationName, @PathVariable String path, @PathVariable final String fileName, HttpServletRequest request, HttpServletResponse response) throws ServiceException, CheckException, IOException { if (logger.isDebugEnabled()) { logger.debug("containerId:" + containerId); logger.debug("applicationName:" + applicationName); logger.debug("fileName:" + fileName); } User user = authentificationUtils.getAuthentificatedUser(); Application application = applicationService.findByNameAndUser(user, applicationName); // We must be sure there is no running action before starting new one this.authentificationUtils.canStartNewAction(user, application, locale); File file = File.createTempFile("previousDownload", FilesUtils.setSuffix(fileName)); path = convertPathFromUI(path); Optional<File> fileFromContainer = fileService.getFileFromContainer(applicationName, containerId, file, fileName, path); // File can be empty but we need to return one if (fileFromContainer.filter(x -> x.length() == 0).isPresent()) { file = File.createTempFile(fileName, ""); // put an empty space for empty file FileUtils.write(file, " "); } InputStream inputStream = new FileInputStream(file); //load the file IOUtils.copy(inputStream, response.getOutputStream()); response.flushBuffer(); }
From source file:com.epam.ta.reportportal.util.email.MailServiceFactory.java
/** * Build mail service based on provided configs * * @param projectConfig Project-level configuration * @param serverConfig Server-level configuration * @return Built email service//from ww w . j a v a 2 s. co m */ public Optional<EmailService> getEmailService(ProjectEmailConfig projectConfig, ServerEmailDetails serverConfig) { return getEmailService(serverConfig).flatMap(service -> { // if there is server email config, let's check project config Optional<ProjectEmailConfig> projectConf = ofNullable(projectConfig); if (projectConf.isPresent()) { // if project config is present, check whether sending emails is enabled and replace server properties with project properties return projectConf.filter(ProjectEmailConfig::getEmailEnabled).flatMap(pc -> { //update of present on project level Optional.ofNullable(pc.getFrom()).ifPresent(service::setFrom); return Optional.of(service); }); } else { return Optional.of(service); } }); }
From source file:com.ikanow.aleph2.search_service.elasticsearch.utils.ElasticsearchIndexUtils.java
/** Creates a mapping for the bucket - columnar elements * ALSO INCLUDES THE PER-FIELD CONFIGURATION FROM THE SEARCH_INDEX_SCHEMA AND TEMPORAL_SCHMEA * @param bucket//from w w w. j a v a 2s . c o m * @return * @throws IOException */ public static XContentBuilder getColumnarMapping(final DataBucketBean bucket, Optional<XContentBuilder> to_embed, final LinkedHashMap<Either<String, Tuple2<String, String>>, JsonNode> field_lookups, final JsonNode enabled_not_analyzed, final JsonNode enabled_analyzed, final JsonNode default_not_analyzed, final JsonNode default_analyzed, final Optional<JsonNode> doc_schema, final SearchIndexSchemaDefaultBean search_index_schema_override, final ObjectMapper mapper, final String index_type) { try { final XContentBuilder start = to_embed.orElse(XContentFactory.jsonBuilder().startObject()); final boolean columnar_enabled = Optional.ofNullable(bucket.data_schema()) .map(DataSchemaBean::columnar_schema).filter(s -> Optional.ofNullable(s.enabled()).orElse(true)) .isPresent(); final Map<Either<String, Tuple2<String, String>>, String> type_override = Optionals .of(() -> bucket.data_schema().search_index_schema().type_override()).map(m -> buildTypeMap(m)) .orElse(Collections.emptyMap()); // If no columnar settings are specified then go with a sensible default final Optional<DataSchemaBean.ColumnarSchemaBean> maybe_user_columnar_schema = Optionals .of(() -> bucket.data_schema().columnar_schema()); final DataSchemaBean.ColumnarSchemaBean columnar_schema = maybe_user_columnar_schema .filter(__ -> columnar_enabled).filter(schema -> (null == schema.field_include_list()) && // ie the entire thing is empty (null == schema.field_exclude_list()) && (null == schema.field_include_pattern_list()) && (null == schema.field_type_include_list()) && (null == schema.field_exclude_pattern_list()) && (null == schema.field_type_exclude_list())) .map(schema -> BeanTemplateUtils.clone(schema) .with(DataSchemaBean.ColumnarSchemaBean::field_type_include_list, Arrays.asList("string", "number", "date")) .done()) .orElseGet(() -> maybe_user_columnar_schema.orElse(null)) // (NOTE: can only be null if columnar_enabled is false) ; final LinkedHashMap<Either<String, Tuple2<String, String>>, JsonNode> column_lookups_pretypes = Stream .of(columnar_enabled ? createFieldIncludeLookups( Optionals.ofNullable(columnar_schema.field_include_list()).stream(), fn -> getKey(fn), field_lookups, enabled_not_analyzed, enabled_analyzed, true, search_index_schema_override, type_override, mapper, index_type) : Stream.<Tuple2<Either<String, Tuple2<String, String>>, JsonNode>>empty(), columnar_enabled ? createFieldExcludeLookups( Optionals.ofNullable(columnar_schema.field_exclude_list()).stream(), fn -> getKey(fn), field_lookups, search_index_schema_override, type_override, mapper, index_type) : Stream.<Tuple2<Either<String, Tuple2<String, String>>, JsonNode>>empty(), columnar_enabled ? createFieldIncludeLookups( Optionals.ofNullable(columnar_schema.field_include_pattern_list()) .stream(), fn -> Either.right(Tuples._2T(fn, "*")), field_lookups, enabled_not_analyzed, enabled_analyzed, true, search_index_schema_override, type_override, mapper, index_type) : Stream.<Tuple2<Either<String, Tuple2<String, String>>, JsonNode>>empty(), columnar_enabled ? createFieldIncludeLookups( Optionals.ofNullable(columnar_schema.field_type_include_list()) .stream(), fn -> Either.right(Tuples._2T("*", fn)), field_lookups, enabled_not_analyzed, enabled_analyzed, true, search_index_schema_override, type_override, mapper, index_type) : Stream.<Tuple2<Either<String, Tuple2<String, String>>, JsonNode>>empty(), columnar_enabled ? createFieldExcludeLookups( Optionals.ofNullable(columnar_schema.field_exclude_pattern_list()) .stream(), fn -> Either.right(Tuples._2T(fn, "*")), field_lookups, search_index_schema_override, type_override, mapper, index_type) : Stream.<Tuple2<Either<String, Tuple2<String, String>>, JsonNode>>empty(), columnar_enabled ? createFieldExcludeLookups( Optionals.ofNullable(columnar_schema.field_type_exclude_list()) .stream(), fn -> Either.right(Tuples._2T("*", fn)), field_lookups, search_index_schema_override, type_override, mapper, index_type) : Stream.<Tuple2<Either<String, Tuple2<String, String>>, JsonNode>>empty(), // Finally add the default columnar lookups to the unmentioned strings (ensures that *_* is at the end) field_lookups.entrySet().stream() .flatMap(kv -> createFieldIncludeLookups(Stream.of(kv.getKey().toString()), __ -> kv.getKey(), field_lookups, default_not_analyzed, default_analyzed, false, search_index_schema_override, type_override, mapper, index_type))) .flatMap(x -> x).collect(Collectors.toMap(t2 -> t2._1(), t2 -> t2._2(), (v1, v2) -> v1, // (ie ignore duplicates) () -> new LinkedHashMap<Either<String, Tuple2<String, String>>, JsonNode>())); ; // Also any types that didn't map onto one of the fields or tokens: final LinkedHashMap<Either<String, Tuple2<String, String>>, JsonNode> column_lookups_types = type_override .entrySet().stream() // (filter - convert name/* to name/type and check if I've already created such an entry using the type map) .filter(kv -> !column_lookups_pretypes .containsKey(kv.getKey().either(s -> s, t2 -> Tuples._2T(t2._1(), kv.getValue())))) .flatMap(kv -> createFieldIncludeLookups(Stream.of(kv.getKey().toString()), __ -> kv.getKey().<Either<String, Tuple2<String, String>>>either(s -> Either.left(s), t2 -> Either.right(Tuples._2T(t2._1(), kv.getValue()))), field_lookups, default_not_analyzed, default_analyzed, false, search_index_schema_override, type_override, mapper, index_type)) .collect(Collectors.toMap(t2 -> t2._1(), t2 -> t2._2(), (v1, v2) -> v1, () -> new LinkedHashMap<Either<String, Tuple2<String, String>>, JsonNode>())); final LinkedHashMap<Either<String, Tuple2<String, String>>, JsonNode> column_lookups = Stream .concat(column_lookups_pretypes.entrySet().stream(), column_lookups_types.entrySet().stream()) .sorted((a, b) -> Integer.compare(sortKey(a.getKey()), sortKey(b.getKey()))) .collect(Collectors.toMap(t2 -> t2.getKey(), t2 -> t2.getValue(), (v1, v2) -> v1, () -> new LinkedHashMap<Either<String, Tuple2<String, String>>, JsonNode>())); final XContentBuilder properties = column_lookups.entrySet().stream() // properties not dynamic_templates .filter(kv -> kv.getKey().isLeft()) // overwrite with version built using columns if it exists .map(kv -> Tuples._2T(kv.getKey(), column_lookups.getOrDefault(kv.getKey(), kv.getValue()))) .reduce(Optional.of(start.startObject("properties")) // add doc_schema if it exists .map(props -> doc_schema .map(ds -> Optionals.streamOf(ds.fields(), false) .reduce(props, Lambdas.wrap_u((acc, kv) -> acc.rawField(kv.getKey(), kv.getValue().toString().getBytes())), (acc1, acc2) -> acc1 // shouldn't be possible )).orElse(props)).get(), Lambdas.wrap_u((acc, t2) -> acc.rawField(t2._1().left().value(), t2._2().toString().getBytes())), // (left by construction) (acc1, acc2) -> acc1) // (not actually possible) .endObject(); final XContentBuilder templates = column_lookups.entrySet().stream() // properties not dynamic_templates .filter(kv -> kv.getKey().isRight()) // overwrite with version built using columns if it exists .map(kv -> Tuples._2T(kv.getKey(), column_lookups.getOrDefault(kv.getKey(), kv.getValue()))) .reduce(properties.startArray("dynamic_templates"), Lambdas.wrap_u((acc, t2) -> acc.startObject() .rawField(getFieldNameFromMatchPair(t2._1().right().value()), t2._2().toString().getBytes()) // (right by construction) .endObject()), (acc1, acc2) -> acc1) // (not actually possible) .endArray(); return templates; } catch (IOException e) { //Handle in-practice-impossible "IOException" return null; } }
From source file:software.coolstuff.springframework.owncloud.service.impl.rest.OwncloudRestResourceServiceImpl.java
@Override public OwncloudResource createDirectory(URI directory) { Optional<OwncloudResource> existingDirectory = find(directory); if (existingDirectory.isPresent()) { return existingDirectory.filter(OwncloudUtils::isDirectory) .orElseThrow(() -> new OwncloudNoDirectoryResourceException(directory)); }/*from www .j a v a 2s .co m*/ return createNonExistingDirectory(directory); }
From source file:alfio.controller.api.user.RestEventApiController.java
@RequestMapping("events/{shortName}") public ResponseEntity<PublicEvent> showEvent(@PathVariable("shortName") String shortName, @RequestParam(value = "specialCode", required = false) String specialCodeParam, HttpServletRequest request) {//w w w. j a va 2s.c o m Optional<SpecialPrice> specialCode = Optional.ofNullable(StringUtils.trimToNull(specialCodeParam)) .flatMap((trimmedCode) -> specialPriceRepository.getByCode(trimmedCode)); return eventRepository.findOptionalByShortName(shortName).map((e) -> { List<PublicCategory> categories = ticketCategoryRepository.findAllTicketCategories(e.getId()).stream() .filter((c) -> !c.isAccessRestricted() || (specialCode.filter(sc -> sc.getTicketCategoryId() == c.getId()).isPresent())) .map(c -> buildPublicCategory(c, e)).collect(Collectors.toList()); Organization organization = organizationRepository.getById(e.getOrganizationId()); return new ResponseEntity<>(new PublicEvent(e, request.getContextPath(), descriptionsLoader.eventDescriptions(), categories, organization), HttpStatus.OK); }).orElseGet(() -> new ResponseEntity<>(HttpStatus.NOT_FOUND)); }
From source file:software.coolstuff.springframework.owncloud.service.impl.rest.OwncloudRestResourceServiceImpl.java
@Override public OutputStream getOutputStream(URI path, MediaType mediaType) { Optional<OwncloudResource> optionalExistingFile = find(path); if (optionalExistingFile.isPresent()) { OwncloudFileResource existingFile = optionalExistingFile.filter(OwncloudUtils::isNotDirectory) .map(OwncloudUtils::toOwncloudFileResource) .orElseThrow(() -> new OwncloudNoFileResourceException(path)); return getOutputStream(existingFile); }/*from w ww . j av a2s . co m*/ OwncloudFileResource resource = OwncloudRestFileResourceImpl.fileBuilder() .owncloudResource(OwncloudRestResourceImpl.builder().href(path).mediaType(mediaType).build()) .build(); return getOutputStream(resource); }
From source file:alfio.manager.system.DataMigrator.java
private void migrateEventToCurrentVersion(Event event) { Optional<EventMigration> optional = optionally( () -> eventMigrationRepository.loadEventMigration(event.getId())); boolean alreadyDefined = optional.isPresent(); if (!alreadyDefined || optional.filter(this::needsFixing).isPresent()) { transactionTemplate.execute(s -> { //optional.ifPresent(eventMigration -> eventMigrationRepository.lockEventMigrationForUpdate(eventMigration.getId())); if (ZonedDateTime.now(event.getZoneId()).isBefore(event.getEnd())) { fixAvailableSeats(event); fillDescriptions(event); fixCategoriesSize(event); }/*w w w . j av a2 s.com*/ //migrate prices to new structure. This should be done for all events, regardless of the expiration date. migratePrices(event.getId()); fixStuckTickets(event.getId()); if (alreadyDefined) { EventMigration eventMigration = optional.get(); int result = eventMigrationRepository.updateMigrationData(eventMigration.getId(), currentVersionAsString, buildTimestamp, EventMigration.Status.COMPLETE.name()); Validate.isTrue(result == 1, "error during update " + result); } else { eventMigrationRepository.insertMigrationData(event.getId(), currentVersionAsString, buildTimestamp, EventMigration.Status.COMPLETE.name()); } return null; }); } }
From source file:com.ikanow.aleph2.analytics.services.AnalyticsContext.java
/** Util to check if we're using a ping pong buffer to change over data "atomically" * Either for a transient job or the entire bucket * Note that for the global outputs, there can be only setting so we read from the bucket * @param job - if this is not present or isn't a transient job then this is global * @return//w w w .j a va 2 s .co m */ protected static boolean needPingPongBuffer(final DataBucketBean bucket, final Optional<AnalyticThreadJobBean> job) { final boolean need_ping_pong_buffer = job .filter(j -> Optionals.of(() -> j.output().is_transient()).orElse(false)) // only transients .map(j -> !Optionals.of(() -> j.output().preserve_existing_data()).orElse(false) && _batch_types .contains(Optional.ofNullable(j.analytic_type()).orElse(MasterEnrichmentType.none))) .orElseGet(() -> { // This is the bucket case ... if there are any batch jobs that don't preserve existing data return Optionals.of(() -> bucket.analytic_thread().jobs()).orElse(Collections.emptyList()) .stream().filter(j -> !Optionals.of(() -> j.output().is_transient()).orElse(false)) // not transient .filter(j -> Optional.ofNullable(j.enabled()).orElse(true)) // enabled .filter(j -> _batch_types.contains( Optional.ofNullable(j.analytic_type()).orElse(MasterEnrichmentType.none))) // batch .filter(j -> !Optionals.of(() -> j.output().preserve_existing_data()).orElse(false)) // not preserving data .findFirst().isPresent(); }); return need_ping_pong_buffer; }
From source file:alfio.controller.ReservationController.java
@RequestMapping(value = "/event/{eventName}/reservation/{reservationId}/success", method = RequestMethod.GET) public String showConfirmationPage(@PathVariable("eventName") String eventName, @PathVariable("reservationId") String reservationId, @RequestParam(value = "confirmation-email-sent", required = false, defaultValue = "false") boolean confirmationEmailSent, @RequestParam(value = "ticket-email-sent", required = false, defaultValue = "false") boolean ticketEmailSent, Model model, Locale locale, HttpServletRequest request) { return eventRepository.findOptionalByShortName(eventName).map(ev -> { Optional<TicketReservation> tr = ticketReservationManager.findById(reservationId); return tr.filter(r -> r.getStatus() == TicketReservationStatus.COMPLETE).map(reservation -> { SessionUtil.removeSpecialPriceData(request); model.addAttribute("reservationId", reservationId); model.addAttribute("reservation", reservation); model.addAttribute("confirmationEmailSent", confirmationEmailSent); model.addAttribute("ticketEmailSent", ticketEmailSent); List<Ticket> tickets = ticketReservationManager.findTicketsInReservation(reservationId); List<Triple<AdditionalService, List<AdditionalServiceText>, AdditionalServiceItem>> additionalServices = ticketReservationManager .findAdditionalServicesInReservation(reservationId).stream() .map(t -> Triple.of( t.getLeft(), t.getMiddle().stream() .filter(d -> d.getLocale().equals(locale.getLanguage())).collect(toList()), t.getRight())) .collect(Collectors.toList()); boolean hasPaidSupplement = ticketReservationManager.hasPaidSupplements(reservationId); model.addAttribute("ticketsByCategory", tickets.stream() .collect(Collectors.groupingBy(Ticket::getCategoryId)).entrySet().stream().map((e) -> { TicketCategory category = eventManager.getTicketCategoryById(e.getKey(), ev.getId()); List<TicketDecorator> decorators = TicketDecorator .decorate(e.getValue(), !hasPaidSupplement && configurationManager.getBooleanConfigValue( Configuration.from(ev.getOrganizationId(), ev.getId(), category.getId(), ALLOW_FREE_TICKETS_CANCELLATION), false), eventManager.checkTicketCancellationPrerequisites(), ticket -> ticketHelper.findTicketFieldConfigurationAndValue(ev.getId(), ticket, locale), tickets.size() == 1, TicketDecorator.EMPTY_PREFIX_GENERATOR); return Pair.of(category, decorators); }).collect(toList())); boolean ticketsAllAssigned = tickets.stream().allMatch(Ticket::getAssigned); model.addAttribute("ticketsAreAllAssigned", ticketsAllAssigned); model.addAttribute("collapseEnabled", tickets.size() > 1 && !ticketsAllAssigned); model.addAttribute("additionalServicesOnly", tickets.isEmpty() && !additionalServices.isEmpty()); model.addAttribute("additionalServices", additionalServices); model.addAttribute("countries", TicketHelper.getLocalizedCountries(locale)); model.addAttribute("pageTitle", "reservation-page-complete.header.title"); model.addAttribute("event", ev); model.addAttribute("useFirstAndLastName", ev.mustUseFirstAndLastName()); model.asMap().putIfAbsent("validationResult", ValidationResult.success()); return "/event/reservation-page-complete"; }).orElseGet(() -> redirectReservation(tr, eventName, reservationId)); }).orElse("redirect:/"); }
From source file:com.ikanow.aleph2.analytics.services.AnalyticsContext.java
/** Utility to grab a generic data service (top level) - underlying version * @param context/*from w ww . j a va 2 s . c om*/ * @param service_type * @param service_name * @return */ protected static Optional<? extends IUnderlyingService> getUnderlyingService(final IServiceContext context, final String service_type, final Optional<String> service_name) { return DataServiceUtils.getUnderlyingServiceInterface(service_type) .flatMap(ds -> context.getService(ds, service_name.filter(s -> !s.isEmpty()))); }