Example usage for java.time ZoneId systemDefault

List of usage examples for java.time ZoneId systemDefault

Introduction

In this page you can find the example usage for java.time ZoneId systemDefault.

Prototype

public static ZoneId systemDefault() 

Source Link

Document

Gets the system default time-zone.

Usage

From source file:dk.dbc.rawrepo.oai.ResumptionTokenTest.java

@Test
public void testXmlExpiration() throws Exception {
    ObjectNode jsonOriginal = (ObjectNode) new ObjectMapper().readTree("{\"foo\":\"bar\"}");

    long now = Instant.now().getEpochSecond();
    ResumptionTokenType token = ResumptionToken.toToken(jsonOriginal, 0);

    OAIPMH oaipmh = OBJECT_FACTORY.createOAIPMH();
    ListRecordsType getRecord = OBJECT_FACTORY.createListRecordsType();
    oaipmh.setListRecords(getRecord);//from   ww  w  .ja  va  2  s .c o m
    getRecord.setResumptionToken(token);
    JAXBContext context = JAXBContext.newInstance(OAIPMH.class);
    StringWriter writer = new StringWriter();
    Marshaller marshaller = context.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    marshaller.marshal(oaipmh, writer);
    String xml = writer.getBuffer().toString();
    System.out.println("XML is:\n" + xml);
    int start = xml.indexOf("expirationDate=\"") + "expirationDate=\"".length();
    int end = xml.indexOf("\"", start);
    String timestamp = xml.substring(start, end);
    System.out.println("timestamp = " + timestamp);

    assertTrue("Timestamp should be in ISO_INSTANT ending with Z", timestamp.endsWith("Z"));
    TemporalAccessor parse = DateTimeFormatter.ISO_INSTANT.withZone(ZoneId.systemDefault()).parse(timestamp);
    long epochSecond = Instant.from(parse).getEpochSecond();
    long diff = Math.abs(now - epochSecond);
    System.out.println("diff = " + diff);
    assertTrue("Difference between expirationdate and now should be 10 sec or less", diff <= 10);
}

From source file:retsys.client.controller.PurchaseOrderConfirmController.java

private void populateData(PurchaseOrder po) {
    po_no.setText(po.getId().toString());
    po_date.setValue(LocalDateTime.ofInstant(po.getDate().toInstant(), ZoneId.systemDefault()).toLocalDate());
    po_no.setText(po.getId().toString());
    delivery_address.setText(po.getDeliveryAddress());
    vendor.setText(po.getVendor().getName() + " (ID:" + po.getVendor().getId() + ")");
    project.setText(po.getProject().getName() + " (ID:" + po.getProject().getId() + ")");

    ObservableList<POItem> items = FXCollections.observableArrayList();
    Iterator detailsIt = po.getPurchaseOrderDetail().iterator();
    while (detailsIt.hasNext()) {
        PurchaseOrderDetail detail = (PurchaseOrderDetail) detailsIt.next();
        Item item = detail.getItem();/*from w  ww.  ja  v  a 2s  .c o  m*/
        int id = item.getId();
        String site = item.getSite();
        String name = item.getName();
        String brand = item.getBrand();
        String model = null;
        Double quantity = detail.getQuantity();
        Boolean confirm = "Y".equals(detail.getConfirm());

        items.add(new POItem(detail.getId(), site, name + " (ID:" + id + ")", brand, model, quantity, confirm,
                detail.getReceivedDate()));
    }
    poDetail.setItems(items);
    System.out.println(po.getAudit());
    populateAuditValues(po);
}

From source file:com.bofa.sstradingreport.managementreport.TradeReportControllerTest.java

