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() 

Source Link

Document

Obtains the current date-time from the system clock in the default time-zone.

Usage

From source file:org.apache.james.jmap.model.MailboxMessageTest.java

@Test(expected = IllegalStateException.class)
public void buildShouldThrowWhenAttachedMessageIsNotMatchingAttachments() {
    Attachment simpleAttachment = Attachment.builder().blobId(BlobId.of("blobId")).type("type").name("name")
            .size(123).build();//from  w  w w .ja  v a2s.  c  om
    ImmutableList<Attachment> attachments = ImmutableList.of(simpleAttachment);
    SubMessage simpleMessage = SubMessage.builder().headers(ImmutableMap.of("key", "value")).subject("subject")
            .date(ZonedDateTime.now()).build();
    ImmutableMap<BlobId, SubMessage> attachedMessages = ImmutableMap.of(BlobId.of("differentBlobId"),
            simpleMessage);
    Message.builder().id(MessageId.of("user|box|1")).blobId(BlobId.of("blobId")).threadId("threadId")
            .mailboxIds(ImmutableList.of("mailboxId")).headers(ImmutableMap.of("key", "value"))
            .subject("subject").size(123).date(ZonedDateTime.now()).preview("preview").attachments(attachments)
            .attachedMessages(attachedMessages).build();
}

From source file:org.cgiar.ccafs.marlo.action.summaries.ProjectHighlightsSummaryAction.java

