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.NotificationManager.java

void sendWaitingMessages() {
    Date now = new Date();
    eventRepository.findAllActiveIds(ZonedDateTime.now(UTC)).stream()
            .flatMap(id -> emailMessageRepository.loadIdsWaitingForProcessing(id, now).stream()).distinct()
            .forEach(this::processMessage);
}

From source file:alfio.manager.EventManager.java

public void updateEventPrices(Event original, EventModification em, String username) {
    checkOwnership(original, username, em.getOrganizationId());
    int eventId = original.getId();
    int seatsDifference = em.getAvailableSeats() - eventRepository.countExistingTickets(original.getId());
    if (seatsDifference < 0) {
        int allocatedSeats = ticketCategoryRepository.findByEventId(original.getId()).stream()
                .filter(TicketCategory::isBounded).mapToInt(TicketCategory::getMaxTickets).sum();
        if (em.getAvailableSeats() < allocatedSeats) {
            throw new IllegalArgumentException(format(
                    "cannot reduce max tickets to %d. There are already %d tickets allocated. Try updating categories first.",
                    em.getAvailableSeats(), allocatedSeats));
        }//from   w  w  w  .  j av  a 2 s .  c o  m
    }

    String paymentProxies = collectPaymentProxies(em);
    BigDecimal vat = em.isFreeOfCharge() ? BigDecimal.ZERO : em.getVatPercentage();
    eventRepository.updatePrices(em.getCurrency(), em.getAvailableSeats(), em.isVatIncluded(), vat,
            paymentProxies, eventId, em.getVatStatus(), em.getPriceInCents());
    if (seatsDifference != 0) {
        Event modified = eventRepository.findById(eventId);
        if (seatsDifference > 0) {
            final MapSqlParameterSource[] params = generateEmptyTickets(modified,
                    Date.from(ZonedDateTime.now(modified.getZoneId()).toInstant()), seatsDifference,
                    TicketStatus.RELEASED).toArray(MapSqlParameterSource[]::new);
            jdbc.batchUpdate(ticketRepository.bulkTicketInitialization(), params);
        } else {
            List<Integer> ids = ticketRepository.selectNotAllocatedTicketsForUpdate(eventId,
                    Math.abs(seatsDifference), singletonList(TicketStatus.FREE.name()));
            Validate.isTrue(ids.size() == Math.abs(seatsDifference),
                    "cannot lock enough tickets for deletion.");
            int invalidatedTickets = ticketRepository.invalidateTickets(ids);
            Validate.isTrue(ids.size() == invalidatedTickets, String.format(
                    "error during ticket invalidation: expected %d, got %d", ids.size(), invalidatedTickets));
        }
    }
}

From source file:alfio.manager.NotificationManager.java

private void sendMessage(EmailMessage message) {
    Event event = eventRepository.findById(message.getEventId());
    mailer.send(event, message.getRecipient(), message.getCc(), message.getSubject(), message.getMessage(),
            Optional.empty(), decodeAttachments(message.getAttachments()));
    emailMessageRepository.updateStatusToSent(message.getEventId(), message.getChecksum(),
            ZonedDateTime.now(UTC), Collections.singletonList(IN_PROCESS.name()));
}

From source file:nu.yona.server.analysis.service.ActivityServiceTest.java

@Test
public void getUserDayActivityOverviews_noActivityPresent_resultsWithInactivity() {
    ZonedDateTime today = getDayStartTime(ZonedDateTime.now(userAnonZone));

    Page<DayActivityOverviewDto<DayActivityDto>> inactivityDayOverviews = service
            .getUserDayActivityOverviews(userId, new PageRequest(0, 3));

    // because the gambling goal was added with creation date two weeks ago, there are multiple days
    assertThat(inactivityDayOverviews.getNumberOfElements(), equalTo(3));
    // the other goals were created today, so get the most recent (first) element
    DayActivityOverviewDto<DayActivityDto> inactivityDayOverview = inactivityDayOverviews.getContent().get(0);
    assertThat(inactivityDayOverview.getDayActivities().size(), equalTo(userAnonEntity.getGoals().size()));
    DayActivityDto inactivityDayForGambling = inactivityDayOverview.getDayActivities().stream()
            .filter(a -> a.getGoalId().equals(gamblingGoal.getId())).findAny().get();
    assertThat(inactivityDayForGambling.getStartTime(), equalTo(today));
    assertThat(inactivityDayForGambling.getTotalActivityDurationMinutes().get(), equalTo(0));
    assertThat(inactivityDayForGambling.getTotalMinutesBeyondGoal(), equalTo(0));
}

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

/**
 * Adds a new API to the system//  w w w  .  j ava2  s  .  com
 *
 * @param apiBuilder API model object
 * @return UUID of the added API.
 * @throws APIManagementException if failed to add API
 */