@Test
public void shouldgetTradeReports() throws Exception {
    final List<TradeReportEntity> allbikes = Arrays.asList(
            Reflect.on(TradeReportEntity.class).create().set("id", 4711).set("name", "Bike 1")
                    .set("tradeDate",
                            GregorianCalendar.from(
                                    LocalDate.of(2015, Month.JANUARY, 1).atStartOfDay(ZoneId.systemDefault())))
                    .call("getTradeReport").get(),
            Reflect.on(TradeReportEntity.class).create().set("id", 23)
                    .set("tradeDate",
                            GregorianCalendar.from(
                                    LocalDate.of(2014, Month.JANUARY, 1).atStartOfDay(ZoneId.systemDefault())))
                    .call("getTradeReport").get());
    final List<TradeReportEntity> activeBikes = Arrays.asList(allbikes.get(0));

    final TradeReportRepository repository = mock(TradeReportRepository.class);
    stub(repository.findAll(any(Sort.class))).toReturn(allbikes);
    //   stub(repository.findByDecaommissionedOnIsNull(any(Sort.class))).toReturn(activeBikes);

    final TradeReportController controller = new TradeReportController(repository);

    final MockMvc mockMvc = MockMvcBuilders.standaloneSetup(controller)
            .setControllerAdvice(new ExceptionHandlerAdvice())
            .apply(documentationConfiguration(this.restDocumentation)).build();

    mockMvc.perform(get("http://localhost:8088/sstradingreport/api/bikes").param("all", "true"))
            .andExpect(status().isOk()).andExpect(content().string(objectMapper.writeValueAsString(allbikes)))
            .andDo(document("api/bikes/get", preprocessRequest(prettyPrint()),
                    preprocessResponse(prettyPrint()),
                    requestParameters(parameterWithName("all").description(
                            "Flag, if all bikes, including decommissioned bikes, should be returned.")),
                    responseFields(fieldWithPath("[]").description("An array of bikes"),
                            fieldWithPath("[].id").description("The unique Id of the bike"),
                            fieldWithPath("[].name").description("The name of the bike"),
                            fieldWithPath("[].tradeDate").description("The date the bike was bought"))));

    mockMvc.perform(get("http://biking.michael-simons.eu/api/bikes")).andExpect(status().isOk())
            .andExpect(content().string(objectMapper.writeValueAsString(activeBikes)));

    Mockito.verify(repository).findAll(Mockito.any(Sort.class));
    //   Mockito.verify(repository).findByDecommissionedOnIsNull(Mockito.any(Sort.class));
    verifyNoMoreInteractions(repository);
}

From source file:RequestStat.java

private String getDateFromInstant(long start) {
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd " + "HH:mm:ss")
            .withZone(ZoneId.systemDefault());
    return formatter.format(Instant.ofEpochMilli(start));
}

From source file:cn.afterturn.easypoi.excel.export.base.ExportCommonService.java

private Object dateFormatValue(Object value, ExcelExportEntity entity) throws Exception {
    Date temp = null;/*from  w  w w  . j  av  a 2  s .  co m*/
    if (value instanceof String && StringUtils.isNoneEmpty(value.toString())) {
        SimpleDateFormat format = new SimpleDateFormat(entity.getDatabaseFormat());
        temp = format.parse(value.toString());
    } else if (value instanceof Date) {
        temp = (Date) value;
    } else if (value instanceof Instant) {
        Instant instant = (Instant) value;
        temp = Date.from(instant);
    } else if (value instanceof LocalDate) {
        LocalDate localDate = (LocalDate) value;
        temp = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
    } else if (value instanceof LocalDateTime) {
        LocalDateTime localDateTime = (LocalDateTime) value;
        temp = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
    } else if (value instanceof java.sql.Date) {
        temp = new Date(((java.sql.Date) value).getTime());
    } else if (value instanceof java.sql.Time) {
        temp = new Date(((java.sql.Time) value).getTime());
    } else if (value instanceof java.sql.Timestamp) {
        temp = new Date(((java.sql.Timestamp) value).getTime());
    }
    if (temp != null) {
        SimpleDateFormat format = new SimpleDateFormat(entity.getFormat());
        if (StringUtils.isNotEmpty(entity.getTimezone())) {
            format.setTimeZone(TimeZone.getTimeZone(entity.getTimezone()));
        }
        value = format.format(temp);
    }
    return value;
}

