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:bzzAgent.BiteSizedBzzDaoJpa.java

@Override
public boolean memberHasBSBActivities(String username) {
    Validate.notBlank(username, "username was missing");
    Instant cutoff = LocalDate.now().atStartOfDay(ZoneId.systemDefault()).toInstant();

    final StringBuilder sql = new StringBuilder("from BsbAgentActivityEntity bsbaae ")
            .append(" left join fetch bsbaae.incentives incentive ")
            .append(" where bsbaae.username = :username ").append(" and bsbaae.campaignInviteStatus in (1,2)") //'New', 'Viewed'
            .append(" and bsbaae.startDate < '" + cutoff + "' and bsbaae.endDate > '" + cutoff + "'");

    final TypedQuery<BsbAgentActivityEntity> query2 = em
            .createQuery(sql.toString(), BsbAgentActivityEntity.class).setParameter("username", username);

    return BzzUtil.isNotEmpty(query2.getResultList());
}

From source file:de.alpharogroup.user.service.UserTokensBusinessService.java

/**
 * New user tokens.//  w  w w .  j av a2  s .c om
 *
 * @param username
 *            the username
 * @return the user tokens
 */
private UserTokens newUserTokens(String username) {
    UserTokens userTokens;
    // expires in one year
    Date expiry = Date.from(LocalDateTime.now().plusMonths(12).atZone(ZoneId.systemDefault()).toInstant());
    // create a token
    String token = RandomExtensions.randomToken();
    userTokens = UserTokens.builder().expiry(expiry).username(username).token(token).build();
    return userTokens;
}

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

/**
 *
 * @param request servlet request//w  ww.  j  a v a  2 s .c  o  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");
        User student = em.find(User.class, studId);
        List<Exam> exams = student.getRegistrableExams();
        JSONObject json = new JSONObject();
        json.put("students_idNumber", studId);
        json.put("firstName", student.getFirstName());
        json.put("lastName", student.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");

        User student = em.find(User.class, studId);
        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();
            if (stSeat.equals("normal")) {
                user.makeAppointment(student, Seating.NORMAL, exam, inst, clk);
                em.getTransaction().commit();
                json.put("success", "Appointment Made!");
                response.getWriter().write(json.toString());
            } else if (stSeat.equals("setaside")) {
                user.makeAppointment(student, Seating.SETASIDE, exam, inst, clk);
                em.getTransaction().commit();
                json.put("success", "Appointment Made!");
                response.getWriter().write(json.toString());
            } else {
                em.getTransaction().rollback();
                json.put("error", "invalid choice of seating");
                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());
    }
}

From source file:alfio.test.util.IntegrationTestUtil.java

public static Pair<Event, String> initEvent(List<TicketCategoryModification> categories,
        OrganizationRepository organizationRepository, UserManager userManager, EventManager eventManager,
        EventRepository eventRepository) {

    String organizationName = UUID.randomUUID().toString();
    String username = UUID.randomUUID().toString();
    String eventName = UUID.randomUUID().toString();

    userManager.createOrganization(organizationName, "org", "email@example.com");
    Organization organization = organizationRepository.findByName(organizationName).get();
    userManager.insertUser(organization.getId(), username, "test", "test", "test@example.com", Role.OPERATOR,
            User.Type.INTERNAL);
    userManager.insertUser(organization.getId(), username + "_owner", "test", "test", "test@example.com",
            Role.OWNER, User.Type.INTERNAL);

    LocalDateTime expiration = LocalDateTime.now().plusDays(5).plusHours(1);

    Map<String, String> desc = new HashMap<>();
    desc.put("en", "muh description");
    desc.put("it", "muh description");
    desc.put("de", "muh description");

    EventModification em = new EventModification(null, Event.EventType.INTERNAL, "url", "url", "url", "url",
            null, eventName, "event display name", organization.getId(), "muh location", "0.0", "0.0",
            ZoneId.systemDefault().getId(), desc,
            new DateTimeModification(LocalDate.now().plusDays(5), LocalTime.now()),
            new DateTimeModification(expiration.toLocalDate(), expiration.toLocalTime()), BigDecimal.TEN, "CHF",
            AVAILABLE_SEATS, BigDecimal.ONE, true, Collections.singletonList(PaymentProxy.OFFLINE), categories,
            false, new LocationDescriptor("", "", "", ""), 7, null, null);
    eventManager.createEvent(em);/*from w  ww. jav  a2s .  c  om*/
    Event event = eventManager.getSingleEvent(eventName, username);
    Assert.assertEquals(AVAILABLE_SEATS, eventRepository.countExistingTickets(event.getId()).intValue());
    return Pair.of(event, username);
}