@Override
public String addAPI(API.APIBuilder apiBuilder) throws APIManagementException {

    API createdAPI;
    APIGateway gateway = getApiGateway();

    apiBuilder.provider(getUsername());
    if (StringUtils.isEmpty(apiBuilder.getId())) {
        apiBuilder.id(UUID.randomUUID().toString());
    }

    LocalDateTime localDateTime = LocalDateTime.now();
    apiBuilder.createdTime(localDateTime);
    apiBuilder.lastUpdatedTime(localDateTime);
    apiBuilder.createdBy(getUsername());
    apiBuilder.updatedBy(getUsername());
    if (apiBuilder.getLabels().isEmpty()) {
        Set<String> labelSet = new HashSet<>();
        labelSet.add(APIMgtConstants.DEFAULT_LABEL_NAME);
        apiBuilder.labels(labelSet);
    }
    Map<String, Endpoint> apiEndpointMap = apiBuilder.getEndpoint();
    validateEndpoints(apiEndpointMap, false);
    try {
        if (!isApiNameExist(apiBuilder.getName()) && !isContextExist(apiBuilder.getContext())) {
            LifecycleState lifecycleState = getApiLifecycleManager().addLifecycle(APIMgtConstants.API_LIFECYCLE,
                    getUsername());
            apiBuilder.associateLifecycle(lifecycleState);

            createUriTemplateList(apiBuilder, false);

            List<UriTemplate> list = new ArrayList<>(apiBuilder.getUriTemplates().values());
            List<TemplateBuilderDTO> resourceList = new ArrayList<>();

            validateApiPolicy(apiBuilder.getApiPolicy());
            validateSubscriptionPolicies(apiBuilder);
            for (UriTemplate uriTemplate : list) {
                TemplateBuilderDTO dto = new TemplateBuilderDTO();
                dto.setTemplateId(uriTemplate.getTemplateId());
                dto.setUriTemplate(uriTemplate.getUriTemplate());
                dto.setHttpVerb(uriTemplate.getHttpVerb());
                Map<String, Endpoint> map = uriTemplate.getEndpoint();
                if (map.containsKey(APIMgtConstants.PRODUCTION_ENDPOINT)) {
                    Endpoint endpoint = map.get(APIMgtConstants.PRODUCTION_ENDPOINT);
                    dto.setProductionEndpoint(endpoint);
                }
                if (map.containsKey(APIMgtConstants.SANDBOX_ENDPOINT)) {
                    Endpoint endpoint = map.get(APIMgtConstants.SANDBOX_ENDPOINT);
                    dto.setSandboxEndpoint(endpoint);
                }
                resourceList.add(dto);
            }
            GatewaySourceGenerator gatewaySourceGenerator = getGatewaySourceGenerator();
            APIConfigContext apiConfigContext = new APIConfigContext(apiBuilder.build(),
                    config.getGatewayPackageName());
            gatewaySourceGenerator.setApiConfigContext(apiConfigContext);
            String gatewayConfig = gatewaySourceGenerator.getConfigStringFromTemplate(resourceList);
            if (log.isDebugEnabled()) {
                log.debug("API " + apiBuilder.getName() + "gateway config: " + gatewayConfig);
            }
            apiBuilder.gatewayConfig(gatewayConfig);

            if (StringUtils.isEmpty(apiBuilder.getApiDefinition())) {
                apiBuilder.apiDefinition(apiDefinitionFromSwagger20.generateSwaggerFromResources(apiBuilder));
            }
            if (!StringUtils.isEmpty(apiBuilder.getApiPermission())) {
                Map<String, Integer> roleNamePermissionList;
                roleNamePermissionList = getAPIPermissionArray(apiBuilder.getApiPermission());
                apiBuilder.permissionMap(roleNamePermissionList);
            }

            createdAPI = apiBuilder.build();
            APIUtils.validate(createdAPI);

            //Add API to gateway
            gateway.addAPI(createdAPI);
            if (log.isDebugEnabled()) {
                log.debug("API : " + apiBuilder.getName() + " has been identifier published to gateway");
            }

            Set<String> apiRoleList;

            //if the API has public visibility, add the API without any role checking
            //if the API has role based visibility, add the API with role checking
            if (API.Visibility.PUBLIC == createdAPI.getVisibility()) {
                getApiDAO().addAPI(createdAPI);
            } else if (API.Visibility.RESTRICTED == createdAPI.getVisibility()) {
                //get all the roles in the system
                Set<String> allAvailableRoles = APIUtils.getAllAvailableRoles();
                //get the roles needed to be associated with the API
                apiRoleList = createdAPI.getVisibleRoles();
                if (APIUtils.checkAllowedRoles(allAvailableRoles, apiRoleList)) {
                    getApiDAO().addAPI(createdAPI);
                }
            }

            APIUtils.logDebug("API " + createdAPI.getName() + "-" + createdAPI.getVersion() + " was created "
                    + "successfully.", log);

            // 'API_M Functions' related code
            //Create a payload with event specific details
            Map<String, String> eventPayload = new HashMap<>();
            eventPayload.put(APIMgtConstants.FunctionsConstants.API_ID, createdAPI.getId());
            eventPayload.put(APIMgtConstants.FunctionsConstants.API_NAME, createdAPI.getName());
            eventPayload.put(APIMgtConstants.FunctionsConstants.API_VERSION, createdAPI.getVersion());
            eventPayload.put(APIMgtConstants.FunctionsConstants.API_DESCRIPTION, createdAPI.getDescription());
            eventPayload.put(APIMgtConstants.FunctionsConstants.API_CONTEXT, createdAPI.getContext());
            eventPayload.put(APIMgtConstants.FunctionsConstants.API_LC_STATUS, createdAPI.getLifeCycleStatus());
            eventPayload.put(APIMgtConstants.FunctionsConstants.API_PERMISSION, createdAPI.getApiPermission());
            // This will notify all the EventObservers(Asynchronous)
            ObserverNotifier observerNotifier = new ObserverNotifier(Event.API_CREATION, getUsername(),
                    ZonedDateTime.now(ZoneOffset.UTC), eventPayload, this);
            ObserverNotifierThreadPool.getInstance().executeTask(observerNotifier);
        } else {
            String message = "Duplicate API already Exist with name/Context " + apiBuilder.getName();
            log.error(message);
            throw new APIManagementException(message, ExceptionCodes.API_ALREADY_EXISTS);
        }
    } catch (APIMgtDAOException e) {
        String errorMsg = "Error occurred while creating the API - " + apiBuilder.getName();
        log.error(errorMsg);
        throw new APIManagementException(errorMsg, e, e.getErrorHandler());
    } catch (LifecycleException | ParseException e) {
        String errorMsg = "Error occurred while Associating the API - " + apiBuilder.getName();
        log.error(errorMsg);
        throw new APIManagementException(errorMsg, e, ExceptionCodes.APIMGT_LIFECYCLE_EXCEPTION);
    } catch (APITemplateException e) {
        String message = "Error generating API configuration for API " + apiBuilder.getName();
        log.error(message, e);
        throw new APIManagementException(message, ExceptionCodes.TEMPLATE_EXCEPTION);
    } catch (GatewayException e) {
        String message = "Error occurred while adding API - " + apiBuilder.getName() + " to gateway";
        log.error(message, e);
        throw new APIManagementException(message, ExceptionCodes.GATEWAY_EXCEPTION);
    }
    return apiBuilder.getId();
}