From source file:cn.afterturn.easypoi.excel.imports.CellValueService.java

/**
 * ??//from w  ww .  ja  va2s .co m
 *
 * @param cell
 * @param entity
 * @return
 */
private Object getCellValue(String classFullName, Cell cell, ExcelImportEntity entity) {
    if (cell == null) {
        return "";
    }
    Object result = null;
    if ("class java.util.Date".equals(classFullName) || "class java.sql.Date".equals(classFullName)
            || ("class java.sql.Time").equals(classFullName)
            || ("class java.time.Instant").equals(classFullName)
            || ("class java.time.LocalDate").equals(classFullName)
            || ("class java.time.LocalDateTime").equals(classFullName)
            || ("class java.sql.Timestamp").equals(classFullName)) {
        //FIX: ?yyyyMMdd cell.getDateCellValue() ?
        if (CellType.NUMERIC == cell.getCellType() && DateUtil.isCellDateFormatted(cell)) {
            result = DateUtil.getJavaDate(cell.getNumericCellValue());
        } else {
            String val = "";
            try {
                val = cell.getStringCellValue();
            } catch (Exception e) {
                cell.setCellType(CellType.STRING);
                val = cell.getStringCellValue();
            }

            result = getDateData(entity, val);
            if (result == null) {
                return null;
            }
        }
        if (("class java.time.Instant").equals(classFullName)) {
            result = ((Date) result).toInstant();
        } else if (("class java.time.LocalDate").equals(classFullName)) {
            result = ((Date) result).toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        } else if (("class java.time.LocalDateTime").equals(classFullName)) {
            result = ((Date) result).toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
        } else if (("class java.sql.Date").equals(classFullName)) {
            result = new java.sql.Date(((Date) result).getTime());
        } else if (("class java.sql.Time").equals(classFullName)) {
            result = new Time(((Date) result).getTime());
        } else if (("class java.sql.Timestamp").equals(classFullName)) {
            result = new Timestamp(((Date) result).getTime());
        }
    } else {
        switch (cell.getCellType()) {
        case STRING:
            result = cell.getRichStringCellValue() == null ? "" : cell.getRichStringCellValue().getString();
            break;
        case NUMERIC:
            if (DateUtil.isCellDateFormatted(cell)) {
                if ("class java.lang.String".equals(classFullName)) {
                    result = formateDate(entity, cell.getDateCellValue());
                }
            } else {
                result = readNumericCell(cell);
            }
            break;
        case BOOLEAN:
            result = Boolean.toString(cell.getBooleanCellValue());
            break;
        case BLANK:
            break;
        case ERROR:
            break;
        case FORMULA:
            try {
                result = readNumericCell(cell);
            } catch (Exception e1) {
                try {
                    result = cell.getRichStringCellValue() == null ? ""
                            : cell.getRichStringCellValue().getString();
                } catch (Exception e2) {
                    throw new RuntimeException("???", e2);
                }
            }
            break;
        default:
            break;
        }
    }
    return result;
}

From source file:com.example.controller.user.OrderController.java

@RequestMapping(value = "/order", method = RequestMethod.DELETE)
public String delete() {
    if (DataHelper.isCanCreateOrder()) {
        orderRepository.deleteByCustomerLoginAndUpdatedBetween(
                SecurityContextHolder.getContext().getAuthentication().getName(),
                DataHelper.getYesterdayOrderTime(), DataHelper.getTodayOrderTime());
        return "ok";

    } else/*from   w w w. j  a v  a 2  s.com*/
        return "Can't delete order, you can delete order only before 11:00 by" + ZoneId.systemDefault().getId();
}

From source file:me.rkfg.xmpp.bot.plugins.FaggotOfTheDayPlugin.java

private Date getFirstTime() {
    final LocalTime midnight = LocalTime.MIDNIGHT;
    final LocalDate today = LocalDate.now();
    final LocalDateTime todayMidnight = LocalDateTime.of(today, midnight);
    return Date.from(todayMidnight.atZone(ZoneId.systemDefault()).toInstant());
}