@Override
public String execute() throws Exception {
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    try {/*  ww w  . ja  v a  2s.  c  o  m*/
        Resource reportResource;
        if (this.getSelectedFormat().equals(APConstants.SUMMARY_FORMAT_EXCEL)) {
            reportResource = resourceManager.createDirectly(
                    this.getClass().getResource("/pentaho/crp/ProjectHighlightsExcel.prpt"),
                    MasterReport.class);
        } else {
            reportResource = resourceManager.createDirectly(
                    this.getClass().getResource("/pentaho/crp/ProjectHighlightsPDF.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 date = timezone.format(format) + "(GMT" + zone + ")";
        // Set Main_Query
        CompoundDataFactory cdf = CompoundDataFactory.normalize(masterReport.getDataFactory());
        String masterQueryName = "main";
        TableDataFactory sdf = (TableDataFactory) cdf.getDataFactoryForQuery(masterQueryName);
        TypedTableModel model = this.getMasterTableModel(center, date, String.valueOf(this.getSelectedYear()));
        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("project_highlight"), "project_highlight");
        if (this.getSelectedFormat().equals(APConstants.SUMMARY_FORMAT_EXCEL)) {
            ExcelReportUtil.createXLSX(masterReport, os);
            bytesXLSX = os.toByteArray();
        } else {
            PdfReportUtil.createPDF(masterReport, os);
            bytesPDF = os.toByteArray();
        }
        os.close();
    } catch (Exception e) {
        LOG.error("Error generating ProjectHighlights" + this.getSelectedFormat() + ": " + 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()
            + ". Time to generate: " + stopTime + "ms.");
    return SUCCESS;
}

From source file:alfio.manager.CheckInManager.java

public boolean revertCheckIn(int eventId, String ticketIdentifier, String user) {
    return findAndLockTicket(ticketIdentifier).map((t) -> {
        if (t.getStatus() == TicketStatus.CHECKED_IN) {
            TicketReservation reservation = ticketReservationRepository
                    .findReservationById(t.getTicketsReservationId());
            TicketStatus revertedStatus = reservation.getPaymentMethod() == PaymentProxy.ON_SITE
                    ? TicketStatus.TO_BE_PAID
                    : TicketStatus.ACQUIRED;
            ticketRepository.updateTicketStatusWithUUID(ticketIdentifier, revertedStatus.toString());
            scanAuditRepository.insert(ticketIdentifier, eventId, ZonedDateTime.now(), user,
                    OK_READY_TO_BE_CHECKED_IN, ScanAudit.Operation.REVERT);
            auditingRepository.insert(t.getTicketsReservationId(),
                    userRepository.findIdByUserName(user).orElse(null), eventId,
                    Audit.EventType.REVERT_CHECK_IN, new Date(), Audit.EntityType.TICKET,
                    Integer.toString(t.getId()));
            return true;
        }//  w  w  w . j av a 2  s  .  c o m
        return false;
    }).orElse(false);
}

From source file:org.cgiar.ccafs.marlo.action.summaries.ProjectHighlightSummaryAction.java

@Override
public String execute() throws Exception {
    if (projectHighlightID == null
            || projectHighLightManager.getProjectHighligthById(projectHighlightID) == null
            || projectHighLightManager.getProjectHighligthById(projectHighlightID)
                    .getProjectHighlightInfo(this.getSelectedPhase()) == null) {
        LOG.error("Project Highlight " + projectHighlightID + " Not found");
        return NOT_FOUND;
    } else {/*from  w w  w.java  2s  .co  m*/
        projectHighlightInfo = projectHighLightManager.getProjectHighligthById(projectHighlightID)
                .getProjectHighlightInfo(this.getSelectedPhase());
    }
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    try {
        Resource reportResource = resourceManager.createDirectly(
                this.getClass().getResource("/pentaho/crp/ProjectHighlightPDF.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 date = timezone.format(format) + "(GMT" + zone + ")";
        // Set Main_Query
        CompoundDataFactory cdf = CompoundDataFactory.normalize(masterReport.getDataFactory());
        String masterQueryName = "main";
        TableDataFactory sdf = (TableDataFactory) cdf.getDataFactoryForQuery(masterQueryName);
        TypedTableModel model = this.getMasterTableModel(center, date, String.valueOf(this.getSelectedYear()));
        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("project_highlight"), "project_highlight");
        PdfReportUtil.createPDF(masterReport, os);
        bytesPDF = os.toByteArray();
        os.close();
    } catch (Exception e) {
        LOG.error("Error generating ProjectHighlights Summary: " + e.getMessage());
        throw e;
    }
    // Calculate time of generation
    long stopTime = System.currentTimeMillis();
    stopTime = stopTime - startTime;
    LOG.info("Downloaded successfully: " + this.getFileName() + ". User: " + this.getDownloadByUser()
            + ". CRP: " + this.getLoggedCrp().getAcronym() + ". Time to generate: " + stopTime + "ms.");
    return SUCCESS;
}

From source file:com.streamsets.pipeline.stage.origin.jdbc.table.BaseTableJdbcSourceIT.java

protected static Object generateRandomData(Field.Type fieldType) {
    switch (fieldType) {
    case DATE:/*from  w  w w . j  av a 2 s .c  o m*/
    case DATETIME:
    case TIME:
        return getRandomDateTime(fieldType);
    case ZONED_DATETIME:
        return ZonedDateTime.now();
    case DOUBLE:
        return RANDOM.nextDouble();
    case FLOAT:
        return RANDOM.nextFloat();
    case SHORT:
        return (short) RANDOM.nextInt(Short.MAX_VALUE + 1);
    case INTEGER:
        return RANDOM.nextInt();
    case LONG:
        return RANDOM.nextLong();
    case CHAR:
        return UUID.randomUUID().toString().charAt(0);
    case STRING:
        return UUID.randomUUID().toString();
    case DECIMAL:
        return new BigDecimal(BigInteger.valueOf(RANDOM.nextLong() % (long) Math.pow(10, 20)), 10);
    default:
        return null;
    }
}

From source file:com.streamsets.pipeline.stage.origin.tcp.TCPObjectToRecordHandler.java

private void evaluateElAndSendResponse(ELEval eval, ELVars vars, String expression, ChannelHandlerContext ctx,
        Charset charset, boolean recordLevel, String expressionDescription) {
    if (Strings.isNullOrEmpty(expression)) {
        return;// www.ja  v  a 2  s. co m
    }
    if (lastRecord != null) {
        RecordEL.setRecordInContext(vars, lastRecord);
    }
    final Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone(ZoneId.of(timeZoneId)));
    TimeEL.setCalendarInContext(vars, calendar);
    TimeNowEL.setTimeNowInContext(vars, Date.from(ZonedDateTime.now().toInstant()));
    final String elResult;
    try {
        elResult = eval.eval(vars, expression, String.class);
        ctx.writeAndFlush(Unpooled.copiedBuffer(elResult, charset));
    } catch (ELEvalException exception) {
        if (LOG.isErrorEnabled()) {
            LOG.error(String.format("ELEvalException caught attempting to evaluate %s expression",
                    expressionDescription), exception);
        }

        if (recordLevel) {
            switch (context.getOnErrorRecord()) {
            case DISCARD:
                // do nothing
                break;
            case STOP_PIPELINE:
                if (LOG.isErrorEnabled()) {
                    LOG.error(String.format(
                            "ELEvalException caught when evaluating %s expression to send client response; failing pipeline %s"
                                    + " as per stage configuration: %s",
                            expressionDescription, context.getPipelineId(), exception.getMessage()), exception);
                }
                stopPipelineHandler.stopPipeline(context.getPipelineId(), exception);
                break;
            case TO_ERROR:
                Record errorRecord = lastRecord != null ? lastRecord : context.createRecord(generateRecordId());
                batchContext.toError(errorRecord, exception);
                break;
            }
        } else {
            context.reportError(Errors.TCP_35, expressionDescription, exception.getMessage(), exception);
        }
    }
}

From source file:com.sumzerotrading.reporting.csv.ReportGeneratorTest.java

@Test
public void testOrderEvent_RoundTripExists_ButNotComplete() 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);

    reportGenerator.roundTripMap.put("123", roundTrip);

    doReturn(longExitLine).when(reportGenerator).getTradeReferenceLine(any(String.class));
    doNothing().when(reportGenerator).savePartial(any(String.class), any(PairTradeRoundTrip.class));
    assertEquals(1, reportGenerator.roundTripMap.size());

    reportGenerator.orderEvent(orderEvent);

    verify(reportGenerator).savePartial("123", roundTrip);
    verify(reportGenerator, never()).writeRoundTripToFile(any(PairTradeRoundTrip.class));

    assertEquals(1, reportGenerator.roundTripMap.size());
}

From source file:com.sumzerotrading.eod.trading.strategy.ReportGeneratorTest.java

@Test
public void testOrderEvent_RoundTripComplete() throws Exception {
    RoundTrip roundTrip = new RoundTrip();
    TradeReferenceLine tradeReferenceLine = buildReferenceLine("123", LONG, ENTRY);
    tradeReferenceLine.correlationId = "123";
    tradeReferenceLine.direction = TradeReferenceLine.Direction.LONG;
    tradeReferenceLine.side = TradeReferenceLine.Side.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(RoundTrip.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:org.cgiar.ccafs.marlo.action.summaries.ProjectInnovationSummaryAction.java

@Override
public String execute() throws Exception {
    if (projectInnovationID == null
            || projectInnovationManager.getProjectInnovationById(projectInnovationID) == null
            || projectInnovationManager.getProjectInnovationById(projectInnovationID)
                    .getProjectInnovationInfo(this.getSelectedPhase()) == null) {
        LOG.error("Project Innovation " + projectInnovationID + " Not found");
        return NOT_FOUND;
    } else {/*from  w ww .j  a  v a2 s.  c o  m*/
        projectInnovationInfo = projectInnovationManager.getProjectInnovationById(projectInnovationID)
                .getProjectInnovationInfo(this.getSelectedPhase());
    }
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    try {
        Resource reportResource = resourceManager.createDirectly(
                this.getClass().getResource("/pentaho/crp/ProjectInnovationPDF.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 date = timezone.format(format) + "(GMT" + zone + ")";
        // Set Main_Query
        CompoundDataFactory cdf = CompoundDataFactory.normalize(masterReport.getDataFactory());
        String masterQueryName = "main";
        TableDataFactory sdf = (TableDataFactory) cdf.getDataFactoryForQuery(masterQueryName);
        TypedTableModel model = this.getMasterTableModel(center, date, String.valueOf(this.getSelectedYear()));
        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("project_innovation"), "project_innovation");
        PdfReportUtil.createPDF(masterReport, os);
        bytesPDF = os.toByteArray();
        os.close();
    } catch (Exception e) {
        LOG.error("Error generating ProjectInnovation Summary: " + e.getMessage());
        throw e;
    }
    // Calculate time of generation
    long stopTime = System.currentTimeMillis();
    stopTime = stopTime - startTime;
    LOG.info("Downloaded successfully: " + this.getFileName() + ". User: " + this.getDownloadByUser()
            + ". CRP: " + this.getLoggedCrp().getAcronym() + ". Time to generate: " + stopTime + "ms.");
    return SUCCESS;
}

From source file:alfio.manager.AdminReservationManagerIntegrationTest.java

@Test
public void testReserveFromNewCategory() throws Exception {
    List<TicketCategoryModification> categories = Collections.singletonList(new TicketCategoryModification(null,
            "default", 1, new DateTimeModification(LocalDate.now(), LocalTime.now()),
            new DateTimeModification(LocalDate.now(), LocalTime.now()), DESCRIPTION, BigDecimal.TEN, false, "",
            true, null, null, null, null, null));
    Pair<Event, String> eventWithUsername = initEvent(categories, organizationRepository, userManager,
            eventManager, eventRepository);
    Event event = eventWithUsername.getKey();
    String username = eventWithUsername.getValue();
    DateTimeModification expiration = DateTimeModification.fromZonedDateTime(ZonedDateTime.now().plusDays(1));
    CustomerData customerData = new CustomerData("Integration", "Test", "integration-test@test.ch",
            "Billing Address", "en");
    Category category = new Category(null, "name", new BigDecimal("100.00"));
    int attendees = AVAILABLE_SEATS;
    List<TicketsInfo> ticketsInfoList = Collections
            .singletonList(new TicketsInfo(category, generateAttendees(attendees), true, false));
    AdminReservationModification modification = new AdminReservationModification(expiration, customerData,
            ticketsInfoList, "en", false, null);
    Result<Pair<TicketReservation, List<Ticket>>> result = adminReservationManager
            .createReservation(modification, event.getShortName(), username);
    assertTrue(result.isSuccess());/*from  w  w  w .j a  v a 2s .  co  m*/
    Pair<TicketReservation, List<Ticket>> data = result.getData();
    List<Ticket> tickets = data.getRight();
    assertTrue(tickets.size() == attendees);
    assertNotNull(data.getLeft());
    int categoryId = tickets.get(0).getCategoryId();
    Event modified = eventManager.getSingleEvent(event.getShortName(), username);
    assertEquals(attendees + 1, eventRepository.countExistingTickets(event.getId()).intValue());
    assertEquals(attendees,
            ticketRepository.findPendingTicketsInCategories(Collections.singletonList(categoryId)).size());
    TicketCategory categoryModified = ticketCategoryRepository.getByIdAndActive(categoryId, event.getId());
    assertEquals(categoryModified.getMaxTickets(), attendees);
    ticketCategoryRepository.findByEventId(event.getId())
            .forEach(tc -> assertTrue(specialPriceRepository.findAllByCategoryId(tc.getId()).stream()
                    .allMatch(sp -> sp.getStatus() == SpecialPrice.Status.PENDING)));
    adminReservationManager.confirmReservation(event.getShortName(), data.getLeft().getId(), username);
    ticketCategoryRepository.findByEventId(event.getId())
            .forEach(tc -> assertTrue(specialPriceRepository.findAllByCategoryId(tc.getId()).stream()
                    .allMatch(sp -> sp.getStatus() == SpecialPrice.Status.TAKEN)));
    assertFalse(ticketRepository.findAllReservationsConfirmedButNotAssigned(event.getId())
            .contains(data.getLeft().getId()));
}