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.ng200.openolympus.ContestTest.java

public Contest createContestUsingAPI(int duration) throws Exception {
    // @formatter:off
    final ZonedDateTime now = ZonedDateTime.now();

    final String result = this.mockMvc
            .perform(MockMvcRequestBuilders.post("/api/contests/create")
                    .param("name", "TestContest_" + ContestTest.id++)
                    .param("startTime", now.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME))
                    .param("duration", Integer.toString(duration)))
            .andDo(MockMvcResultHandlers.print()).andExpect(MockMvcResultMatchers.status().isOk())
            .andExpect(MockMvcResultMatchers.content().contentType(this.contentType))
            .andExpect(MockMvcResultMatchers.jsonPath("$.status").value("OK"))
            .andExpect(MockMvcResultMatchers.jsonPath("$.data.id").exists()).andReturn().getResponse()
            .getContentAsString();/* www. j  a  v a  2s .  com*/
    return this.contestRepository.findOne(Long.valueOf(JsonPath.read(result, "$.data.id").toString()));
    // @formatter:on
}

From source file:org.openhab.binding.ntp.test.NtpOSGiTest.java

@Test
public void testDateTimeChannelDefaultTimeZoneUpdate() {
    ZonedDateTime zoned = ZonedDateTime.now();

    ZoneOffset expectedTimeZone = zoned.getOffset();
    Configuration configuration = new Configuration();
    // Initialize with configuration with no time zone property set.
    initialize(configuration, NtpBindingConstants.CHANNEL_DATE_TIME, ACCEPTED_ITEM_TYPE_DATE_TIME, null, null);

    String testItemState = getItemState(ACCEPTED_ITEM_TYPE_DATE_TIME).toString();
    assertFormat(testItemState, DateTimeType.DATE_PATTERN_WITH_TZ_AND_MS);
    ZoneOffset timeZoneFromItemRegistry = new DateTimeType(testItemState).getZonedDateTime().getOffset();

    assertEquals(expectedTimeZone, timeZoneFromItemRegistry);
}

From source file:alfio.util.TemplateResource.java

private static Ticket sampleTicket(String firstName, String lastName, String email) {
    return new Ticket(0, "597e7e7b-c514-4dcb-be8c-46cf7fe2c36e", ZonedDateTime.now(), 0, "ACQUIRED", 0,
            "597e7e7b-c514-4dcb-be8c-46cf7fe2c36e", firstName + " " + lastName, firstName, lastName, email,
            false, "en", 1000, 1000, 80, 0, null);
}

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