From source file:ca.phon.session.io.xml.v12.XMLSessionWriter_v12.java

/**
 * Create a new jaxb version of the session
 * //from  w  w  w  . java  2  s  .  c  o m
 * @param session
 * @return an version of the session use-able by jaxb 
 */
private JAXBElement<SessionType> toSessionType(Session session) throws IOException {
    final ObjectFactory factory = new ObjectFactory();
    final SessionType retVal = factory.createSessionType();

    // header data
    retVal.setVersion("PB1.2");
    retVal.setId(session.getName());
    retVal.setCorpus(session.getCorpus());

    final HeaderType headerData = factory.createHeaderType();
    if (session.getMediaLocation() != null && session.getMediaLocation().length() > 0) {
        headerData.setMedia(session.getMediaLocation());
    }
    final LocalDate date = (session.getDate() == null ? LocalDate.now() : session.getDate());
    try {
        final DatatypeFactory df = DatatypeFactory.newInstance();
        final XMLGregorianCalendar cal = df
                .newXMLGregorianCalendar(GregorianCalendar.from(date.atStartOfDay(ZoneId.systemDefault())));
        cal.setTimezone(DatatypeConstants.FIELD_UNDEFINED);
        headerData.setDate(cal);
    } catch (DatatypeConfigurationException e) {
        LOGGER.log(Level.WARNING, e.getMessage(), e);
    }
    final String lang = session.getLanguage();
    if (lang != null && lang.length() > 0) {
        final String langs[] = lang.split("\\p{Space}");
        for (String l : langs) {
            headerData.getLanguage().add(l);
        }
    }
    retVal.setHeader(headerData);

    final TranscriptType transcript = factory.createTranscriptType();
    // commets
    for (int i = 0; i < session.getMetadata().getNumberOfComments(); i++) {
        final Comment c = session.getMetadata().getComment(i);
        final CommentType ct = copyComment(factory, c);
        transcript.getUOrComment().add(ct);
    }

    // participants
    final ParticipantsType parts = factory.createParticipantsType();
    for (int i = 0; i < session.getParticipantCount(); i++) {
        final Participant part = session.getParticipant(i);
        final ParticipantType pt = copyParticipant(factory, part);
        parts.getParticipant().add(pt);
    }
    retVal.setParticipants(parts);

    // transcribers
    final TranscribersType tt = factory.createTranscribersType();
    for (int i = 0; i < session.getTranscriberCount(); i++) {
        final Transcriber tr = session.getTranscriber(i);
        final TranscriberType trt = copyTranscriber(factory, tr);
        tt.getTranscriber().add(trt);
    }
    retVal.setTranscribers(tt);

    // tier info/ordering
    final UserTiersType utt = factory.createUserTiersType();
    for (int i = 0; i < session.getUserTierCount(); i++) {
        final TierDescription td = session.getUserTier(i);
        final UserTierType tierType = copyTierDescription(factory, td);
        utt.getUserTier().add(tierType);
    }
    retVal.setUserTiers(utt);

    final TierOrderType tot = factory.createTierOrderType();
    for (TierViewItem tvi : session.getTierView()) {
        final TvType tvt = copyTierViewItem(factory, tvi);
        tot.getTier().add(tvt);
    }
    retVal.setTierOrder(tot);

    // session data
    for (int i = 0; i < session.getRecordCount(); i++) {
        final Record record = session.getRecord(i);

        // insert comments first
        for (int j = 0; j < record.getNumberOfComments(); j++) {
            final Comment com = record.getComment(j);
            final CommentType ct = copyComment(factory, com);
            transcript.getUOrComment().add(ct);
        }

        // copy record data
        final RecordType rt = copyRecord(factory, retVal, record);

        rt.setId(record.getUuid().toString());

        if (record.isExcludeFromSearches())
            rt.setExcludeFromSearches(record.isExcludeFromSearches());

        // setup participant
        if (record.getSpeaker() != null) {
            for (ParticipantType pt : parts.getParticipant()) {
                if (pt.getId().equals(record.getSpeaker().getId())) {
                    rt.setSpeaker(pt);
                    break;
                }
            }
        }

        transcript.getUOrComment().add(rt);
    }
    retVal.setTranscript(transcript);

    return factory.createSession(retVal);
}

