Example usage for java.time LocalDateTime now

List of usage examples for java.time LocalDateTime now

Introduction

In this page you can find the example usage for java.time LocalDateTime now.

Prototype

public static LocalDateTime now(Clock clock) 

Source Link

Document

Obtains the current date-time from the specified clock.

Usage

From source file:org.finra.herd.dao.JestClientFactory.java

/**
 * Builds and returns a JEST client./*from  w  ww. ja  v a2  s  . com*/
 *
 * @return the configured JEST client
 */
public JestClient getJestClient() {
    // Retrieve the configuration values used for setting up an Elasticsearch JEST client.
    final String esRegionName = configurationHelper
            .getProperty(ConfigurationValue.ELASTICSEARCH_AWS_REGION_NAME);
    final String hostname = configurationHelper
            .getProperty(ConfigurationValue.ELASTICSEARCH_DOMAIN_REST_CLIENT_HOSTNAME);
    final int port = configurationHelper.getProperty(ConfigurationValue.ELASTICSEARCH_DOMAIN_REST_CLIENT_PORT,
            Integer.class);
    final String scheme = configurationHelper
            .getProperty(ConfigurationValue.ELASTICSEARCH_DOMAIN_REST_CLIENT_SCHEME);
    final String serverUri = String.format("%s://%s:%d", scheme, hostname, port);
    final int connectionTimeout = configurationHelper
            .getProperty(ConfigurationValue.ELASTICSEARCH_REST_CLIENT_CONNECTION_TIMEOUT, Integer.class);
    final int readTimeout = configurationHelper
            .getProperty(ConfigurationValue.ELASTICSEARCH_REST_CLIENT_READ_TIMEOUT, Integer.class);

    LOGGER.info("Elasticsearch REST Client Settings:  scheme={}, hostname={}, port={}, serverUri={}", scheme,
            hostname, port, serverUri);

    DefaultAWSCredentialsProviderChain awsCredentialsProvider = new DefaultAWSCredentialsProviderChain();
    final AWSSigner awsSigner = new AWSSigner(awsCredentialsProvider, esRegionName, "es",
            () -> LocalDateTime.now(ZoneOffset.UTC));

    final AWSSigningRequestInterceptor requestInterceptor = new AWSSigningRequestInterceptor(awsSigner);

    JestClientFactoryStaticInner jestClientFactory = new JestClientFactoryStaticInner(requestInterceptor);

    if (StringUtils.equalsIgnoreCase(scheme, "https")) {
        SSLConnectionSocketFactory sslSocketFactory;
        try {
            sslSocketFactory = new SSLConnectionSocketFactory(SSLContext.getDefault(),
                    NoopHostnameVerifier.INSTANCE);
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalStateException(e);
        }

        jestClientFactory.setHttpClientConfig(
                new HttpClientConfig.Builder(serverUri).connTimeout(connectionTimeout).readTimeout(readTimeout)
                        .sslSocketFactory(sslSocketFactory).multiThreaded(true).build());
    } else {
        jestClientFactory.setHttpClientConfig(new HttpClientConfig.Builder(serverUri)
                .connTimeout(connectionTimeout).readTimeout(readTimeout).multiThreaded(true).build());
    }

    return jestClientFactory.getObject();
}

From source file:com.coinkite.CoinkiteSigningRequestInterceptor.java

LocalDateTime getDateTime() {

    if (dateTime == null) {
        return LocalDateTime.now(Clock.system(ZoneId.of("UTC")));
    }// w ww  .j a  v a  2s  .c  o m

    return dateTime;
}

From source file:com.nirmata.workflow.details.TestJsonSerializer.java

@Test
public void testStartedTask() {
    StartedTask startedTask = new StartedTask(Integer.toString(random.nextInt()),
            LocalDateTime.now(Clock.systemUTC()));
    JsonNode node = newStartedTask(startedTask);
    String str = nodeToString(node);
    System.out.println(str);//from  ww w. ja  v a2  s.c  o  m

    StartedTask unStartedTask = getStartedTask(fromString(str));
    Assert.assertEquals(startedTask, unStartedTask);
}

From source file:msi.gama.util.GamaDate.java