@Override
public String execute() throws Exception {
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    try {//from w  ww.j a v  a2  s  .  c  o m
        Resource reportResource;
        if (this.getSelectedFormat().equals(APConstants.SUMMARY_FORMAT_EXCEL)) {
            reportResource = resourceManager.createDirectly(
                    this.getClass().getResource("/pentaho/crp/CaseStudiesExcel.prpt"), MasterReport.class);
        } else {
            reportResource = resourceManager.createDirectly(
                    this.getClass().getResource("/pentaho/crp/StudiesPDF.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("case_studies"), "case_studies");

        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 CaseStudy" + 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:org.cgiar.ccafs.marlo.action.summaries.StudySummaryAction.java

@Override
public String execute() throws Exception {
    if (projectExpectedStudyID == null
            || projectExpectedStudyManager.getProjectExpectedStudyById(projectExpectedStudyID) == null
            || projectExpectedStudyManager.getProjectExpectedStudyById(projectExpectedStudyID)
                    .getProjectExpectedStudyInfo(this.getSelectedPhase()) == null) {
        LOG.error("ProjectExpectedStudy " + projectExpectedStudyID + " Not found");
        return NOT_FOUND;
    } else {//  w  w  w.j av a2s . c om
        projectExpectedStudyInfo = projectExpectedStudyManager
                .getProjectExpectedStudyById(projectExpectedStudyID)
                .getProjectExpectedStudyInfo(this.getSelectedPhase());
    }
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    try {
        Resource reportResource = resourceManager
                .createDirectly(this.getClass().getResource("/pentaho/crp/StudyPDF.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("study"), "study");

        PdfReportUtil.createPDF(masterReport, os);
        bytesPDF = os.toByteArray();
        os.close();
    } catch (Exception e) {
        LOG.error("Error generating Study 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.util.TemplateResource.java

private static TicketReservation sampleTicketReservation() {
    return new TicketReservation("597e7e7b-c514-4dcb-be8c-46cf7fe2c36e", new Date(),
            TicketReservation.TicketReservationStatus.COMPLETE, "Firstname Lastname", "FirstName", "Lastname",
            "email@email.tld", "billing address", ZonedDateTime.now(), ZonedDateTime.now(), PaymentProxy.STRIPE,
            true, null, false, "en", false, null, null, null, "123456", "CH", false, new BigDecimal("8.00"),
            true);//from  w w  w. j  av  a 2s  .  c  om
}

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

/**
 * Get the main information of the report
 * /*from  w  ww .j  a v  a  2s. c  o m*/
 * @return
 */
private TypedTableModel getMasterTableModel() {
    // Initialization of Model
    TypedTableModel model = new TypedTableModel(
            new String[] { "current_date", "imageUrl", "research_program_id", "center",
                    "researchProgramTitle" },
            new Class[] { String.class, String.class, Long.class, String.class, String.class });
    String currentDate = "";
    // Get datetime
    ZonedDateTime timezone = ZonedDateTime.now();
    DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-d 'at' HH:mm ");
    currentDate = timezone.format(format) + this.getTimeZone();

    // Get CIAT imgage URL from repo
    String imageUrl = this.getBaseUrl() + "/global/images/centers/CIAT.png";

    String center = null;
    center = researchProgram.getResearchArea().getResearchCenter().getName();

    String researchProgramTitle = null;
    if (researchProgram.getName() != null && !researchProgram.getName().trim().isEmpty()) {
        researchProgramTitle = researchProgram.getName();
    }

    model.addRow(new Object[] { currentDate, imageUrl, researchProgram.getId(), center, researchProgramTitle });
    return model;
}

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

/**
 * Get the main information of the report
 * /*  w  w w.  jav a 2  s .  c om*/
 * @return
 */
private TypedTableModel getMasterTableModel() {
    // Initialization of Model
    TypedTableModel model = new TypedTableModel(
            new String[] { "title", "current_date", "imageUrl", "research_program_id" },
            new Class[] { String.class, String.class, String.class, Long.class });
    String title = "Impact Pathway Full Report";
    String currentDate = "";

    // Get title
    title = researchProgram.getResearchArea().getAcronym() + ", " + researchProgram.getComposedName()
            + ", Organized by Impact";

    // Get datetime
    ZonedDateTime timezone = ZonedDateTime.now();
    DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-d 'at' HH:mm ");
    currentDate = timezone.format(format) + this.getTimeZone();

    // Get CIAT imgage URL from repo
    String imageUrl = this.getBaseUrl() + "/global/images/centers/CIAT.png";

    model.addRow(new Object[] { title, currentDate, imageUrl, researchProgram.getId() });
    return model;
}

From source file:alfio.manager.AdminReservationManagerIntegrationTest.java

@Test
public void testReserveMixed() 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, "",
            false, 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");

    TicketCategory existingCategory = ticketCategoryRepository.findByEventId(event.getId()).get(0);

    Category resExistingCategory = new Category(existingCategory.getId(), "", existingCategory.getPrice());
    Category resNewCategory = new Category(null, "name", new BigDecimal("100.00"));
    int attendees = 1;
    List<TicketsInfo> ticketsInfoList = Arrays.asList(
            new TicketsInfo(resExistingCategory, generateAttendees(attendees), false, false),
            new TicketsInfo(resNewCategory, generateAttendees(attendees), false, false),
            new TicketsInfo(resExistingCategory, generateAttendees(attendees), false, 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 .  c om*/
    Pair<TicketReservation, List<Ticket>> data = result.getData();
    List<Ticket> tickets = data.getRight();
    assertTrue(tickets.size() == 3);
    assertNotNull(data.getLeft());
    assertTrue(tickets.stream().allMatch(t -> t.getTicketsReservationId().equals(data.getKey().getId())));
    int resExistingCategoryId = tickets.get(0).getCategoryId();
    int resNewCategoryId = tickets.get(2).getCategoryId();

    Event modified = eventManager.getSingleEvent(event.getShortName(), username);
    assertEquals(AVAILABLE_SEATS, eventRepository.countExistingTickets(event.getId()).intValue());
    assertEquals(3, ticketRepository
            .findPendingTicketsInCategories(Arrays.asList(resExistingCategoryId, resNewCategoryId)).size());
    assertEquals(3, ticketRepository.findTicketsInReservation(data.getLeft().getId()).size());

    String reservationId = data.getLeft().getId();
    assertEquals(ticketRepository.findTicketsInReservation(reservationId).stream().findFirst().get().getId(),
            ticketRepository.findFirstTicketInReservation(reservationId).get().getId());

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

From source file:com.sumzerotrading.broker.ib.InteractiveBrokersBroker.java

public ZonedDateTime getCurrentTime() {
    ibConnection.reqCurrentTime();/*  w  ww  . j av  a  2s.  com*/
    try {
        return brokerTimeQueue.poll(2, TimeUnit.SECONDS);
    } catch (InterruptedException ex) {
        logger.error(directory);
        System.out.println("Time Out waiting to get current time from broker, returning local current time");
        return ZonedDateTime.now();
    }
}