Example usage for java.time ZonedDateTime now

List of usage examples for java.time ZonedDateTime now

Introduction

In this page you can find the example usage for java.time ZonedDateTime now.

Prototype

public static ZonedDateTime now(Clock clock) 

Source Link

Document

Obtains the current date-time from the specified clock.

Usage

From source file:alfio.manager.EventManagerIntegrationTest.java

@Test
public void testNewRestrictedCategory() {
    Pair<Event, String> eventAndUser = generateAndEditEvent(AVAILABLE_SEATS + 10);
    //now we have 20 free seats, 10 of which RELEASED
    Event event = eventAndUser.getLeft();
    String username = eventAndUser.getRight();
    TicketCategoryModification tcm = new TicketCategoryModification(null, "additional", 20,
            DateTimeModification.fromZonedDateTime(ZonedDateTime.now(event.getZoneId()).minusMinutes(1)),
            DateTimeModification.fromZonedDateTime(ZonedDateTime.now(event.getZoneId()).plusDays(5)),
            Collections.emptyMap(), BigDecimal.TEN, true, "", true, null, null, null, null, null);
    Result<Integer> result = eventManager.insertCategory(event, tcm, username);
    assertTrue(result.isSuccess());//from  w  w w.  j  av  a 2  s  .com
    assertEquals(20, ticketRepository.countFreeTickets(event.getId(), result.getData()).intValue());
}

From source file:com.example.app.profile.model.ProfileDAO.java

/**
 * Get a list of Users that have a Membership to the given Profile that has the given MembershipOperation
 *
 * @param profile the Profile//from  w  w w  .  ja v a2  s  .c  o  m
 * @param operation the Operation
 * @param timeZone the timezone.
 *
 * @return list of Users
 */
public List<User> getUsersWithOperation(@Nonnull Profile profile, TimeZone timeZone,
        @Nonnull MembershipOperation operation) {
    ZonedDateTime now = ZonedDateTime.now(timeZone.toZoneId());
    return getUsersWithOperation(profile, operation, now, now);
}

From source file:alfio.manager.TicketReservationManager.java

private void acquireItems(TicketStatus ticketStatus, AdditionalServiceItemStatus asStatus,
        PaymentProxy paymentProxy, String reservationId, String email, CustomerName customerName,
        String userLanguage, String billingAddress, int eventId) {
    Map<Integer, Ticket> preUpdateTicket = ticketRepository.findTicketsInReservation(reservationId).stream()
            .collect(toMap(Ticket::getId, Function.identity()));
    int updatedTickets = ticketRepository.updateTicketsStatusWithReservationId(reservationId,
            ticketStatus.toString());//from  w  ww .j  a va  2  s  .  c  o  m
    Map<Integer, Ticket> postUpdateTicket = ticketRepository.findTicketsInReservation(reservationId).stream()
            .collect(toMap(Ticket::getId, Function.identity()));

    postUpdateTicket.forEach((id, ticket) -> {
        auditUpdateTicket(preUpdateTicket.get(id), Collections.emptyMap(), ticket, Collections.emptyMap(),
                eventId);
    });

    int updatedAS = additionalServiceItemRepository.updateItemsStatusWithReservationUUID(reservationId,
            asStatus);
    Validate.isTrue(updatedTickets + updatedAS > 0, "no items have been updated");
    specialPriceRepository.updateStatusForReservation(singletonList(reservationId), Status.TAKEN.toString());
    ZonedDateTime timestamp = ZonedDateTime.now(ZoneId.of("UTC"));
    int updatedReservation = ticketReservationRepository.updateTicketReservation(reservationId,
            TicketReservationStatus.COMPLETE.toString(), email, customerName.getFullName(),
            customerName.getFirstName(), customerName.getLastName(), userLanguage, billingAddress, timestamp,
            paymentProxy.toString());
    Validate.isTrue(updatedReservation == 1,
            "expected exactly one updated reservation, got " + updatedReservation);
    waitingQueueManager.fireReservationConfirmed(reservationId);
    if (paymentProxy == PaymentProxy.PAYPAL || paymentProxy == PaymentProxy.ADMIN) {
        //we must notify the plugins about ticket assignment and send them by email
        Event event = eventRepository.findByReservationId(reservationId);
        TicketReservation reservation = findById(reservationId).orElseThrow(IllegalStateException::new);
        findTicketsInReservation(reservationId).stream()
                .filter(ticket -> StringUtils.isNotBlank(ticket.getFullName())
                        || StringUtils.isNotBlank(ticket.getFirstName())
                        || StringUtils.isNotBlank(ticket.getEmail()))
                .forEach(ticket -> {
                    Locale locale = Locale.forLanguageTag(ticket.getUserLanguage());
                    if (paymentProxy == PaymentProxy.PAYPAL) {
                        sendTicketByEmail(ticket, locale, event,
                                getTicketEmailGenerator(event, reservation, locale));
                    }
                    pluginManager.handleTicketAssignment(ticket);
                    extensionManager.handleTicketAssignment(ticket);
                });

    }
}