From source file:org.nuxeo.ecm.blob.azure.AzureBinaryManager.java

@Override
protected URI getRemoteUri(String digest, ManagedBlob blob, HttpServletRequest servletRequest)
        throws IOException {
    try {/*ww  w .  j a  v a 2 s  .  com*/
        CloudBlockBlob blockBlobReference = container.getBlockBlobReference(digest);
        SharedAccessBlobPolicy policy = new SharedAccessBlobPolicy();
        policy.setPermissionsFromString("r");

        Instant endDateTime = LocalDateTime.now().plusSeconds(directDownloadExpire)
                .atZone(ZoneId.systemDefault()).toInstant();
        policy.setSharedAccessExpiryTime(Date.from(endDateTime));

        SharedAccessBlobHeaders headers = new SharedAccessBlobHeaders();
        headers.setContentDisposition(getContentDispositionHeader(blob, servletRequest));
        headers.setContentType(getContentTypeHeader(blob));

        String sas = blockBlobReference.generateSharedAccessSignature(policy, headers, null);

        CloudBlockBlob signedBlob = new CloudBlockBlob(blockBlobReference.getUri(),
                new StorageCredentialsSharedAccessSignature(sas));
        return signedBlob.getQualifiedUri();
    } catch (URISyntaxException | InvalidKeyException | StorageException e) {
        throw new IOException(e);
    }
}

From source file:org.apache.geode.management.internal.cli.commands.ExportLogsDUnitTest.java

@Test
public void startAndEndDateCanIncludeLogs() throws Exception {
    ZonedDateTime now = LocalDateTime.now().atZone(ZoneId.systemDefault());
    ZonedDateTime yesterday = now.minusDays(1);
    ZonedDateTime tomorrow = now.plusDays(1);

    DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(ONLY_DATE_FORMAT);

    CommandStringBuilder commandStringBuilder = new CommandStringBuilder("export logs");
    commandStringBuilder.addOption("start-time", dateTimeFormatter.format(yesterday));
    commandStringBuilder.addOption("end-time", dateTimeFormatter.format(tomorrow));
    commandStringBuilder.addOption("log-level", "debug");

    gfshConnector.executeAndVerifyCommand(commandStringBuilder.toString());

    Set<String> acceptedLogLevels = Stream.of("info", "error", "debug").collect(toSet());
    verifyZipFileContents(acceptedLogLevels);
}

From source file:org.openmrs.module.operationtheater.OperationTheaterModuleActivator.java

private Patient getEmergencyPatient(PatientIdentifierType patientIdentifierType,
        LocationService locationService) {
    Patient patient = new Patient();
    patient.setUuid(OTMetadata.PLACEHOLDER_PATIENT_UUID);

    PersonName pName = new PersonName();
    String gender = "M";
    boolean male = gender.equals("M");
    pName.setGivenName("EMERGENCY");
    pName.setFamilyName("PLACEHOLDER PATIENT");
    patient.addName(pName);/*from w  ww  . j  a  v a  2  s.  co  m*/

    patient.setBirthdate(Date.from(LocalDate.of(1970, 1, 1).atStartOfDay(ZoneId.systemDefault()).toInstant()));
    patient.setBirthdateEstimated(false);
    patient.setGender(gender);

    PatientIdentifier pa1 = new PatientIdentifier();
    pa1.setIdentifier(idService.generateIdentifier(patientIdentifierType, "EmergencyData"));
    pa1.setIdentifierType(patientIdentifierType);
    pa1.setDateCreated(new Date());
    pa1.setLocation(locationService.getLocation(1));
    patient.addIdentifier(pa1);

    return patient;
}

From source file:org.edgexfoundry.scheduling.ScheduleContext.java

private ZonedDateTime parseTime(String time) {
    DateTimeFormatter dtf = DateTimeFormatter.ofPattern(Schedule.DATETIME_FORMATS[0])
            .withZone(ZoneId.systemDefault());
    ZonedDateTime zdt = null;//w w w .  ja v  a 2 s  .  c  o m
    try {
        zdt = ZonedDateTime.parse(time, dtf);
    } catch (DateTimeParseException e) {
        logger.error("parseTime() failed to parse '" + time + "'");
    }
    return zdt;
}

