List of usage examples for java.time ZonedDateTime now
public static ZonedDateTime now()
From source file:org.mascherl.example.service.ComposeMailService.java
@Transactional public void saveDraft(Mail mail, User currentUser) { if (mail.getUuid() == null) { throw new IllegalArgumentException("Given draft mail has no UUID"); }/*from www . j ava2 s. co m*/ MailEntity draftEntity = em.find(MailEntity.class, mail.getUuid()); if (!Objects.equals(draftEntity.getUser().getUuid(), currentUser.getUuid())) { throw new IllegalArgumentException("The draft to be saved does not belong to the current user."); } draftEntity.setMailType(MailType.DRAFT); draftEntity.setDateTime(ZonedDateTime.now()); draftEntity.setUnread(false); draftEntity.setTo(mail.getTo()); draftEntity.setCc(mail.getCc()); draftEntity.setBcc(mail.getBcc()); draftEntity.setSubject(mail.getSubject()); draftEntity.setMessageText(mail.getMessageText()); em.merge(draftEntity); em.flush(); }
From source file:org.apache.james.jmap.model.MailboxMessageTest.java
@Test public void buildShouldWorkWhenAllFieldsArePresent() { Emailer from = Emailer.builder().name("from").email("from@domain").build(); ImmutableList<Emailer> to = ImmutableList.of(Emailer.builder().name("to").email("to@domain").build()); ImmutableList<Emailer> cc = ImmutableList.of(Emailer.builder().name("cc").email("cc@domain").build()); ImmutableList<Emailer> bcc = ImmutableList.of(Emailer.builder().name("bcc").email("bcc@domain").build()); ImmutableList<Emailer> replyTo = ImmutableList .of(Emailer.builder().name("replyTo").email("replyTo@domain").build()); ZonedDateTime currentDate = ZonedDateTime.now(); Attachment simpleAttachment = Attachment.builder().blobId(BlobId.of("blobId")).type("type").name("name") .size(123).build();/*from www . j a v a 2 s . c o m*/ ImmutableList<Attachment> attachments = ImmutableList.of(simpleAttachment); SubMessage simpleMessage = SubMessage.builder().headers(ImmutableMap.of("key", "value")).subject("subject") .date(currentDate).build(); ImmutableMap<BlobId, SubMessage> attachedMessages = ImmutableMap.of(BlobId.of("blobId"), simpleMessage); Message expected = new Message(MessageId.of("user|box|1"), BlobId.of("blobId"), "threadId", ImmutableList.of("mailboxId"), Optional.of("inReplyToMessageId"), true, true, true, true, true, ImmutableMap.of("key", "value"), Optional.of(from), to, cc, bcc, replyTo, "subject", currentDate, 123, "preview", Optional.of("textBody"), Optional.of("htmlBody"), attachments, attachedMessages); Message tested = Message.builder().id(MessageId.of("user|box|1")).blobId(BlobId.of("blobId")) .threadId("threadId").mailboxIds(ImmutableList.of("mailboxId")) .inReplyToMessageId("inReplyToMessageId").isUnread(true).isFlagged(true).isAnswered(true) .isDraft(true).headers(ImmutableMap.of("key", "value")).from(from).to(to).cc(cc).bcc(bcc) .replyTo(replyTo).subject("subject").date(currentDate).size(123).preview("preview") .textBody("textBody").htmlBody("htmlBody").attachments(attachments) .attachedMessages(attachedMessages).build(); assertThat(tested).isEqualToComparingFieldByField(expected); }
From source file:com.sumzerotrading.reporting.csv.ReportGeneratorTest.java
@Test public void testOrderEvent_RoundTripComplete() throws Exception { PairTradeRoundTrip roundTrip = new PairTradeRoundTrip(); TradeReferenceLine tradeReferenceLine = buildReferenceLine("123", LONG, ENTRY); roundTrip.addTradeReference(order, tradeReferenceLine); order.setCurrentStatus(OrderStatus.Status.FILLED); OrderEvent orderEvent = new OrderEvent(order, new OrderStatus(OrderStatus.Status.NEW, "", "", new StockTicker("QQQ"), ZonedDateTime.now())); TradeReferenceLine longExitLine = buildReferenceLine("123", LONG, EXIT); TradeReferenceLine shortEntryLine = buildReferenceLine("123", SHORT, ENTRY); TradeReferenceLine shortExitLine = buildReferenceLine("123", SHORT, EXIT); roundTrip.addTradeReference(order, longExitLine); roundTrip.addTradeReference(order, shortEntryLine); reportGenerator.roundTripMap.put("123", roundTrip); doReturn(shortExitLine).when(reportGenerator).getTradeReferenceLine(any(String.class)); doNothing().when(reportGenerator).writeRoundTripToFile(any(PairTradeRoundTrip.class)); doNothing().when(reportGenerator).deletePartial("123"); assertEquals(1, reportGenerator.roundTripMap.size()); reportGenerator.orderEvent(orderEvent); verify(reportGenerator).deletePartial("123"); verify(reportGenerator).writeRoundTripToFile(roundTrip); assertTrue(reportGenerator.roundTripMap.isEmpty()); }
From source file:alfio.manager.WaitingQueueManagerIntegrationTest.java
@Test public void testDistributeSeatsFirstCategoryIsBounded() throws Exception { List<TicketCategoryModification> categories = getPreSalesTicketCategoryModifications(true, 10, true, 10); Pair<Event, String> pair = initEvent(categories, organizationRepository, userManager, eventManager, eventRepository);/*from ww w.ja va 2 s . c o m*/ Event event = pair.getKey(); TicketCategory firstCategory = eventManager.loadTicketCategories(event).stream() .filter(t -> t.getName().equals("defaultFirst")).findFirst() .orElseThrow(IllegalStateException::new); configurationManager.saveCategoryConfiguration(firstCategory.getId(), event.getId(), Collections.singletonList(new ConfigurationModification(null, ConfigurationKeys.MAX_AMOUNT_OF_TICKETS_BY_RESERVATION.getValue(), "1")), pair.getRight() + "_owner"); configurationManager.saveSystemConfiguration(ConfigurationKeys.ENABLE_PRE_REGISTRATION, "true"); configurationManager.saveSystemConfiguration(ConfigurationKeys.ENABLE_WAITING_QUEUE, "true"); boolean result = waitingQueueManager.subscribe(event, customerJohnDoe(event), "john@doe.com", null, Locale.ENGLISH); assertTrue(result); List<Triple<WaitingQueueSubscription, TicketReservationWithOptionalCodeModification, ZonedDateTime>> subscriptions = waitingQueueManager .distributeSeats(event).collect(Collectors.toList()); assertEquals(1, subscriptions.size()); Triple<WaitingQueueSubscription, TicketReservationWithOptionalCodeModification, ZonedDateTime> subscriptionDetail = subscriptions .get(0); assertEquals("john@doe.com", subscriptionDetail.getLeft().getEmailAddress()); TicketReservationWithOptionalCodeModification reservation = subscriptionDetail.getMiddle(); assertEquals(Integer.valueOf(firstCategory.getId()), reservation.getTicketCategoryId()); assertEquals(Integer.valueOf(1), reservation.getAmount()); assertTrue(subscriptionDetail.getRight().isAfter(ZonedDateTime.now())); }
From source file:org.cgiar.ccafs.marlo.action.summaries.SearchTermsSummaryAction.java
@Override public String execute() throws Exception { ByteArrayOutputStream os = new ByteArrayOutputStream(); try {//www . j av a 2 s . c om Resource reportResource = resourceManager.createDirectly( this.getClass().getResource("/pentaho/crp/SearchTerms.prpt"), MasterReport.class); MasterReport masterReport = (MasterReport) reportResource.getResource(); String center = this.getLoggedCrp().getAcronym(); // Get datetime ZonedDateTime timezone = ZonedDateTime.now(); DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-d 'at' HH:mm "); String zone = timezone.getOffset() + ""; if (zone.equals("Z")) { zone = "+0"; } String currentDate = timezone.format(format) + "(GMT" + zone + ")"; String parameters = this.getRequest().getParameter("keys"); if (parameters != null) { if (parameters.isEmpty()) { // Empty keys } else { // String parametersNotEspecialChar = parameters.replaceAll("[^a-zA-Z0-9]+", ""); keys = Arrays.asList(parameters.split(",")); } } // Set Main_Query CompoundDataFactory cdf = CompoundDataFactory.normalize(masterReport.getDataFactory()); String masterQueryName = "main"; TableDataFactory sdf = (TableDataFactory) cdf.getDataFactoryForQuery(masterQueryName); TypedTableModel model = this.getMasterTableModel(center, currentDate); sdf.addTable(masterQueryName, model); masterReport.setDataFactory(cdf); // Set i8n for pentaho masterReport = this.addi8nParameters(masterReport); // Get details band ItemBand masteritemBand = masterReport.getItemBand(); // Create new empty subreport hash map HashMap<String, Element> hm = new HashMap<String, Element>(); // method to get all the subreports in the prpt and store in the HashMap this.getAllSubreports(hm, masteritemBand); // Uncomment to see which Subreports are detecting the method getAllSubreports // System.out.println("Pentaho SubReports: " + hm); this.fillSubreport((SubReport) hm.get("projects_details"), "project"); this.fillSubreport((SubReport) hm.get("projects_activities"), "activities"); this.fillSubreport((SubReport) hm.get("projects_deliverables"), "deliverables"); ExcelReportUtil.createXLSX(masterReport, os); bytesXLSX = os.toByteArray(); os.close(); } catch (Exception e) { LOG.error("Error generating PDF " + e.getMessage()); throw e; } // Calculate time of generation long stopTime = System.currentTimeMillis(); stopTime = stopTime - startTime; LOG.info("Downloaded successfully: " + this.getFileName() + ". User: " + this.getCurrentUser().getComposedCompleteName() + ". CRP: " + this.getLoggedCrp().getAcronym() + ". Cycle: " + this.getSelectedCycle() + ". Time to generate: " + stopTime + "ms."); return SUCCESS; }
From source file:com.mgmtp.perfload.perfalyzer.reporting.ReportCreator.java
public void createReport(final List<PerfAlyzerFile> files) throws IOException { Function<PerfAlyzerFile, String> classifier = perfAlyzerFile -> { String marker = perfAlyzerFile.getMarker(); return marker == null ? "Overall" : marker; };//from www . j a v a 2 s. c om Supplier<Map<String, List<PerfAlyzerFile>>> mapFactory = () -> new TreeMap<>(Ordering.explicit(tabNames)); Map<String, List<PerfAlyzerFile>> filesByMarker = files.stream() .collect(Collectors.groupingBy(classifier, mapFactory, toList())); Map<String, SortedSetMultimap<String, PerfAlyzerFile>> contentItemFiles = new LinkedHashMap<>(); for (Entry<String, List<PerfAlyzerFile>> entry : filesByMarker.entrySet()) { SortedSetMultimap<String, PerfAlyzerFile> contentItemFilesByMarker = contentItemFiles.computeIfAbsent( entry.getKey(), s -> TreeMultimap.create(new ItemComparator(reportContentsConfigMap.get("priorities")), Ordering.natural())); for (PerfAlyzerFile perfAlyzerFile : entry.getValue()) { File file = perfAlyzerFile.getFile(); String groupKey = removeExtension(file.getPath()); boolean excluded = false; for (Pattern pattern : reportContentsConfigMap.get("exclusions")) { Matcher matcher = pattern.matcher(groupKey); if (matcher.matches()) { excluded = true; log.debug("Excluded from report: {}", groupKey); break; } } if (!excluded) { contentItemFilesByMarker.put(groupKey, perfAlyzerFile); } } } // explicitly copy it because it is otherwise filtered from the report in order to only show in the overview String loadProfilePlot = new File("console", "[loadprofile].png").getPath(); copyFile(new File(soureDir, loadProfilePlot), new File(destDir, loadProfilePlot)); Map<String, List<ContentItem>> tabItems = new LinkedHashMap<>(); Map<String, QuickJump> quickJumps = new HashMap<>(); Set<String> tabNames = contentItemFiles.keySet(); for (Entry<String, SortedSetMultimap<String, PerfAlyzerFile>> tabEntry : contentItemFiles.entrySet()) { String tab = tabEntry.getKey(); SortedSetMultimap<String, PerfAlyzerFile> filesForTab = tabEntry.getValue(); List<ContentItem> contentItems = tabItems.computeIfAbsent(tab, list -> new ArrayList<>()); Map<String, String> quickJumpMap = new LinkedHashMap<>(); quickJumps.put(tab, new QuickJump(tab, quickJumpMap)); int itemIndex = 0; for (Entry<String, Collection<PerfAlyzerFile>> itemEntry : filesForTab.asMap().entrySet()) { String title = itemEntry.getKey(); Collection<PerfAlyzerFile> itemFiles = itemEntry.getValue(); TableData tableData = null; String plotSrc = null; for (PerfAlyzerFile file : itemFiles) { if ("png".equals(getExtension(file.getFile().getName()))) { plotSrc = file.getFile().getPath(); copyFile(new File(soureDir, plotSrc), new File(destDir, plotSrc)); } else { tableData = createTableData(file.getFile()); } } // strip off potential marker title = substringBefore(title, "{"); String[] titleParts = split(title, SystemUtils.FILE_SEPARATOR); StringBuilder sb = new StringBuilder(50); String separator = " - "; sb.append(resourceBundle.getString(titleParts[0])); sb.append(separator); sb.append(resourceBundle.getString(titleParts[1])); List<String> fileNameParts = extractFileNameParts(titleParts[1], true); if (titleParts[1].contains("[distribution]")) { String operation = fileNameParts.get(1); sb.append(separator); sb.append(operation); } else if ("comparison".equals(titleParts[0])) { String operation = fileNameParts.get(1); sb.append(separator); sb.append(operation); } else if (titleParts[1].contains("[gclog]")) { if (fileNameParts.size() > 1) { sb.append(separator); sb.append(fileNameParts.get(1)); } } title = sb.toString(); ContentItem item = new ContentItem(tab, itemIndex, title, tableData, plotSrc, resourceBundle.getString("report.topLink")); contentItems.add(item); quickJumpMap.put(tab + "_" + itemIndex, title); itemIndex++; } } NavBar navBar = new NavBar(tabNames, quickJumps); String testName = removeExtension(testMetadata.getTestPlanFile()); OverviewItem overviewItem = new OverviewItem(testMetadata, resourceBundle, locale); Content content = new Content(tabItems); String perfAlyzerVersion; try { perfAlyzerVersion = Resources.toString(Resources.getResource("perfAlyzer.version"), Charsets.UTF_8); } catch (IOException ex) { log.error("Could not read perfAlyzer version from classpath resource 'perfAlyzer.version'", ex); perfAlyzerVersion = ""; } String dateTimeString = DateTimeFormatter.ISO_OFFSET_DATE_TIME.withLocale(locale) .format(ZonedDateTime.now()); String createdString = String.format(resourceBundle.getString("footer.created"), perfAlyzerVersion, dateTimeString); HtmlSkeleton html = new HtmlSkeleton(testName, createdString, navBar, overviewItem, content); writeReport(html); }
From source file:it.tidalwave.northernwind.frontend.ui.component.calendar.DefaultCalendarViewController.java
/******************************************************************************************************************* * * Returns the current year reading it from the path params, or by default from the calendar. * ******************************************************************************************************************/ @Nonnegative/*from w ww. ja v a 2s .c om*/ private int getCurrentYear(final @Nonnull String pathParams) throws HttpStatusException { try { return "".equals(pathParams) ? ZonedDateTime.now().getYear() : Integer.parseInt(pathParams.replaceAll("/$", "").replaceAll("^/", "")); // return "".equals(pathParams) ? new ZonedDateTime().getYear() : Integer.parseInt(pathParams.replaceAll("/", "")); } catch (NumberFormatException e) { throw new HttpStatusException(404); } }
From source file:org.apache.james.queue.jms.JMSMailQueue.java
public long computeNextDeliveryTimestamp(long delay, TimeUnit unit) { if (delay > 0) { try {/*ww w . j a v a 2s .c o m*/ return ZonedDateTime.now().plus(delay, Temporals.chronoUnit(unit)).toInstant().toEpochMilli(); } catch (ArithmeticException e) { LOGGER.warn( "The {} was caused by conversation {}({}) followed by addition to current timestamp. Falling back to Long.MAX_VALUE.", e.getMessage(), delay, unit.name()); return Long.MAX_VALUE; } } return NO_DELAY; }
From source file:org.openlmis.fulfillment.service.OrderServiceTest.java
@Test public void shouldSaveOrderAndNotDeleteFileIfFtpSendFailure() throws Exception { StatusChange statusChange = new StatusChange(); statusChange.setStatus(ExternalStatus.APPROVED); statusChange.setCreatedDate(ZonedDateTime.now()); statusChange.setAuthorId(randomUUID()); order.setStatusChanges(Lists.newArrayList(statusChange)); when(orderSender.send(order)).thenReturn(false); Order created = orderService.save(order); // then/* w w w .j ava2 s . co m*/ validateCreatedOrder(created, order); assertEquals(OrderStatus.TRANSFER_FAILED, created.getStatus()); InOrder inOrder = inOrder(orderRepository, orderStorage, orderSender); inOrder.verify(orderRepository).save(order); inOrder.verify(orderStorage).store(order); inOrder.verify(orderSender).send(order); inOrder.verify(orderStorage, never()).delete(order); }
From source file:com.github.mavogel.ilias.printer.VelocityOutputPrinter.java
/** * Creates a file writer with a timestamp from the current output type and template. Write * a file in the current directory. Striped the folders off the name if the given template. * * @param outputType the output type//ww w . j a v a 2 s . co m * @param templateName the name of the template * @return the OutputStreamWriter * @throws IOException if the file could not be created. */ private static OutputStreamWriter createFileWriter(final OutputType outputType, final String templateName) throws IOException { final String fileName; int lastIndexOf = templateName.lastIndexOf(System.getProperty("file.separator")); if (lastIndexOf == -1) { fileName = templateName.replace(outputType.getTemplateExtension(), "") + outputType.getFileExtension(); } else { fileName = templateName.substring(lastIndexOf + 1).replace(outputType.getTemplateExtension(), "") + outputType.getFileExtension(); } String datedFileName = Defaults.OUTFILE_DATE_FORMAT.format(ZonedDateTime.now()) + "_" + fileName; LOG.info("Writing to file '" + datedFileName + "'"); return new OutputStreamWriter(new FileOutputStream(datedFileName), Charset.forName("UTF-8")); }