List of usage examples for java.time ZonedDateTime now
public static ZonedDateTime now(Clock clock)
From source file:nu.yona.server.analysis.service.ActivityServiceTest.java
@Test public void getUserWeekActivityDetail_noActivityPresent_resultWithInactivity() { WeekActivityDto inactivityWeek = service.getUserWeekActivityDetail(userId, getWeekStartDate(LocalDate.now(userAnonZone)), gamblingGoal.getId()); assertThat(inactivityWeek.getSpread().size(), equalTo(96)); assertThat(inactivityWeek.getStartTime(), equalTo(getWeekStartTime(ZonedDateTime.now(userAnonZone)))); assertThat(inactivityWeek.getTimeZoneId(), equalTo(userAnonZone.getId())); assertThat(inactivityWeek.getTotalActivityDurationMinutes().get(), equalTo(0)); }
From source file:ru.anr.base.BaseParent.java
/** * Current time. It always is represented in UTC. * //from w ww. j a v a 2 s . c o m * @return Time represented as {@link ZonedDateTime} object */ public static ZonedDateTime now() { return (clock == null) ? ZonedDateTime.now(DEFAULT_TIMEZONE) : ZonedDateTime.now(clock); }
From source file:alfio.manager.AdminReservationManager.java
private Result<TicketCategory> createCategory(TicketsInfo ti, Event event, AdminReservationModification reservation, String username) { Category category = ti.getCategory(); List<Attendee> attendees = ti.getAttendees(); DateTimeModification inception = fromZonedDateTime(ZonedDateTime.now(event.getZoneId())); int tickets = attendees.size(); TicketCategoryModification tcm = new TicketCategoryModification(category.getExistingCategoryId(), category.getName(), tickets, inception, reservation.getExpiration(), Collections.emptyMap(), category.getPrice(), true, "", true, null, null, null, null, null); int notAllocated = getNotAllocatedTickets(event); int missingTickets = Math.max(tickets - notAllocated, 0); Event modified = increaseSeatsIfNeeded(ti, event, missingTickets, event); return eventManager.insertCategory(modified, tcm, username) .map(id -> ticketCategoryRepository.getByIdAndActive(id, event.getId())); }
From source file:alfio.manager.TicketReservationManager.java
public void confirmOfflinePayment(Event event, String reservationId, String username) { TicketReservation ticketReservation = findById(reservationId).orElseThrow(IllegalArgumentException::new); ticketReservationRepository.lockReservationForUpdate(reservationId); Validate.isTrue(ticketReservation.getPaymentMethod() == PaymentProxy.OFFLINE, "invalid payment method"); Validate.isTrue(ticketReservation.getStatus() == TicketReservationStatus.OFFLINE_PAYMENT, "invalid status"); ticketReservationRepository.confirmOfflinePayment(reservationId, TicketReservationStatus.COMPLETE.name(), ZonedDateTime.now(event.getZoneId())); registerAlfioTransaction(event, reservationId, PaymentProxy.OFFLINE); auditingRepository.insert(reservationId, userRepository.findIdByUserName(username).orElse(null), event.getId(), Audit.EventType.RESERVATION_OFFLINE_PAYMENT_CONFIRMED, new Date(), Audit.EntityType.RESERVATION, ticketReservation.getId()); CustomerName customerName = new CustomerName(ticketReservation.getFullName(), ticketReservation.getFirstName(), ticketReservation.getLastName(), event); acquireItems(TicketStatus.ACQUIRED, AdditionalServiceItemStatus.ACQUIRED, PaymentProxy.OFFLINE, reservationId, ticketReservation.getEmail(), customerName, ticketReservation.getUserLanguage(), ticketReservation.getBillingAddress(), event.getId()); Locale language = findReservationLanguage(reservationId); sendConfirmationEmail(event, findById(reservationId).orElseThrow(IllegalArgumentException::new), language); final TicketReservation finalReservation = ticketReservationRepository.findReservationById(reservationId); pluginManager.handleReservationConfirmation(finalReservation, event.getId()); extensionManager.handleReservationConfirmation(finalReservation, event.getId()); }
From source file:alfio.manager.TicketReservationManager.java
void registerAlfioTransaction(Event event, String reservationId, PaymentProxy paymentProxy) { int priceWithVAT = totalReservationCostWithVAT(reservationId).getPriceWithVAT(); Long platformFee = FeeCalculator.getCalculator(event, configurationManager) .apply(ticketRepository.countTicketsInReservation(reservationId), (long) priceWithVAT).orElse(0L); //FIXME we must support multiple transactions for a reservation, otherwise we can't handle properly the case of ON_SITE payments if (paymentProxy != PaymentProxy.ON_SITE || !transactionRepository.loadOptionalByReservationId(reservationId).isPresent()) { String transactionId = paymentProxy.getKey() + "-" + System.currentTimeMillis(); transactionRepository.insert(transactionId, null, reservationId, ZonedDateTime.now(event.getZoneId()), priceWithVAT, event.getCurrency(), "Offline payment confirmed for " + reservationId, paymentProxy.getKey(), platformFee, 0L); } else {/*from w w w.j a v a 2s . co m*/ log.warn("ON-Site check-in: ignoring transaction registration for reservationId {}", reservationId); } }
From source file:alfio.manager.AdminReservationManager.java
private void createMissingTickets(Event event, int tickets) { final MapSqlParameterSource[] params = generateEmptyTickets(event, Date.from(ZonedDateTime.now(event.getZoneId()).toInstant()), tickets, Ticket.TicketStatus.FREE) .toArray(MapSqlParameterSource[]::new); jdbc.batchUpdate(ticketRepository.bulkTicketInitialization(), params); }
From source file:org.wso2.carbon.apimgt.core.impl.APIPublisherImpl.java
/** * Updates design and implementation of an existing API. This method must not be used to change API status. * Implementations should throw an exceptions when such attempts are made. All life cycle state changes * should be carried out using the changeAPIStatus method of this interface. * * @param apiBuilder {@code org.wso2.carbon.apimgt.core.models.API.APIBuilder} model object * @throws APIManagementException if failed to update API *///ww w.j a v a2s . c o m @Override public void updateAPI(API.APIBuilder apiBuilder) throws APIManagementException { APIGateway gateway = getApiGateway(); apiBuilder.provider(getUsername()); apiBuilder.updatedBy(getUsername()); try { API originalAPI = getAPIbyUUID(apiBuilder.getId()); if (originalAPI != null) { //Checks whether the logged in user has the "UPDATE" permission for the API verifyUserPermissionsToUpdateAPI(getUsername(), originalAPI); apiBuilder.createdTime(originalAPI.getCreatedTime()); //workflow status is an internal property and shouldn't be allowed to update externally apiBuilder.workflowStatus(originalAPI.getWorkflowStatus()); if ((originalAPI.getName().equals(apiBuilder.getName())) && (originalAPI.getVersion().equals(apiBuilder.getVersion())) && (originalAPI.getProvider().equals(apiBuilder.getProvider())) && originalAPI.getLifeCycleStatus().equalsIgnoreCase(apiBuilder.getLifeCycleStatus())) { if (!StringUtils.isEmpty(apiBuilder.getApiPermission())) { apiBuilder.apiPermission(replaceGroupNamesWithId(apiBuilder.getApiPermission())); Map<String, Integer> roleNamePermissionList; roleNamePermissionList = getAPIPermissionArray(apiBuilder.getApiPermission()); apiBuilder.permissionMap(roleNamePermissionList); } Map<String, Endpoint> apiEndpointMap = apiBuilder.getEndpoint(); validateEndpoints(apiEndpointMap, true); createUriTemplateList(apiBuilder, true); validateApiPolicy(apiBuilder.getApiPolicy()); validateSubscriptionPolicies(apiBuilder); String updatedSwagger = apiDefinitionFromSwagger20.generateSwaggerFromResources(apiBuilder); String gatewayConfig = getApiGatewayConfig(apiBuilder.getId()); GatewaySourceGenerator gatewaySourceGenerator = getGatewaySourceGenerator(); APIConfigContext apiConfigContext = new APIConfigContext(apiBuilder.build(), config.getGatewayPackageName()); gatewaySourceGenerator.setApiConfigContext(apiConfigContext); String updatedGatewayConfig = gatewaySourceGenerator.getGatewayConfigFromSwagger(gatewayConfig, updatedSwagger); API api = apiBuilder.build(); //Add API to gateway gateway.updateAPI(api); if (log.isDebugEnabled()) { log.debug("API : " + apiBuilder.getName() + " has been successfully updated in gateway"); } if (originalAPI.getContext() != null && !originalAPI.getContext().equals(apiBuilder.getContext())) { if (!checkIfAPIContextExists(api.getContext())) { //if the API has public visibility, update the API without any role checking if (API.Visibility.PUBLIC == api.getVisibility()) { getApiDAO().updateAPI(api.getId(), api); } else if (API.Visibility.RESTRICTED == api.getVisibility()) { //get all the roles in the system Set<String> availableRoles = APIUtils.getAllAvailableRoles(); //get the roles needed to be associated with the API Set<String> apiRoleList = api.getVisibleRoles(); //if the API has role based visibility, update the API with role checking if (APIUtils.checkAllowedRoles(availableRoles, apiRoleList)) { getApiDAO().updateAPI(api.getId(), api); } } getApiDAO().updateApiDefinition(api.getId(), updatedSwagger, api.getUpdatedBy()); getApiDAO().updateGatewayConfig(api.getId(), updatedGatewayConfig, api.getUpdatedBy()); } else { throw new APIManagementException("Context already Exist", ExceptionCodes.API_ALREADY_EXISTS); } } else { //if the API has public visibility, update the API without any role checking if (API.Visibility.PUBLIC == api.getVisibility()) { getApiDAO().updateAPI(api.getId(), api); } else if (API.Visibility.RESTRICTED == api.getVisibility()) { //get all the roles in the system Set<String> allAvailableRoles = APIUtils.getAllAvailableRoles(); //get the roles needed to be associated with the API Set<String> apiRoleList = api.getVisibleRoles(); //if the API has role based visibility, update the API with role checking if (APIUtils.checkAllowedRoles(allAvailableRoles, apiRoleList)) { getApiDAO().updateAPI(api.getId(), api); } } getApiDAO().updateApiDefinition(api.getId(), updatedSwagger, api.getUpdatedBy()); getApiDAO().updateGatewayConfig(api.getId(), updatedGatewayConfig, api.getUpdatedBy()); } if (log.isDebugEnabled()) { log.debug("API " + api.getName() + "-" + api.getVersion() + " was updated successfully."); // '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_DESCRIPTION, api.getDescription()); eventPayload.put(APIMgtConstants.FunctionsConstants.API_CONTEXT, api.getContext()); eventPayload.put(APIMgtConstants.FunctionsConstants.API_LC_STATUS, api.getLifeCycleStatus()); // This will notify all the EventObservers(Asynchronous) ObserverNotifier observerNotifier = new ObserverNotifier(Event.API_UPDATE, getUsername(), ZonedDateTime.now(ZoneOffset.UTC), eventPayload, this); ObserverNotifierThreadPool.getInstance().executeTask(observerNotifier); } } else { APIUtils.verifyValidityOfApiUpdate(apiBuilder, originalAPI); } } else { log.error("Couldn't found API with ID " + apiBuilder.getId()); throw new APIManagementException("Couldn't found API with ID " + apiBuilder.getId(), ExceptionCodes.API_NOT_FOUND); } } catch (APIMgtDAOException e) { String errorMsg = "Error occurred while updating the API - " + apiBuilder.getName(); log.error(errorMsg, e); throw new APIManagementException(errorMsg, e, e.getErrorHandler()); } catch (ParseException e) { String errorMsg = "Error occurred while parsing the permission json from swagger - " + apiBuilder.getName(); log.error(errorMsg, e); throw new APIManagementException(errorMsg, e, ExceptionCodes.SWAGGER_PARSE_EXCEPTION); } catch (GatewayException e) { String message = "Error occurred while updating API - " + apiBuilder.getName() + " in gateway"; log.error(message, e); throw new APIManagementException(message, ExceptionCodes.GATEWAY_EXCEPTION); } }
From source file:alfio.manager.TicketReservationManager.java
public static ZonedDateTime getOfflinePaymentDeadline(Event event, ConfigurationManager configurationManager) { ZonedDateTime now = ZonedDateTime.now(event.getZoneId()); int waitingPeriod = getOfflinePaymentWaitingPeriod(event, configurationManager); if (waitingPeriod == 0) { log.warn(// ww w . jav a 2s . com "accepting offline payments the same day is a very bad practice and should be avoided. Please set cash payment as payment method next time"); //if today is the event start date, then we add a couple of hours. //TODO Maybe should we avoid this wrong behavior upfront, in the admin area? return now.plusHours(2); } return now.plusDays(waitingPeriod).truncatedTo(ChronoUnit.HALF_DAYS); }
From source file:alfio.manager.TicketReservationManager.java
public static int getOfflinePaymentWaitingPeriod(Event event, ConfigurationManager configurationManager) { ZonedDateTime now = ZonedDateTime.now(event.getZoneId()); ZonedDateTime eventBegin = event.getBegin(); int daysToBegin = (int) ChronoUnit.DAYS.between(now.toLocalDate(), eventBegin.toLocalDate()); if (daysToBegin < 0) { throw new OfflinePaymentException("Cannot confirm an offline reservation after event start"); }/* w ww.j av a 2s .c o m*/ int waitingPeriod = configurationManager.getIntConfigValue( Configuration.from(event.getOrganizationId(), event.getId(), OFFLINE_PAYMENT_DAYS), 5); return Math.min(daysToBegin, waitingPeriod); }
From source file:alfio.manager.EventManagerIntegrationTest.java
@Test public void testNewCategoryBoundedAddReleasedTickets() { 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, false, "", true, null, null, null, null, null); Result<Integer> result = eventManager.insertCategory(event, tcm, username); assertTrue(result.isSuccess());/*from ww w. j a v a 2 s . c o m*/ assertEquals(20, ticketRepository.countReleasedTicketInCategory(event.getId(), result.getData()).intValue()); }