From source file:alfio.manager.TicketReservationManager.java

private void reserveAdditionalServicesForReservation(int eventId, String transactionId,
        ASReservationWithOptionalCodeModification additionalServiceReservation, PromoCodeDiscount discount) {
    Optional.ofNullable(additionalServiceReservation.getAdditionalServiceId())
            .flatMap(id -> optionally(() -> additionalServiceRepository.getById(id, eventId)))
            .filter(as -> additionalServiceReservation.getQuantity() > 0
                    && (as.isFixPrice() || Optional.ofNullable(additionalServiceReservation.getAmount())
                            .filter(a -> a.compareTo(BigDecimal.ZERO) > 0).isPresent()))
            .map(as -> Pair.of(eventRepository.findById(eventId), as)).ifPresent(pair -> {
                Event e = pair.getKey();
                AdditionalService as = pair.getValue();
                IntStream.range(0, additionalServiceReservation.getQuantity()).forEach(i -> {
                    AdditionalServicePriceContainer pc = AdditionalServicePriceContainer
                            .from(additionalServiceReservation.getAmount(), as, e, discount);
                    additionalServiceItemRepository.insert(UUID.randomUUID().toString(),
                            ZonedDateTime.now(Clock.systemUTC()), transactionId, as.getId(),
                            AdditionalServiceItemStatus.PENDING, eventId, pc.getSrcPriceCts(),
                            unitToCents(pc.getFinalPrice()), unitToCents(pc.getVAT()),
                            unitToCents(pc.getAppliedDiscount()));
                });/*from  w  w w  . j a v a 2 s  .  co m*/
            });

}

From source file:nu.yona.server.analysis.service.ActivityServiceTest.java