From source file:alfio.manager.EventManager.java

void handleTicketNumberModification(Event event, TicketCategory original, TicketCategory updated,
        int addedTickets, boolean resetToFree) {
    if (addedTickets == 0) {
        log.debug("ticket handling not required since the number of ticket wasn't modified");
        return;//from www  . j av a 2 s .com
    }

    log.debug("modification detected in ticket number. The difference is: {}", addedTickets);

    if (addedTickets > 0) {
        //the updated category contains more tickets than the older one
        List<Integer> lockedTickets = ticketRepository.selectNotAllocatedTicketsForUpdate(event.getId(),
                addedTickets, asList(TicketStatus.FREE.name(), TicketStatus.RELEASED.name()));
        Validate.isTrue(addedTickets == lockedTickets.size(),
                "Cannot add %d tickets. There are only %d free tickets.", addedTickets, lockedTickets.size());
        jdbc.batchUpdate(ticketRepository.bulkTicketUpdate(),
                lockedTickets.stream()
                        .map(id -> new MapSqlParameterSource("id", id).addValue("categoryId", updated.getId())
                                .addValue("srcPriceCts", updated.getSrcPriceCts()))
                        .toArray(MapSqlParameterSource[]::new));
        if (updated.isAccessRestricted()) {
            //since the updated category is not public, the tickets shouldn't be distributed to waiting people.
            ticketRepository.revertToFree(event.getId(), updated.getId(), lockedTickets);
        } else if (!resetToFree) {
            ticketRepository.resetTickets(lockedTickets);
        }

    } else {
        int absDifference = Math.abs(addedTickets);
        final List<Integer> ids = ticketRepository.lockTicketsToInvalidate(event.getId(), updated.getId(),
                absDifference);
        int actualDifference = ids.size();
        if (actualDifference < absDifference) {
            throw new IllegalStateException("Cannot invalidate " + absDifference + " tickets. There are only "
                    + actualDifference + " free tickets");
        }
        ticketRepository.invalidateTickets(ids);
        final MapSqlParameterSource[] params = generateEmptyTickets(event,
                Date.from(ZonedDateTime.now(event.getZoneId()).toInstant()), absDifference,
                TicketStatus.RELEASED).toArray(MapSqlParameterSource[]::new);
        jdbc.batchUpdate(ticketRepository.bulkTicketInitialization(), params);
    }
}

From source file:alfio.manager.EventManager.java

private void createAllTicketsForEvent(Event event, EventModification em) {
    final MapSqlParameterSource[] params = prepareTicketsBulkInsertParameters(
            ZonedDateTime.now(event.getZoneId()), event, em.getAvailableSeats(), TicketStatus.FREE);
    jdbc.batchUpdate(ticketRepository.bulkTicketInitialization(), params);
}

From source file:alfio.manager.EventManager.java

private Stream<Event> getActiveEventsStream() {
    return eventRepository.findAll().stream().filter(e -> e.getEnd().truncatedTo(ChronoUnit.DAYS).plusDays(1)
            .isAfter(ZonedDateTime.now(e.getZoneId()).truncatedTo(ChronoUnit.DAYS)));
}

From source file:alfio.manager.TicketReservationManager.java

private static Predicate<TicketReservation> notificationNotSent(ZoneId eventZoneId, int quietPeriod) {
    return r -> r.latestNotificationTimestamp(eventZoneId).map(t -> t.truncatedTo(ChronoUnit.DAYS)
            .plusDays(quietPeriod).isBefore(ZonedDateTime.now(eventZoneId).truncatedTo(ChronoUnit.DAYS)))
            .orElse(true);//from   www  .  j  av  a 2  s  . c o  m
}

From source file:org.wso2.carbon.apimgt.core.impl.APIPublisherImpl.java

/**
 * Delete an API//from   www.j a  va2  s  .c o m
 *
 * @param identifier UUID of the API.
 * @throws APIManagementException if failed to remove the API
 */