From source file:de.adorsys.multibanking.hbci.model.HbciMapping.java

public static List<Booking> createBookings(GVRKUms gvrkUms) {
    List<Booking> bookings = new ArrayList<>();
    if (gvrkUms.isOK()) {
        List<GVRKUms.UmsLine> lines = gvrkUms.getFlatData();
        for (GVRKUms.UmsLine line : lines) {
            if (line == null) {
                continue;
            }/*  ww  w  .  j a  v a 2 s  .co m*/
            if (line.value == null) {
                log.warn("Booking has no amount, skipping: %s", line);
                continue;
            }
            if (line.bdate == null) {
                log.warn("Booking has no booking date, skipping: %s", line);
                continue;
            }
            Booking booking = new Booking();
            booking.setBankApi(BankApi.HBCI);
            booking.setBookingDate(line.bdate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate());
            booking.setAmount(line.value.getBigDecimalValue().setScale(2));
            booking.setCurrency(line.value.getCurr());
            booking.setAdditional(line.additional);
            booking.setAddkey(line.addkey);
            booking.setCustomerRef(line.customerref);
            booking.setInstRef(line.instref);
            booking.setReversal(line.isStorno);
            booking.setSepa(line.isSepa);
            booking.setPrimanota(line.primanota);
            booking.setText(line.text);
            booking.setValutaDate(line.valuta.toInstant().atZone(ZoneId.systemDefault()).toLocalDate());
            if (line.saldo != null && line.saldo.value != null) {
                booking.setBalance(line.saldo.value.getBigDecimalValue().setScale(2));
            }
            if (line.charge_value != null) {
                booking.setChargeValue(line.charge_value.getBigDecimalValue().setScale(2));
            }
            if (line.orig_value != null) {
                booking.setOrigValue(line.orig_value.getBigDecimalValue().setScale(2));
            }
            if (line.other != null) {
                booking.setOtherAccount(toBankAccount(line.other));

                String differentInitiator = Utils.extractDifferentInitiator(booking.getUsage());
                if (differentInitiator != null) {
                    booking.getOtherAccount()
                            .setOwner(booking.getOtherAccount().getOwner() + " " + differentInitiator);
                }

                if (StringUtils.isBlank(booking.getOtherAccount().getIban())) {
                    booking.getOtherAccount().setIban(extractIban(booking.getUsage()));
                }

            }
            booking.setExternalId("B-" + line.valuta.getTime() + "_" + line.value.getLongValue() + "_"
                    + line.saldo.value.getLongValue());

            // die Bank liefert keine strukturierten Verwendungszwecke (gvcode=999).
            // Daher verwenden wir den gesamten "additional"-Block und zerlegen ihn
            // in 27-Zeichen lange Haeppchen
            booking.setUsage(getUsage(line.usage.size() > 0 ? line.usage : splitEqually(line.additional, 27)));

            booking.setCreditorId((Utils.extractCreditorId(booking.getUsage())));
            booking.setMandateReference(Utils.extractMandateReference(booking.getUsage()));

            bookings.add(0, booking);
        }
    }

    log.debug("Received {} bookings: {}", bookings.size(), bookings);
    return bookings;
}

From source file:net.ceos.project.poi.annotated.core.CsvHandler.java

/**
 * Apply a LocalDateTime value to the object.
 * //from w  ww  .j  a v  a  2  s .  c  o  m
 * @param o
 *            the object
 * @param field
 *            the field
 * @param xlsAnnotation
 *            the {@link XlsElement} annotation
 * @param values
 *            the array with the content at one line
 * @param idx
 *            the index of the field
 * @throws ConverterException
 *             the conversion exception type
 */
protected static void localDateTimeReader(final Object o, final Field field, final XlsElement xlsAnnotation,
        final String[] values, final int idx) throws ConverterException {
    if (StringUtils.isNotBlank(values[idx])) {
        try {
            field.set(o, applyMaskToDate(xlsAnnotation, values, idx).toInstant().atZone(ZoneId.systemDefault())
                    .toLocalDateTime());
        } catch (IllegalArgumentException | IllegalAccessException e) {
            throw new ConverterException(ExceptionMessage.CONVERTER_LOCALDATETIME.getMessage(), e);
        }
    }
}