@Test
public void getUserWeekActivityOverviews_noActivityPresent_resultsWithInactivity() {
    Page<WeekActivityOverviewDto> inactivityWeekOverviews = service.getUserWeekActivityOverviews(userId,
            new PageRequest(0, 5));

    // because the gambling goal was added with creation date two weeks ago, there are multiple weeks
    assertThat(inactivityWeekOverviews.getNumberOfElements(), equalTo(3));
    // the other goals were created today, so get the most recent (first) element
    WeekActivityOverviewDto inactivityWeekOverview = inactivityWeekOverviews.getContent().get(0);
    assertThat(inactivityWeekOverview.getWeekActivities().size(), equalTo(userAnonEntity.getGoals().size()));
    WeekActivityDto inactivityWeekForGambling = inactivityWeekOverview.getWeekActivities().stream()
            .filter(a -> a.getGoalId().equals(gamblingGoal.getId())).findAny().get();
    assertThat(inactivityWeekForGambling.getStartTime(),
            equalTo(getWeekStartTime(ZonedDateTime.now(userAnonZone))));
    // TODO: mock day activity in this week?
    // ZonedDateTime today = getDayStartTime(ZonedDateTime.now(userAnonZone));
    // int thisWeekNumberOfWeekDaysPast = today.getDayOfWeek() == DayOfWeek.SUNDAY ? 0 : today.getDayOfWeek().getValue();
    // assertThat(inactivityWeekForGambling.getDayActivities().size(), equalTo(1 + thisWeekNumberOfWeekDaysPast));
}

From source file:com.example.app.support.service.AppUtil.java

/**
 * Get a ZonedDateTime for comparison on membership dates
 *
 * @param zone the TimeZone/*from  www .  j  av a 2s.c  om*/
 *
 * @return the ZonedDateTime
 */
public static ZonedDateTime getZonedDateTimeForComparison(TimeZone zone) {
    ZonedDateTime dt = ZonedDateTime.now(zone.toZoneId());
    dt = dt.plus(1L, ChronoUnit.HOURS);
    dt = dt.truncatedTo(ChronoUnit.HOURS);
    return dt;
}

From source file:nu.yona.server.analysis.service.ActivityServiceTest.java

@Test
public void getUserDayActivityDetail_noActivityPresent_resultWithInactivity() {
    ZonedDateTime today = getDayStartTime(ZonedDateTime.now(userAnonZone));

    DayActivityDto inactivityDay = service.getUserDayActivityDetail(userId, LocalDate.now(userAnonZone),
            gamblingGoal.getId());//from   w w  w .j a  va  2 s . co  m

    assertThat(inactivityDay.getSpread().size(), equalTo(96));
    assertThat(inactivityDay.getStartTime(), equalTo(today));
    assertThat(inactivityDay.getTimeZoneId(), equalTo(userAnonZone.getId()));
    assertThat(inactivityDay.getTotalActivityDurationMinutes().get(), equalTo(0));
    assertThat(inactivityDay.getTotalMinutesBeyondGoal(), equalTo(0));
}

From source file:nu.yona.server.analysis.service.ActivityServiceTest.java

@Test
public void getUserDayActivityDetail_activityPresent_resultWithActivity() {
    ZonedDateTime today = getDayStartTime(ZonedDateTime.now(userAnonZone));
    ZonedDateTime yesterday = today.minusDays(1);

    LocalTime activityStartTimeOnDay = LocalTime.parse("20:14:57");
    LocalTime activityEndTimeOnDay = LocalTime.parse("20:21:00");

    int hour = 20;
    int[] expectedSpread = getEmptySpread();
    expectedSpread[hour * 4] = 1;/* w  ww  .j  av a 2 s  .  co m*/
    expectedSpread[hour * 4 + 1] = 6;

    // gambling goal was created 2 weeks ago, see above
    // mock some activity on yesterday
    DayActivity yesterdayRecordedActivity = DayActivity.createInstance(userAnonEntity, gamblingGoal,
            userAnonZone, yesterday.toLocalDate());
    ZonedDateTime activityStartTime = yesterday.withHour(activityStartTimeOnDay.getHour())
            .withMinute(activityStartTimeOnDay.getMinute()).withSecond(activityStartTimeOnDay.getSecond());
    ZonedDateTime activityEndTime = yesterday.withHour(activityEndTimeOnDay.getHour())
            .withMinute(activityEndTimeOnDay.getMinute()).withSecond(activityEndTimeOnDay.getSecond());
    Activity recordedActivity = Activity.createInstance(userAnonZone, activityStartTime.toLocalDateTime(),
            activityEndTime.toLocalDateTime(), Optional.empty());
    yesterdayRecordedActivity.addActivity(recordedActivity);
    when(mockDayActivityRepository.findOne(userAnonId, yesterday.toLocalDate(), gamblingGoal.getId()))
            .thenReturn(yesterdayRecordedActivity);

    DayActivityDto activityDay = service.getUserDayActivityDetail(userId, yesterday.toLocalDate(),
            gamblingGoal.getId());

    verify(mockDayActivityRepository, times(1)).findOne(userAnonId, yesterday.toLocalDate(),
            gamblingGoal.getId());
    assertThat(activityDay.getSpread(), equalTo(Arrays.asList(ArrayUtils.toObject((expectedSpread)))));
}