@Override
public void deleteAPI(String identifier) throws APIManagementException {
    APIGateway gateway = getApiGateway();
    try {
        if (getAPISubscriptionCountByAPI(identifier) == 0) {
            API api = getAPIbyUUID(identifier);
            if (api != null) {
                //Checks whether the user has required permissions to delete the API
                verifyUserPermissionsToDeleteAPI(getUsername(), api);
                String apiWfStatus = api.getWorkflowStatus();
                API.APIBuilder apiBuilder = new API.APIBuilder(api);

                //Delete API in gateway

                gateway.deleteAPI(api);
                if (log.isDebugEnabled()) {
                    log.debug("API : " + api.getName() + " has been successfully removed from the gateway");
                }

                getApiDAO().deleteAPI(identifier);
                getApiLifecycleManager().removeLifecycle(apiBuilder.getLifecycleInstanceId());
                APIUtils.logDebug("API with id " + identifier + " was deleted successfully.", log);

                if (APILCWorkflowStatus.PENDING.toString().equals(apiWfStatus)) {
                    cleanupPendingTaskForAPIStateChange(identifier);
                }
                // 'API_M Functions' related code
                //Create a payload with event specific details
                Map<String, String> eventPayload = new HashMap<>();
                eventPayload.put(APIMgtConstants.FunctionsConstants.API_ID, api.getId());
                eventPayload.put(APIMgtConstants.FunctionsConstants.API_NAME, api.getName());
                eventPayload.put(APIMgtConstants.FunctionsConstants.API_VERSION, api.getVersion());
                eventPayload.put(APIMgtConstants.FunctionsConstants.API_PROVIDER, api.getProvider());
                eventPayload.put(APIMgtConstants.FunctionsConstants.API_DESCRIPTION, api.getDescription());
                // This will notify all the EventObservers(Asynchronous)
                ObserverNotifier observerNotifier = new ObserverNotifier(Event.API_DELETION, getUsername(),
                        ZonedDateTime.now(ZoneOffset.UTC), eventPayload, this);
                ObserverNotifierThreadPool.getInstance().executeTask(observerNotifier);
            }
        } else {
            throw new ApiDeleteFailureException("API with " + identifier + " already have subscriptions");
        }
    } catch (APIMgtDAOException e) {
        String errorMsg = "Error occurred while deleting the API with id " + identifier;
        log.error(errorMsg, e);
        throw new APIManagementException(errorMsg, e, e.getErrorHandler());
    } catch (LifecycleException e) {
        String errorMsg = "Error occurred while Disassociating the API with Lifecycle id " + identifier;
        log.error(errorMsg, e);
        throw new APIManagementException(errorMsg, e, ExceptionCodes.APIMGT_LIFECYCLE_EXCEPTION);
    } catch (GatewayException e) {
        String message = "Error occurred while deleting API with id - " + identifier + " from gateway";
        log.error(message, e);
        throw new APIManagementException(message, ExceptionCodes.GATEWAY_EXCEPTION);
    }
}

From source file:alfio.manager.TicketReservationManager.java

