List of usage examples for java.time ZonedDateTime toInstant
default Instant toInstant()
From source file:org.apache.james.jmap.methods.integration.cucumber.GetMessagesMethodStepdefs.java
private void appendMessage(String mailbox, ContentType contentType, String subject, String content, Optional<Map<String, String>> headers) throws Exception { ZonedDateTime dateTime = ZonedDateTime.parse("2014-10-30T14:12:00Z"); mainStepdefs.jmapServer.serverProbe().appendMessage(userStepdefs.lastConnectedUser, new MailboxPath(MailboxConstants.USER_NAMESPACE, userStepdefs.lastConnectedUser, mailbox), new ByteArrayInputStream(message(contentType, subject, content, headers).getBytes(Charsets.UTF_8)), Date.from(dateTime.toInstant()), false, new Flags()); }
From source file:io.stallion.jobs.JobCoordinator.java
/** * This really should not be a public method, but needs to be so unittests can access it. * This is called by the main run() loop to actually find jobs to run and trigger their running * @param now/*from w w w. j av a 2 s . co m*/ * @throws ClassNotFoundException * @throws IllegalAccessException * @throws InstantiationException */ public void executeJobsForCurrentTime(ZonedDateTime now) throws ClassNotFoundException, IllegalAccessException, InstantiationException { now = now.withSecond(0).withNano(0); Log.finest("Checking for jobs to execute this period"); for (JobStatus jobStatus : JobStatusController.instance().findJobsForPeriod(now)) { JobDefinition definition = JobCoordinator.instance().getJobDefinition(jobStatus.getName()); lastRanAtByJobName.put(definition.getName(), now.toInstant().toEpochMilli()); Log.info("Dispatching job {0}", definition.getName()); // Now start-up a thread to actually run the job Class<? extends Job> jobClass = definition.getJobClass(); Job job = jobClass.newInstance(); JobInstanceDispatcher dispatcher = new JobInstanceDispatcher(jobStatus, definition, job, false, now); if (synchronousMode) { dispatcher.run(); } else { pool.execute(dispatcher); } } }
From source file:com.querydsl.webhooks.GithubReviewWindow.java
@Bean public PullRequestHandler reviewWindowHandler(Environment environment) { Duration defaultReviewWindow = Duration.parse(environment.getRequiredProperty("duration")); //duration is the default window Map<String, ScheduledFuture<?>> asyncTasks = Maps.newConcurrentMap(); return payload -> { PullRequest pullRequest = payload.getPullRequest(); Ref head = pullRequest.getHead(); try {/*ww w.j av a2 s.c o m*/ GHRepository repository = github.getRepository(payload.getRepository().getFullName()); Collection<GHLabel> labels = repository.getIssue(pullRequest.getNumber()).getLabels(); Duration reviewTime = labels.stream().map(label -> "duration." + label.getName()) //for all duration.[label] properties .map(environment::getProperty).filter(Objects::nonNull) //look for a Duration .findFirst().map(Duration::parse).orElse(defaultReviewWindow); //if none found, use the default window ZonedDateTime creationTime = pullRequest.getCreatedAt(); ZonedDateTime windowCloseTime = creationTime.plus(reviewTime); boolean windowPassed = now().isAfter(windowCloseTime); logger.info("creationTime({}) + reviewTime({}) = windowCloseTime({}), so windowPassed = {}", creationTime, reviewTime, windowCloseTime, windowPassed); if (windowPassed) { completeAndCleanUp(asyncTasks, repository, head); } else { createPendingMessage(repository, head, reviewTime); ScheduledFuture<?> scheduledTask = taskScheduler.schedule( () -> completeAndCleanUp(asyncTasks, repository, head), Date.from(windowCloseTime.toInstant())); replaceCompletionTask(asyncTasks, scheduledTask, head); } } catch (IOException ex) { throw Throwables.propagate(ex); } }; }
From source file:me.ryanhamshire.griefprevention.command.CommandHelper.java
public static void displayClaimBankInfo(CommandSource src, GPClaim claim, boolean checkTown, boolean returnToClaimInfo) { final EconomyService economyService = GriefPreventionPlugin.instance.economyService.orElse(null); if (economyService == null) { GriefPreventionPlugin.sendMessage(src, GriefPreventionPlugin.instance.messageData.economyNotInstalled.toText()); return;/*from w ww . java 2 s.com*/ } if (checkTown && !claim.isInTown()) { GriefPreventionPlugin.sendMessage(src, GriefPreventionPlugin.instance.messageData.townNotIn.toText()); return; } if (!checkTown && (claim.isSubdivision() || claim.isAdminClaim())) { return; } final GPClaim town = claim.getTownClaim(); Account bankAccount = checkTown ? town.getEconomyAccount().orElse(null) : claim.getEconomyAccount().orElse(null); if (bankAccount == null) { GriefPreventionPlugin.sendMessage(src, GriefPreventionPlugin.instance.messageData.economyVirtualNotSupported.toText()); return; } final GPPlayerData playerData = GriefPreventionPlugin.instance.dataStore.getPlayerData(claim.getWorld(), claim.getOwnerUniqueId()); final double claimBalance = bankAccount.getBalance(economyService.getDefaultCurrency()).doubleValue(); double taxOwed = -1; final double playerTaxRate = GPOptionHandler.getClaimOptionDouble(playerData.getPlayerSubject(), claim, GPOptions.Type.TAX_RATE, playerData); if (checkTown) { if (!town.getOwnerUniqueId().equals(playerData.playerID)) { for (Claim playerClaim : playerData.getInternalClaims()) { GPClaim playerTown = (GPClaim) playerClaim.getTown().orElse(null); if (!playerClaim.isTown() && playerTown != null && playerTown.getUniqueId().equals(claim.getUniqueId())) { taxOwed += (playerTown.getClaimBlocks() / 256) * playerTaxRate; } } } else { taxOwed = town.getClaimBlocks() * playerTaxRate; } } else { taxOwed = claim.getClaimBlocks() * playerTaxRate; } final GriefPreventionConfig<?> activeConfig = GriefPreventionPlugin .getActiveConfig(claim.getWorld().getProperties()); final ZonedDateTime withdrawDate = TaskUtils .getNextTargetZoneDate(activeConfig.getConfig().claim.taxApplyHour, 0, 0); Duration duration = Duration.between(Instant.now().truncatedTo(ChronoUnit.SECONDS), withdrawDate.toInstant()); final long s = duration.getSeconds(); final String timeLeft = String.format("%d:%02d:%02d", s / 3600, (s % 3600) / 60, (s % 60)); final Text message = GriefPreventionPlugin.instance.messageData.claimBankInfo .apply(ImmutableMap.of("balance", claimBalance, "amount", taxOwed, "time_remaining", timeLeft, "tax_balance", claim.getData().getEconomyData().getTaxBalance())) .build(); Text transactions = Text.builder().append(Text.of(TextStyles.ITALIC, TextColors.AQUA, "Bank Transactions")) .onClick(TextActions .executeCallback(createBankTransactionsConsumer(src, claim, checkTown, returnToClaimInfo))) .onHover(TextActions.showText(Text.of("Click here to view bank transactions"))).build(); List<Text> textList = new ArrayList<>(); if (returnToClaimInfo) { textList.add(Text.builder() .append(Text.of(TextColors.WHITE, "\n[", TextColors.AQUA, "Return to claim info", TextColors.WHITE, "]\n")) .onClick(TextActions.executeCallback(CommandHelper.createCommandConsumer(src, "claiminfo", ""))) .build()); } textList.add(message); textList.add(transactions); PaginationService paginationService = Sponge.getServiceManager().provide(PaginationService.class).get(); PaginationList.Builder paginationBuilder = paginationService.builder() .title(Text.of(TextColors.AQUA, "Bank Info")).padding(Text.of(TextStyles.STRIKETHROUGH, "-")) .contents(textList); paginationBuilder.sendTo(src); }
From source file:edu.usu.sdl.openstorefront.service.UserServiceImpl.java
@Override public void cleanupOldUserMessages() { int maxDays = Convert.toInteger(PropertiesManager.getValue(PropertiesManager.KEY_MESSAGE_KEEP_DAYS, "30")); LocalDateTime archiveTime = LocalDateTime.now(); archiveTime = archiveTime.minusDays(maxDays); archiveTime = archiveTime.truncatedTo(ChronoUnit.DAYS); String deleteQuery = "updateDts < :maxUpdateDts AND activeStatus = :activeStatusParam"; ZonedDateTime zdt = archiveTime.atZone(ZoneId.systemDefault()); Date archiveDts = Date.from(zdt.toInstant()); Map<String, Object> queryParams = new HashMap<>(); queryParams.put("maxUpdateDts", archiveDts); queryParams.put("activeStatusParam", UserMessage.INACTIVE_STATUS); persistenceService.deleteByQuery(UserMessage.class, deleteQuery, queryParams); }
From source file:alfio.manager.EventManager.java
MapSqlParameterSource[] prepareTicketsBulkInsertParameters(ZonedDateTime creation, Event event, int requestedTickets, TicketStatus ticketStatus) { //FIXME: the date should be inserted as ZonedDateTime ! Date creationDate = Date.from(creation.toInstant()); List<TicketCategory> categories = ticketCategoryRepository.findByEventId(event.getId()); Stream<MapSqlParameterSource> boundedTickets = categories.stream().filter(IS_CATEGORY_BOUNDED) .flatMap(tc -> generateTicketsForCategory(tc, event, creationDate, 0)); int generatedTickets = categories.stream().filter(IS_CATEGORY_BOUNDED) .mapToInt(TicketCategory::getMaxTickets).sum(); if (generatedTickets >= requestedTickets) { return boundedTickets.toArray(MapSqlParameterSource[]::new); }/*from www . j a v a 2 s . c o m*/ return Stream.concat(boundedTickets, generateEmptyTickets(event, creationDate, requestedTickets - generatedTickets, ticketStatus)) .toArray(MapSqlParameterSource[]::new); }
From source file:alfio.manager.TicketReservationManager.java
private void transitionToOfflinePayment(Event event, String reservationId, String email, CustomerName customerName, String billingAddress) { ZonedDateTime deadline = getOfflinePaymentDeadline(event, configurationManager); int updatedReservation = ticketReservationRepository.postponePayment(reservationId, Date.from(deadline.toInstant()), email, customerName.getFullName(), customerName.getFirstName(), customerName.getLastName(), billingAddress); Validate.isTrue(updatedReservation == 1, "expected exactly one updated reservation, got " + updatedReservation); }
From source file:com.teradata.benchto.service.TagControllerTest.java
@Test public void tagsHappyPath() throws Exception { ZonedDateTime start = currentDateTime(); // create env mvc.perform(post("/v1/environment/env").contentType(APPLICATION_JSON).content("{}")) .andExpect(status().isOk()); // create tag1 mvc.perform(post("/v1/tag/env").contentType(APPLICATION_JSON) .content(storeTagRequest("tag1", "description for tag1"))).andExpect(status().isOk()); ZonedDateTime afterTag1 = currentDateTime(); // create tag2 mvc.perform(/* ww w.j a v a 2s . co m*/ post("/v1/tag/env").contentType(APPLICATION_JSON).content(storeTagRequest("tag2 - no description"))) .andExpect(status().isOk()); // create tag3 mvc.perform(post("/v1/tag/env").contentType(APPLICATION_JSON) .content(storeTagRequest("tag3", "description for tag3"))).andExpect(status().isOk()); // get all tags mvc.perform(get("/v1/tags/env").contentType(APPLICATION_JSON)).andExpect(status().isOk()) .andExpect(jsonPath("$", hasSize(3))).andExpect(jsonPath("$[0].name", is("tag1"))) .andExpect(jsonPath("$[0].description", is("description for tag1"))) .andExpect(jsonPath("$[1].name", is("tag2 - no description"))) .andExpect(jsonPath("$[1].description", isEmptyOrNullString())) .andExpect(jsonPath("$[2].name", is("tag3"))) .andExpect(jsonPath("$[2].description", is("description for tag3"))); // get tag2, get3 mvc.perform(get("/v1/tags/env").contentType(APPLICATION_JSON) .content("{\"start\": \"" + afterTag1.format(ISO_ZONED_DATE_TIME) + "\"}")) .andExpect(status().isOk()).andExpect(jsonPath("$", hasSize(2))) .andExpect(jsonPath("$[0].name", is("tag2 - no description"))) .andExpect(jsonPath("$[0].description", isEmptyOrNullString())) .andExpect(jsonPath("$[1].name", is("tag3"))) .andExpect(jsonPath("$[1].description", is("description for tag3"))); // get tag1 mvc.perform(get("/v1/tags/env").contentType(APPLICATION_JSON) .content("{\"start\": \"" + start.format(ISO_ZONED_DATE_TIME) + "\", \"end\": \"" + afterTag1.format(ISO_ZONED_DATE_TIME) + "\"}")) .andExpect(status().isOk()).andExpect(jsonPath("$", hasSize(1))) .andExpect(jsonPath("$[0].name", is("tag1"))) .andExpect(jsonPath("$[0].description", is("description for tag1"))); // get latest tag mvc.perform(get("/v1/tags/env/latest").contentType(APPLICATION_JSON)).andExpect(status().isOk()) .andExpect(jsonPath("$.name", is("tag3"))) .andExpect(jsonPath("$.description", is("description for tag3"))); // get latest tag but not older than afterTat1 timestamp mvc.perform(get("/v1/tags/env/latest?until={until}", afterTag1.toInstant().toEpochMilli()) .contentType(APPLICATION_JSON)).andExpect(status().isOk()).andExpect(jsonPath("$.name", is("tag1"))) .andExpect(jsonPath("$.description", is("description for tag1"))); // get latest tag but not older than start timestamp mvc.perform(get("/v1/tags/env/latest?until={until}", start.toInstant().toEpochMilli()) .contentType(APPLICATION_JSON)).andExpect(status().isOk()) .andExpect(result -> jsonPath("$.name", is("tag1"))).andExpect(content().string("")); }