private static Temporal parse(final IScope scope, final String original, final DateTimeFormatter df) {
    if (original == null || original.isEmpty() || original.equals("now")) {
        return LocalDateTime.now(GamaDateType.DEFAULT_ZONE);
    }//  w w  w .j  a va2 s  .  co  m
    Temporal result = null;

    if (df != null) {
        try {
            final TemporalAccessor ta = df.parse(original);
            if (ta instanceof Temporal) {
                return (Temporal) ta;
            }
            if (!ta.isSupported(ChronoField.YEAR) && !ta.isSupported(ChronoField.MONTH_OF_YEAR)
                    && !ta.isSupported(ChronoField.DAY_OF_MONTH)) {
                if (ta.isSupported(ChronoField.HOUR_OF_DAY)) {
                    return LocalTime.from(ta);
                }
            }
            if (!ta.isSupported(ChronoField.HOUR_OF_DAY) && !ta.isSupported(ChronoField.MINUTE_OF_HOUR)
                    && !ta.isSupported(ChronoField.SECOND_OF_MINUTE)) {
                return LocalDate.from(ta);
            }
            return LocalDateTime.from(ta);
        } catch (final DateTimeParseException e) {
            e.printStackTrace();
        }
        GAMA.reportAndThrowIfNeeded(scope,
                GamaRuntimeException.warning(
                        "The date " + original + " can not correctly be parsed by the pattern provided", scope),
                false);
        return parse(scope, original, null);
    }

    String dateStr;
    try {
        // We first make sure all date fields have the correct length and
        // the string is correctly formatted
        String string = original;
        if (!original.contains("T") && original.contains(" ")) {
            string = StringUtils.replaceOnce(original, " ", "T");
        }
        final String[] base = string.split("T");
        final String[] date = base[0].split("-");
        String other;
        if (base.length == 1) {
            other = "00:00:00";
        } else {
            other = base[1];
        }
        String year, month, day;
        if (date.length == 1) {
            // ISO basic date format
            year = date[0].substring(0, 4);
            month = date[0].substring(4, 6);
            day = date[0].substring(6, 8);
        } else {
            year = date[0];
            month = date[1];
            day = date[2];
        }
        if (year.length() == 2) {
            year = "20" + year;
        }
        if (month.length() == 1) {
            month = '0' + month;
        }
        if (day.length() == 1) {
            day = '0' + day;
        }
        dateStr = year + "-" + month + "-" + day + "T" + other;
    } catch (final Exception e1) {
        throw GamaRuntimeException.error("The date " + original
                + " is not correctly formatted. Please refer to the ISO date/time format", scope);
    }

    try {
        result = LocalDateTime.parse(dateStr);
    } catch (final DateTimeParseException e) {
        try {
            result = OffsetDateTime.parse(dateStr);
        } catch (final DateTimeParseException e2) {
            try {
                result = ZonedDateTime.parse(dateStr);
            } catch (final DateTimeParseException e3) {
                throw GamaRuntimeException.error(
                        "The date " + original
                                + " is not correctly formatted. Please refer to the ISO date/time format",
                        scope);
            }
        }
    }

    return result;
}

From source file:dhbw.clippinggorilla.userinterface.windows.PreferencesWindow.java

private Component buildClippingsTab(User user) {
    HorizontalLayout root = new HorizontalLayout();
    root.setCaption(Language.get(Word.CLIPPINGS));
    root.setIcon(VaadinIcons.NEWSPAPER);
    root.setWidth("100%");
    root.setSpacing(true);/*from  w w  w .ja va 2 s .co  m*/
    root.setMargin(true);

    FormLayout formLayoutClippingDetails = new FormLayout();
    formLayoutClippingDetails.addStyleName(ValoTheme.FORMLAYOUT_LIGHT);
    root.addComponent(formLayoutClippingDetails);

    CheckBox checkBoxReceiveEmails = new CheckBox();
    checkBoxReceiveEmails.setValue(UserUtils.getEmailNewsletter(user));
    checkBoxReceiveEmails.addValueChangeListener(v -> UserUtils.setEmailNewsletter(user, v.getValue()));
    HorizontalLayout layoutCheckBoxReceiveEmails = new HorizontalLayout(checkBoxReceiveEmails);
    layoutCheckBoxReceiveEmails.setCaption(Language.get(Word.EMAIL_SUBSCRIPTION));
    layoutCheckBoxReceiveEmails.setMargin(false);
    layoutCheckBoxReceiveEmails.setSpacing(false);

    HorizontalLayout layoutAddNewClippingTime = new HorizontalLayout();
    layoutAddNewClippingTime.setMargin(false);
    layoutAddNewClippingTime.setCaption(Language.get(Word.ADD_CLIPPING_TIME));
    layoutAddNewClippingTime.setWidth("100%");

    InlineDateTimeField dateFieldNewClippingTime = new InlineDateTimeField();
    LocalDateTime value = LocalDateTime.now(ZoneId.of("Europe/Berlin"));
    dateFieldNewClippingTime.setValue(value);
    dateFieldNewClippingTime.setLocale(VaadinSession.getCurrent().getLocale());
    dateFieldNewClippingTime.setResolution(DateTimeResolution.MINUTE);
    dateFieldNewClippingTime.addStyleName("time-only");

    Button buttonAddClippingTime = new Button();
    buttonAddClippingTime.setIcon(VaadinIcons.PLUS);
    buttonAddClippingTime.addStyleName(ValoTheme.BUTTON_PRIMARY);
    buttonAddClippingTime.setClickShortcut(ShortcutAction.KeyCode.ENTER, null);
    buttonAddClippingTime.addClickListener(e -> {
        LocalTime generalTime = dateFieldNewClippingTime.getValue().toLocalTime();
        layoutClippingTimes.addComponent(getTimeRow(user, generalTime));
        UserUtils.addClippingSendTime(user, generalTime);
    });
    layoutAddNewClippingTime.addComponents(dateFieldNewClippingTime, buttonAddClippingTime);
    layoutAddNewClippingTime.setComponentAlignment(dateFieldNewClippingTime, Alignment.MIDDLE_LEFT);
    layoutAddNewClippingTime.setComponentAlignment(buttonAddClippingTime, Alignment.MIDDLE_CENTER);
    layoutAddNewClippingTime.setExpandRatio(dateFieldNewClippingTime, 5);

    layoutClippingTimes = new VerticalLayout();
    layoutClippingTimes.setMargin(new MarginInfo(true, false, false, true));
    layoutClippingTimes.setCaption(Language.get(Word.CLIPPING_TIMES));
    layoutClippingTimes.setWidth("100%");
    layoutClippingTimes.addStyleName("times");

    Set<LocalTime> userTimes = user.getClippingTime();
    userTimes.forEach(t -> layoutClippingTimes.addComponent(getTimeRow(user, t)));

    formLayoutClippingDetails.addComponents(layoutCheckBoxReceiveEmails, layoutAddNewClippingTime,
            layoutClippingTimes);

    return root;
}