public void updateTicketOwner(Ticket ticket, Locale locale, Event event,
        UpdateTicketOwnerForm updateTicketOwner, PartialTicketTextGenerator confirmationTextBuilder,
        PartialTicketTextGenerator ownerChangeTextBuilder, Optional<UserDetails> userDetails) {

    Ticket preUpdateTicket = ticketRepository.findByUUID(ticket.getUuid());
    Map<String, String> preUpdateTicketFields = ticketFieldRepository.findAllByTicketId(ticket.getId()).stream()
            .collect(Collectors.toMap(TicketFieldValue::getName, TicketFieldValue::getValue));

    String newEmail = updateTicketOwner.getEmail().trim();
    CustomerName customerName = new CustomerName(updateTicketOwner.getFullName(),
            updateTicketOwner.getFirstName(), updateTicketOwner.getLastName(), event);
    ticketRepository.updateTicketOwner(ticket.getUuid(), newEmail, customerName.getFullName(),
            customerName.getFirstName(), customerName.getLastName());

    ////from   w  w w.  j  a v a 2 s. com
    Locale userLocale = Optional.ofNullable(StringUtils.trimToNull(updateTicketOwner.getUserLanguage()))
            .map(Locale::forLanguageTag).orElse(locale);

    ticketRepository.updateOptionalTicketInfo(ticket.getUuid(), userLocale.getLanguage());
    ticketFieldRepository.updateOrInsert(updateTicketOwner.getAdditional(), ticket.getId(), event.getId());

    Ticket newTicket = ticketRepository.findByUUID(ticket.getUuid());
    if (newTicket.getStatus() == TicketStatus.ACQUIRED
            && (!StringUtils.equalsIgnoreCase(newEmail, ticket.getEmail())
                    || !StringUtils.equalsIgnoreCase(customerName.getFullName(), ticket.getFullName()))) {
        sendTicketByEmail(newTicket, userLocale, event, confirmationTextBuilder);
    }

    boolean admin = isAdmin(userDetails);

    if (!admin && StringUtils.isNotBlank(ticket.getEmail())
            && !StringUtils.equalsIgnoreCase(newEmail, ticket.getEmail())
            && ticket.getStatus() == TicketStatus.ACQUIRED) {
        Locale oldUserLocale = Locale.forLanguageTag(ticket.getUserLanguage());
        String subject = messageSource.getMessage("ticket-has-changed-owner-subject",
                new Object[] { event.getDisplayName() }, oldUserLocale);
        notificationManager.sendSimpleEmail(event, ticket.getEmail(), subject,
                () -> ownerChangeTextBuilder.generate(newTicket));
        if (event.getBegin().isBefore(ZonedDateTime.now(event.getZoneId()))) {
            Organization organization = organizationRepository.getById(event.getOrganizationId());
            notificationManager.sendSimpleEmail(event, organization.getEmail(),
                    "WARNING: Ticket has been reassigned after event start",
                    () -> ownerChangeTextBuilder.generate(newTicket));
        }
    }

    if (admin) {
        TicketReservation reservation = findById(ticket.getTicketsReservationId())
                .orElseThrow(IllegalStateException::new);
        //if the current user is admin, then it would be good to update also the name of the Reservation Owner
        String username = userDetails.get().getUsername();
        log.warn("Reservation {}: forced assignee replacement old: {} new: {}", reservation.getId(),
                reservation.getFullName(), username);
        ticketReservationRepository.updateAssignee(reservation.getId(), username);
    }
    pluginManager.handleTicketAssignment(newTicket);

    Ticket postUpdateTicket = ticketRepository.findByUUID(ticket.getUuid());
    Map<String, String> postUpdateTicketFields = ticketFieldRepository.findAllByTicketId(ticket.getId())
            .stream().collect(Collectors.toMap(TicketFieldValue::getName, TicketFieldValue::getValue));

    auditUpdateTicket(preUpdateTicket, preUpdateTicketFields, postUpdateTicket, postUpdateTicketFields,
            event.getId());
}

From source file:alfio.manager.TicketReservationManager.java

void sendReminderForOfflinePaymentsToEventManagers() {
    eventRepository.findAllActives(ZonedDateTime.now(Clock.systemUTC())).stream().filter(event -> {
        ZonedDateTime dateTimeForEvent = ZonedDateTime.now(event.getZoneId());
        return dateTimeForEvent.truncatedTo(ChronoUnit.HOURS).getHour() == 5; //only for the events at 5:00 local time
    }).forEachOrdered(event -> {//  ww w  .  j  av a  2 s  .  c om
        ZonedDateTime dateTimeForEvent = ZonedDateTime.now(event.getZoneId()).truncatedTo(ChronoUnit.DAYS)
                .plusDays(1);
        List<TicketReservationInfo> reservations = ticketReservationRepository
                .findAllOfflinePaymentReservationWithExpirationBefore(dateTimeForEvent, event.getId());
        log.info("for event {} there are {} pending offline payments to handle", event.getId(),
                reservations.size());
        if (!reservations.isEmpty()) {
            Organization organization = organizationRepository.getById(event.getOrganizationId());
            List<String> cc = notificationManager.getCCForEventOrganizer(event);
            String subject = String.format(
                    "There are %d pending offline payments that will expire in event: %s", reservations.size(),
                    event.getDisplayName());
            String baseUrl = configurationManager
                    .getRequiredValue(Configuration.from(event.getOrganizationId(), event.getId(), BASE_URL));
            Map<String, Object> model = TemplateResource
                    .prepareModelForOfflineReservationExpiringEmailForOrganizer(event, reservations, baseUrl);
            notificationManager.sendSimpleEmail(event, organization.getEmail(), cc, subject,
                    () -> templateManager.renderTemplate(event,
                            TemplateResource.OFFLINE_RESERVATION_EXPIRING_EMAIL_FOR_ORGANIZER, model,
                            Locale.ENGLISH));
            extensionManager.handleOfflineReservationsWillExpire(event, reservations);
        }
    });
}