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:org.openlmis.fulfillment.repository.OrderRepositoryIntegrationTest.java

@Test
public void shouldSort() {
    final Order one = orderRepository.save(generateInstance(OrderStatus.ORDERED));
    final Order two = orderRepository.save(generateInstance(OrderStatus.ORDERED));
    final Order three = orderRepository.save(generateInstance(OrderStatus.ORDERED));
    final Order four = orderRepository.save(generateInstance(OrderStatus.ORDERED));

    two.setCreatedDate(ZonedDateTime.of(2017, 3, 29, 0, 0, 0, 0, ZoneId.systemDefault()));
    four.setCreatedDate(ZonedDateTime.of(2017, 3, 29, 1, 0, 0, 0, ZoneId.systemDefault()));
    one.setCreatedDate(ZonedDateTime.of(2017, 3, 30, 0, 0, 0, 0, ZoneId.systemDefault()));
    three.setCreatedDate(ZonedDateTime.of(2017, 4, 1, 0, 0, 0, 0, ZoneId.systemDefault()));

    orderRepository.save(one);//  w  w  w .ja  v  a 2s  .co  m
    orderRepository.save(two);
    orderRepository.save(three);
    orderRepository.save(four);

    HashSet<UUID> availableSupplyingFacilities = newHashSet(one.getSupplyingFacilityId(),
            two.getSupplyingFacilityId(), three.getSupplyingFacilityId(), four.getSupplyingFacilityId());

    OrderSearchParams params = new OrderSearchParams();
    params.setStatus(newHashSet(OrderStatus.ORDERED.name()));
    Page<Order> result = orderRepository.searchOrders(params, null,
            new PageRequest(0, 10, new Sort(Sort.Direction.DESC, "createdDate")), availableSupplyingFacilities,
            null);

    assertEquals(4, result.getContent().size());
    // They should be returned from the most recent to the least recent
    assertTrue(
            result.getContent().get(0).getCreatedDate().isAfter(result.getContent().get(1).getCreatedDate()));
    assertTrue(
            result.getContent().get(1).getCreatedDate().isAfter(result.getContent().get(2).getCreatedDate()));
    assertTrue(
            result.getContent().get(2).getCreatedDate().isAfter(result.getContent().get(3).getCreatedDate()));
}

From source file:no.asgari.civilization.server.action.GameAction.java

public GameDTO mapGameDTO(PBF pbf, Player player) {
    Preconditions.checkNotNull(pbf);/*from ww  w .  ja v  a  2  s  .c om*/
    //Set common stuff
    GameDTO dto = new GameDTO();
    long created = pbf.getCreated().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
    dto.setCreated(created);
    dto.setId(pbf.getId());
    dto.setType(pbf.getType());
    dto.setName(pbf.getName());
    dto.setWhosTurnIsIt(pbf.getNameOfUsersTurn());
    dto.setActive(pbf.isActive());
    dto.setMapLink(pbf.getMapLink());
    dto.setAssetLink(pbf.getAssetLink());

    //Set logs
    List<GameLog> allPublicLogs = gameLogAction.getGameLogs(pbf.getId());
    List<GameLogDTO> publicGamelogDTOs = allPublicLogs.stream()
            .filter(log -> !Strings.isNullOrEmpty(log.getPublicLog())).map(log -> new GameLogDTO(log.getId(),
                    log.getPublicLog(), log.getCreatedInMillis(), new DrawDTO(log.getDraw())))
            .collect(toList());
    dto.setPublicLogs(publicGamelogDTOs);

    //Set private player info if correct player is loggedIn.
    if (player != null && !Strings.isNullOrEmpty(player.getUsername())
            && !Strings.isNullOrEmpty(player.getId())) {
        //Get all the private player stuff
        Optional<Playerhand> playerhand = pbf.getPlayers().stream()
                .filter(p -> p.getPlayerId().equals(player.getId())).findFirst();

        if (playerhand.isPresent()) {
            List<GameLog> allPrivateLogs = gameLogAction.getGameLogsBelongingToPlayer(pbf.getId(),
                    playerhand.get().getUsername());
            List<GameLogDTO> privateGamelogDTOs = allPrivateLogs.stream()
                    .filter(log -> !Strings.isNullOrEmpty(log.getPrivateLog()))
                    .map(log -> new GameLogDTO(log.getId(), log.getPrivateLog(), log.getCreatedInMillis(),
                            new DrawDTO(log.getDraw())))
                    .collect(toList());

            dto.setPlayer(playerhand.get());
            dto.setPrivateLogs(privateGamelogDTOs);
        }
    }
    dto.setRevealedItems(getAllRevealedItems(pbf));
    return dto;
}