From source file:org.silverpeas.core.webapi.calendar.CalendarWebManager.java

/**
 * Gets the next event occurrences from now.
 * @param componentIds identifiers of aimed component instance.
 * @param calendarIdsToExclude identifier of calendars which linked occurrences must be excluded
 * from the result.//from w w  w  . java 2s .  co m
 * @param usersToInclude identifiers of users which linked occurrences must be included into the
 * result
 * @param calendarIdsToInclude identifier of calendars which linked occurrences must be included
 * into the result.
 * @param zoneId the identifier of the zone.
 * @param limit the maximum occurrences the result must have (must be lower than 500)
 * @return a list of {@link CalendarEventOccurrence}.
 */
public Stream<CalendarEventOccurrence> getNextEventOccurrences(final List<String> componentIds,
        final Set<String> calendarIdsToExclude, final Set<User> usersToInclude,
        final Set<String> calendarIdsToInclude, final ZoneId zoneId, final Integer limit) {
    final User currentRequester = User.getCurrentRequester();
    // load calendars
    final List<Calendar> calendars = componentIds.stream().flatMap(i -> getCalendarsHandledBy(i).stream())
            .distinct().collect(Collectors.toList());
    // includes/excludes
    calendarIdsToInclude.removeAll(calendarIdsToExclude);
    calendars.removeIf(c -> calendarIdsToExclude.contains(c.getId()));
    if (!calendarIdsToInclude.isEmpty()) {
        calendars.forEach(c -> calendarIdsToInclude.remove(c.getId()));
        calendarIdsToInclude.forEach(i -> {
            Calendar calendarToInclude = Calendar.getById(i);
            if (calendarToInclude.canBeAccessedBy(currentRequester)) {
                calendars.add(calendarToInclude);
            }
        });
    }
    // loading occurrences
    final int nbOccLimit = (limit != null && limit > 0 && limit <= 500) ? limit : DEFAULT_NB_MAX_NEXT_OCC;
    final LocalDate startDate = zoneId != null ? LocalDateTime.now(zoneId).toLocalDate() : LocalDate.now();
    final Set<CalendarEventOccurrence> occurrences = new HashSet<>();
    for (int nbMonthsToAdd : getNextEventTimeWindows()) {
        occurrences.clear();
        LocalDate endDate = startDate.plusMonths(nbMonthsToAdd);
        occurrences.addAll(getEventOccurrencesOf(startDate, endDate, calendars));
        if (!usersToInclude.isEmpty()) {
            getAllEventOccurrencesByUserIds(Pair.of(componentIds, currentRequester), startDate, endDate,
                    usersToInclude).forEach((u, o) -> occurrences.addAll(o));
        }
        if (occurrences.size() >= nbOccLimit) {
            break;
        }
    }
    return occurrences.stream().sorted(COMPARATOR_BY_DATE_ASC).limit(nbOccLimit);
}

From source file:com.streamsets.pipeline.stage.origin.jdbc.cdc.oracle.OracleCDCSource.java

@NotNull
private LocalDateTime nowAtDBTz() {
    return LocalDateTime.now(zoneId);
}