From source file:com.gigglinggnus.controllers.StudentMakeAppointmentController.java

/**
 *
 * @param request servlet request/*w w  w.  j a va2s .co m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    EntityManager em = (EntityManager) request.getSession().getAttribute("em");

    String msg = request.getParameter("msg");
    User user = (User) (request.getSession().getAttribute("user"));
    Clock clk = (Clock) (request.getSession().getAttribute("clock"));

    if (msg.equals("lookup_student")) {
        String studId = request.getParameter("studentId");
        List<Exam> exams = user.getRegistrableExams();
        JSONObject json = new JSONObject();
        json.put("students_idNumber", studId);
        json.put("firstName", user.getFirstName());
        json.put("lastName", user.getLastName());
        JSONArray jExams = new JSONArray();
        for (Exam exam : exams) {
            JSONObject elem = new JSONObject();

            String examId = exam.getExamId();
            String termId = exam.getTerm().getTermId();
            String start = exam.getInterval().getStart().atZone(ZoneId.systemDefault()).toLocalDate()
                    .toString();
            String end = exam.getInterval().getEnd().atZone(ZoneId.systemDefault()).toLocalDate().toString();
            elem.put("examId", examId);
            elem.put("termId", termId);
            if (exam instanceof CourseExam) {
                String courseId = ((CourseExam) exam).getCourse().getCourseId();
                elem.put("courseId", courseId);
                elem.put("examType", "Course");
            } else {
                elem.put("courseId", "N/A");
                elem.put("examType", "AdHoc");
            }
            elem.put("start", start);
            elem.put("end", end);
            jExams.put(elem);
        }
        json.put("exams", jExams);
        response.getWriter().write(json.toString());
    } else if (msg.equals("exam_available_timeslots")) {
        String examId = request.getParameter("examId");
        String dateStr = request.getParameter("date");
        Exam exam = em.find(Exam.class, examId);
        LocalDate apptDate = LocalDate.parse(dateStr);
        List<LocalTime> timeslots = exam.getTimeslotsForDay(apptDate);

        JSONObject json = new JSONObject();
        json.put("examId", examId);
        JSONArray jTimeSlots = new JSONArray();
        for (LocalTime timeslot : timeslots) {
            String start = timeslot.toString();
            String end = timeslot.plus(exam.getDuration()).toString();
            JSONObject elem = new JSONObject();
            elem.put("start", start);
            elem.put("end", end);
            jTimeSlots.put(elem);
        }
        json.put("timeSlots", jTimeSlots);
        response.getWriter().write(json.toString());
    } else if (msg.equals("submit-appointment")) {
        String studId = request.getParameter("studentId");
        String examId = request.getParameter("examId");
        String stDate = request.getParameter("examDate");
        String stTime = request.getParameter("startTime") + ":00";
        String stSeat = request.getParameter("seatType");

        Exam exam = em.find(Exam.class, examId);
        LocalDate lDate = LocalDate.parse(stDate);
        LocalTime lTime = LocalTime.parse(stTime);
        Instant inst = ZonedDateTime.of(lDate, lTime, ZoneId.systemDefault()).toInstant();
        JSONObject json = new JSONObject();
        try {
            em.getTransaction().begin();
            user.makeAppointment(exam, inst, clk);
            em.getTransaction().commit();
            json.put("success", "Appointment Made!");
            response.getWriter().write(json.toString());
        } catch (Exception e) {
            em.getTransaction().rollback();
            json.put("error", e.toString());
            response.getWriter().write(json.toString());
        }
    } else {
        JSONObject json = new JSONObject();
        json.put("error", msg);
        response.getWriter().write(json.toString());
    }
}