From source file:org.mascherl.example.service.ComposeMailService.java

private static ZonedDateTime convertToZonedDateTimeHibernate(TimestampColumnZonedDateTimeMapper mapper,
        Timestamp dbTimestamp) {/*from w w w .  j a v  a  2  s .c om*/
    // only needed when querying with hibernate, in order to fix a time zone conversion bug
    return mapper.fromNonNullValue(dbTimestamp).withZoneSameLocal(ZoneId.of("Z"))
            .withZoneSameInstant(ZoneId.systemDefault());
}

From source file:dk.dma.ais.packet.AisPacketCSVOutputSink.java

protected String formatEta(Date eta) {
    LocalDateTime time = LocalDateTime.ofInstant(Instant.ofEpochMilli(eta.getTime()), ZoneId.systemDefault());
    return formatEta(time.getDayOfMonth(), time.getMonthValue(), time.getHour(), time.getMinute());
}

From source file:alfio.manager.EventManagerIntegrationTest.java

@Test
public void testIncreaseEventSeatsWithAnUnboundedCategory() {
    List<TicketCategoryModification> categories = Collections.singletonList(new TicketCategoryModification(null,
            "default", 10, 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> pair = initEvent(categories, organizationRepository, userManager, eventManager,
            eventRepository);// ww w .j av  a  2 s  .  co  m
    Event event = pair.getKey();
    EventModification update = new EventModification(event.getId(), Event.EventType.INTERNAL, null, null, null,
            null, null, null, null, event.getOrganizationId(), null, "0.0", "0.0",
            ZoneId.systemDefault().getId(), null, DateTimeModification.fromZonedDateTime(event.getBegin()),
            DateTimeModification.fromZonedDateTime(event.getEnd()), event.getRegularPrice(),
            event.getCurrency(), 40, event.getVat(), event.isVatIncluded(), event.getAllowedPaymentProxies(),
            null, event.isFreeOfCharge(), null, 7, null, null);
    eventManager.updateEventPrices(event, update, pair.getValue());
    List<Ticket> tickets = ticketRepository.findFreeByEventId(event.getId());
    assertNotNull(tickets);
    assertFalse(tickets.isEmpty());
    assertEquals(20, tickets.size());
    assertEquals(20, ticketRepository.countReleasedUnboundedTickets(event.getId()).intValue());
    waitingQueueSubscriptionProcessor.distributeAvailableSeats(event);
    tickets = ticketRepository.findFreeByEventId(event.getId());
    assertEquals(40, tickets.size());
    assertEquals(40, tickets.stream().filter(t -> t.getCategoryId() == null).count());
}

From source file:me.childintime.childintime.ui.window.tool.BmiToolDialog.java

/**
 * Creates a sample dataset./*from  w  w  w  . j  ava 2 s .  c o m*/
 *
 * @return a sample dataset.
 */
private void updateChartDataset() {
    // Clear the data set
    this.dataset.removeAllSeries();

    try {
        // Create the data series
        final XYSeries lengthSeries = new XYSeries("Length (cm)");
        final XYSeries weightSeries = new XYSeries("Weight (kg)");
        final XYSeries bmiSeries = new XYSeries("BMI");

        // Get the student
        Student student = (Student) this.studentList.getSelectedItem();

        // Make sure a student is selected
        if (student == null)
            return;

        // Get the student birthdate
        Date birthdate = (Date) student.getField(StudentFields.BIRTHDAY);

        // Age
        final long age = ChronoUnit.YEARS
                .between(birthdate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate(), LocalDate.now());

        // Loop through the list of body states
        for (AbstractEntity abstractEntity : Core.getInstance().getBodyStateManager().getEntities()) {
            // Cast the entity to a body state
            BodyState bodyState = (BodyState) abstractEntity;

            // Make sure the student owns this body state
            try {
                if (!bodyState.getField(BodyStateFields.STUDENT_ID).equals(student))
                    continue;

            } catch (Exception e) {
                e.printStackTrace();
            }

            // Get the measurement date
            final Date measurementDate = (Date) bodyState.getField(BodyStateFields.DATE);

            // Age
            final long measurementAge = ChronoUnit.YEARS.between(
                    measurementDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate(), LocalDate.now());

            // Get the length and weight
            final int length = (int) bodyState.getField(BodyStateFields.LENGTH);
            final double weight = ((int) bodyState.getField(BodyStateFields.WEIGHT)) / 1000.0;

            // Calculate the BMI
            final double bmi = weight / Math.pow((length / 100.0), 2);

            // Add the data to the sets
            lengthSeries.add(age - measurementAge, length);
            weightSeries.add(age - measurementAge, weight);
            bmiSeries.add(age - measurementAge, bmi);
        }

        // Add the data series to the set
        this.dataset.addSeries(bmiSeries);
        this.dataset.addSeries(lengthSeries);
        this.dataset.addSeries(weightSeries);

    } catch (Exception e) {
        e.printStackTrace();
    }

    // Re set the dataset
    this.chart.getXYPlot().setDataset(this.dataset);
}

From source file:org.codelibs.fess.web.IndexAction.java

@Execute(validator = true, input = "index")
public String go() throws IOException {
    Map<String, Object> doc = null;
    try {//ww  w. j  a va 2  s .  co  m
        doc = searchService.getDocument(fieldHelper.docIdField + ":" + indexForm.docId,
                queryHelper.getResponseFields(), new String[] { fieldHelper.clickCountField });
    } catch (final Exception e) {
        logger.warn("Failed to request: " + indexForm.docId, e);
    }
    if (doc == null) {
        errorMessage = MessageResourcesUtil.getMessage(RequestUtil.getRequest().getLocale(),
                "errors.docid_not_found", indexForm.docId);
        return "error.jsp";
    }
    final Object urlObj = doc.get(fieldHelper.urlField);
    if (urlObj == null) {
        errorMessage = MessageResourcesUtil.getMessage(RequestUtil.getRequest().getLocale(),
                "errors.document_not_found", indexForm.docId);
        return "error.jsp";
    }
    final String url = urlObj.toString();

    if (Constants.TRUE.equals(crawlerProperties.getProperty(Constants.SEARCH_LOG_PROPERTY, Constants.TRUE))) {
        final String userSessionId = userInfoHelper.getUserCode();
        if (userSessionId != null) {
            final SearchLogHelper searchLogHelper = ComponentUtil.getSearchLogHelper();
            final ClickLog clickLog = new ClickLog();
            clickLog.setUrl(url);
            LocalDateTime now = systemHelper.getCurrentTime();
            clickLog.setRequestedTime(now);
            clickLog.setQueryRequestedTime(LocalDateTime
                    .ofInstant(Instant.ofEpochMilli(Long.parseLong(indexForm.rt)), ZoneId.systemDefault()));
            clickLog.setUserSessionId(userSessionId);
            clickLog.setDocId(indexForm.docId);
            long clickCount = 0;
            final Object count = doc.get(fieldHelper.clickCountField);
            if (count instanceof Long) {
                clickCount = ((Long) count).longValue();
            }
            clickLog.setClickCount(clickCount);
            searchLogHelper.addClickLog(clickLog);
        }
    }

    String hash;
    if (StringUtil.isNotBlank(indexForm.hash)) {
        final String value = URLUtil.decode(indexForm.hash, Constants.UTF_8);
        final StringBuilder buf = new StringBuilder(value.length() + 100);
        for (final char c : value.toCharArray()) {
            if (CharUtil.isUrlChar(c) || c == ' ') {
                buf.append(c);
            } else {
                try {
                    buf.append(URLEncoder.encode(String.valueOf(c), Constants.UTF_8));
                } catch (final UnsupportedEncodingException e) {
                    // NOP
                }
            }
        }
        hash = buf.toString();
    } else {
        hash = StringUtil.EMPTY;
    }

    if (isFileSystemPath(url)) {
        if (Constants.TRUE
                .equals(crawlerProperties.getProperty(Constants.SEARCH_FILE_PROXY_PROPERTY, Constants.TRUE))) {
            final CrawlingConfigHelper crawlingConfigHelper = ComponentUtil.getCrawlingConfigHelper();
            try {
                crawlingConfigHelper.writeContent(doc);
                return null;
            } catch (final Exception e) {
                logger.error("Failed to load: " + doc, e);
                errorMessage = MessageResourcesUtil.getMessage(RequestUtil.getRequest().getLocale(),
                        "errors.not_load_from_server", url);
                return "error.jsp";
            }
        } else if (Constants.TRUE
                .equals(crawlerProperties.getProperty(Constants.SEARCH_DESKTOP_PROPERTY, Constants.FALSE))) {
            final String path = url.replaceFirst("file:/+", "//");
            final File file = new File(path);
            if (!file.exists()) {
                errorMessage = MessageResourcesUtil.getMessage(RequestUtil.getRequest().getLocale(),
                        "errors.not_found_on_file_system", url);
                return "error.jsp";
            }
            final Desktop desktop = Desktop.getDesktop();
            try {
                desktop.open(file);
            } catch (final Exception e) {
                errorMessage = MessageResourcesUtil.getMessage(RequestUtil.getRequest().getLocale(),
                        "errors.could_not_open_on_system", url);
                logger.warn("Could not open " + path, e);
                return "error.jsp";
            }

            ResponseUtil.getResponse().setStatus(HttpServletResponse.SC_NO_CONTENT);
            return null;
        } else {
            ResponseUtil.getResponse().sendRedirect(url + hash);
        }
    } else {
        ResponseUtil.getResponse().sendRedirect(url + hash);
    }
    return null;
}

From source file:sx.blah.discord.DiscordClient.java

public LocalDateTime convertFromTimestamp(String time) {
    return LocalDateTime.parse(time.split("\\+")[0]).atZone(ZoneId.of("UTC+00:00"))
            .withZoneSameInstant(ZoneId.systemDefault()).toLocalDateTime();
}

From source file:sopho.Ofeloumenoi.AddOfeloumenoiController.java

@FXML
public void Save(ActionEvent event) {

    if (barcode.getText().isEmpty() || onoma.getText().isEmpty() || eponimo.getText().isEmpty()
            || patronimo.getText().isEmpty()) { //checking if the user has filled the required fields

        sopho.Messages.CustomMessageController cm = new sopho.Messages.CustomMessageController(null,
                "?!",
                "  ?   ? .  ?  ?   Barcode, ,   ? ?  ?  ?",
                "error");
        cm.showAndWait();//from   w  w w.  j a  v a  2  s .  com

    } else if (!NumberUtils.isNumber(barcode.getText()) && !barcode.getText().isEmpty()) {
        sopho.Messages.CustomMessageController cm = new sopho.Messages.CustomMessageController(null,
                "?!",
                "  barcode ?  ?  ??. ?    ?  .",
                "error");
        cm.showAndWait();
    } else if (!NumberUtils.isNumber(eisodima.getText()) && !eisodima.getText().isEmpty()) {
        sopho.Messages.CustomMessageController cm = new sopho.Messages.CustomMessageController(null,
                "?!",
                "   ?  ?  ??. ?    ?  .",
                "error");
        cm.showAndWait();
    } else {//the user has filled the required fields. We can proceed.
        sopho.DBClass db = new sopho.DBClass();
        Connection conn = null;
        PreparedStatement pst = null;
        ResultSet rs = null;

        String teknaDB = ""; //we create a var to push data to db.
        for (int i = 0; i < tekna.getItems().size(); i++) {//we are converting the table rows to a single comma separated string to push it to the database in a single entry.
            tableManager tbl = (tableManager) tekna.getItems().get(i);
            if (!tbl.getEtos().equals("?  ")) { //we are checking if the user has actually entered a number
                teknaDB += tbl.getEtos() + ","; //we have to call getEtos from the tableManager class to get the actual value. We add the value to teknaDB and seperate with comma.
                arithmosTeknon++;
            }
        }
        if (arithmosTeknon > 0) {// we need to catch the case that the user has not added any data to the table.
            teknaDB = teknaDB.substring(0, teknaDB.length() - 1); // we have to remove the last comma.
        }
        conn = db.ConnectDB();

        //Now we will check if the user has already registered this ofeloumenos
        String sql = "SELECT * FROM ofeloumenoi WHERE barcode =?";
        try {
            pst = conn.prepareStatement(sql);
            pst.setString(1, barcode.getText());
            System.out.println("the query is:" + pst.toString());
            rs = pst.executeQuery();
            rs.last(); //i go to the last line of the result to find out the number of the line
            if (rs.getRow() > 0) {// ofeloumenos is already registered to the database
                sopho.Messages.CustomMessageController cm = new sopho.Messages.CustomMessageController(null,
                        "?!",
                        "?  ?    barcode.    ? ?   . Barcode:"
                                + rs.getString("barcode") + " : " + rs.getString("eponimo")
                                + " : " + rs.getString("onoma") + " ?: "
                                + rs.getString("patronimo"),
                        "error");
                cm.showAndWait();
            } else { // we can push the data to database...
                sql = "INSERT INTO ofeloumenoi (barcode, eponimo, onoma, patronimo, mitronimo, imGennisis, dieuthinsi, dimos, tilefono, anergos, epaggelma, eisodima, eksartiseis, photoID, afm, tautotita, ethnikotita, metanastis, roma, oikKatastasi, hasTekna, arithmosTeknon, ilikiesTeknon, politeknos, monogoneiki, mellousaMama, amea, asfForeas, xronios, pathisi, anoTon60, monaxikos, emfiliVia, spoudastis, anenergos, loipa, registerDate) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
                pst = conn.prepareStatement(sql);
                //now we will set the values to the sql statement
                pst.setString(1, barcode.getText());
                pst.setString(2, eponimo.getText());
                pst.setString(3, onoma.getText());
                pst.setString(4, patronimo.getText());
                pst.setString(5, mitronimo.getText());
                //now we have to convert the imGennisis to a suitable format to be able to push it to the database
                if (imGennisis.getValue() != null) {
                    Date date = Date
                            .from(imGennisis.getValue().atStartOfDay(ZoneId.systemDefault()).toInstant());
                    java.sql.Date sqlDate = new java.sql.Date(date.getTime());
                    pst.setDate(6, sqlDate);
                } else {
                    pst.setDate(6, null);
                }
                pst.setString(7, dieuthinsi.getText());
                pst.setString(8, dimos.getText());
                pst.setString(9, tilefono.getText());
                pst.setInt(10, anergos.isSelected() ? 1 : 0); //set 1 if selected and 0 if not. We will use this method for all the checkboxes.
                pst.setString(11, epaggelma.getText());
                pst.setString(12, eisodima.getText());
                pst.setString(13, eksartiseis.getText());
                pst.setString(14, PhotoID);
                pst.setString(15, afm.getText());
                pst.setString(16, tautotita.getText());
                pst.setString(17, ethnikotita.getText());
                pst.setInt(18, metanastis.isSelected() ? 1 : 0);
                pst.setInt(19, roma.isSelected() ? 1 : 0);
                pst.setInt(20, (int) oikKatastasi.getSelectionModel().getSelectedIndex());//we are pushing to database the selected index
                pst.setInt(21, arithmosTeknon > 0 ? 1 : 0); //checking number of tekna. if >0 has tekna gets 1
                pst.setInt(22, arithmosTeknon);
                pst.setString(23, teknaDB); //here we use the converted to comma separated values variable in order to save the tableView data using only one field in database.
                pst.setInt(24, politeknos.isSelected() ? 1 : 0);
                pst.setInt(25, monogoneiki.isSelected() ? 1 : 0);
                pst.setInt(26, mellousaMama.isSelected() ? 1 : 0);
                pst.setInt(27, amea.isSelected() ? 1 : 0);
                pst.setInt(28, (int) asfForeas.getSelectionModel().getSelectedIndex());//we are pushing to database the selected index
                pst.setInt(29, xronios.isSelected() ? 1 : 0);
                pst.setString(30, pathisi.getText());
                pst.setInt(31, monaxiko.isSelected() ? 1 : 0);
                pst.setInt(32, anoTon60.isSelected() ? 1 : 0);
                pst.setInt(33, emfiliVia.isSelected() ? 1 : 0);
                pst.setInt(34, spoudastis.isSelected() ? 1 : 0);
                pst.setInt(35, anenergos.isSelected() ? 1 : 0);
                pst.setString(36, loipa.getText());
                //insert today's date as registerDate
                LocalDate now = LocalDate.now();
                java.sql.Date sqlToday = java.sql.Date.valueOf(now);
                pst.setDate(37, sqlToday);

                System.out.println("the query is:" + pst.toString());
                int linesAffected = pst.executeUpdate();

                //checking if the data were inserted to the database successfully
                if (linesAffected > 0) {
                    Stage stage = (Stage) barcode.getScene().getWindow();
                    try {
                        sl.StageLoad("/sopho/Ofeloumenoi/AddMore.fxml", stage, false, true); //resizable false, utility true
                    } catch (IOException ex) {
                        Logger.getLogger(AddOfeloumenoiController.class.getName()).log(Level.SEVERE, null, ex);
                    }
                } else {//problem inserting data...
                    sopho.Messages.CustomMessageController cm = new sopho.Messages.CustomMessageController(null,
                            "?!",
                            " ?  ?  ?   . ?  ...",
                            "error");
                    cm.showAndWait();
                }
            }

        } catch (SQLException e) {
            System.out.println(
                    "?     ?   ?  !"
                            + e);
        }

    }

}

From source file:org.silverpeas.core.calendar.notification.CalendarContributionReminderUserNotificationTest.java

@Test
public void durationReminderOnSimpleEventOf2HoursShouldWork() throws Exception {
    final DurationReminder durationReminder = initReminderBuilder(
            setupSimpleEventOn2Hours(ZoneId.systemDefault())).triggerBefore(0, TimeUnit.MINUTE, "");
    triggerDateTime(durationReminder);/*from   w  ww .j  ava2  s  .  com*/
    final Map<String, String> titles = computeNotificationTitles(durationReminder);
    assertThat(titles.get(DE), is("Reminder about the event super test - 21.02.2018 21:00 - 23:00"));
    assertThat(titles.get(EN), is("Reminder about the event super test - 02/21/2018 21:00 - 23:00"));
    assertThat(titles.get(FR), is("Rappel sur l'vnement super test - 21/02/2018 21:00 - 23:00"));
    final Map<String, String> contents = computeNotificationContents(durationReminder);
    assertThat(contents.get(DE),
            is("REMINDER: The event <b>super test</b> will be on 21.02.2018 from 21:00 to 23:00."));
    assertThat(contents.get(EN),
            is("REMINDER: The event <b>super test</b> will be on 02/21/2018 from 21:00 to 23:00."));
    assertThat(contents.get(FR),
            is("RAPPEL : L'vnement <b>super test</b> aura lieu le 21/02/2018 de 21:00  23:00."));
}