Example usage for java.time ZoneId of

List of usage examples for java.time ZoneId of

Introduction

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

Prototype

public static ZoneId of(String zoneId) 

Source Link

Document

Obtains an instance of ZoneId from an ID ensuring that the ID is valid and available for use.

Usage

From source file:io.stallion.dataAccess.db.DB.java

/**
 * Intialize the database based on the passed in configuration object.
 * @param config//from  www . j a  v a2s .c  o m
 */
public void initialize(DbConfig config) {
    try {
        dbImplementation = (DbImplementation) StallionClassLoader.loadClass(config.getImplementationClass())
                .newInstance();
    } catch (InstantiationException e) {
        throw new RuntimeException(e);
    } catch (IllegalAccessException e) {
        throw new RuntimeException(e);
    }

    // Test out the connection. We do this directly, because if we test via the ComboPooledDataSource
    // exceptions will make the driver hang while retrying, and will also bury the underlying cause

    try {
        Driver driver = (Driver) StallionClassLoader.loadClass(config.getDriverClass()).newInstance();
        Properties props = new Properties();
        props.setProperty("user", config.getUsername());
        props.setProperty("password", config.getPassword());
        try (Connection conn = driver.connect(config.getUrl(), props)) {
            Statement st = conn.createStatement();
            ResultSet results = st.executeQuery("SELECT 1 AS oneCol");
            results.next();
            Long i = results.getLong("oneCol");
            assert i == 1L;
        }
    } catch (SQLException e) {
        throw new RuntimeException(e);
    } catch (InstantiationException e) {
        throw new RuntimeException(e);
    } catch (IllegalAccessException e) {
        throw new RuntimeException(e);
    }

    ComboPooledDataSource cpds = new ComboPooledDataSource();
    /*
    try {
    try (Connection conn = cpds.getConnection()) {
        Statement st = conn.createStatement();
        ResultSet results = st.executeQuery("SELECT 1");
        Long i = results.getLong(0);
        assert i == 1L;
    }
    } catch (SQLException e) {
    throw new RuntimeException(e);
    }
            
    */
    try {
        cpds.setDriverClass(config.getDriverClass()); //loads the jdbc driver
    } catch (PropertyVetoException e) {
        throw new RuntimeException(e);
    }

    String url = config.getUrl();
    if (!url.contains("?")) {
        url += "?";
    }
    // Assume the database server is in UTC
    if (!url.contains("&useLegacyDatetimeCode=")) {
        url += "&useLegacyDatetimeCode=false";
    }
    if (!url.contains("&serverTimezone=")) {
        url += "&serverTimezone=UTC";
    }
    //&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC

    cpds.setJdbcUrl(url);
    cpds.setUser(config.getUsername());
    cpds.setPassword(config.getPassword());

    if (url.contains("utf8mb4_unicode_ci")) {
        cpds.setConnectionCustomizerClassName("io.stallion.dataAccess.db.mysql.Utf8InitCustomizer");
    }

    cpds.setAcquireRetryAttempts(10);
    cpds.setAcquireRetryDelay(200);
    //cpds.setCheckoutTimeout(1);
    // the settings below are optional -- c3p0 can work with defaults
    cpds.setMinPoolSize(5);
    cpds.setAcquireIncrement(5);
    cpds.setMaxPoolSize(20);
    cpds.setIdleConnectionTestPeriod(5000);
    cpds.setTestConnectionOnCheckin(true);

    this.dataSource = cpds;

    // Make sure the database server time is UTC and in sync with the local server time
    // or else stop execution to prevent nasty and insiduious errors.
    //Timestamp date = this.queryScalar(dbImplementation.getCurrentTimeStampQuery());
    Timestamp date = this.queryScalar(dbImplementation.getCurrentTimeStampQuery());
    ZonedDateTime now = utcNow();
    ZonedDateTime dbTime = ZonedDateTime.ofInstant(Instant.ofEpochMilli(date.getTime()), ZoneId.of("UTC"));

    //LocalDateTime now = utcNow().toLocalDateTime();
    ZonedDateTime max = now.plusMinutes(2);
    ZonedDateTime min = now.minusMinutes(2);

    //LocalDateTime dbTime = date.toLocalDateTime();
    if (dbTime.isAfter(max) || dbTime.isBefore(min)) {
        throw new ConfigException(
                "The database CURRENT_TIMESTAMP() is mismatched with the server time. Db time is " + dbTime
                        + ". Server time is " + now
                        + ". Make sure the database server is in UTC and that all your servers clocks are matched. ");
    }

    // Todo: why not lazy load converters???
    registerConverter(new JsonMapConverter());
    registerConverter(new JsonSetConverter());
    registerConverter(new JsonObjectConverter());
    registerConverter(new JsonListConverter());

    this.tickets = dbImplementation.initTicketsService(this);

}

From source file:org.apache.james.mailbox.elasticsearch.json.MessageToElasticSearchJsonTest.java

@Test
public void emailWithNoInternalDateShouldUseNowDate() throws IOException {
    MessageToElasticSearchJson messageToElasticSearchJson = new MessageToElasticSearchJson(
            new DefaultTextExtractor(), ZoneId.of("Europe/Paris"), IndexAttachments.YES);
    MailboxMessage mailWithNoInternalDate = new SimpleMailboxMessage(MESSAGE_ID, null, SIZE, BODY_START_OCTET,
            new SharedByteArrayInputStream(
                    IOUtils.toByteArray(ClassLoader.getSystemResourceAsStream("eml/recursiveMail.eml"))),
            new FlagsBuilder().add(Flags.Flag.DELETED, Flags.Flag.SEEN).add("debian", "security").build(),
            propertyBuilder, MAILBOX_ID);
    mailWithNoInternalDate.setModSeq(MOD_SEQ);
    mailWithNoInternalDate.setUid(UID);
    assertThatJson(messageToElasticSearchJson.convertToJson(mailWithNoInternalDate,
            ImmutableList.of(new MockMailboxSession("username").getUser()))).when(IGNORING_ARRAY_ORDER)
                    .when(IGNORING_VALUES)
                    .isEqualTo(IOUtils.toString(ClassLoader.getSystemResource("eml/recursiveMail.json")));
}

From source file:org.silverpeas.core.reminder.ContributionReminderUserNotificationTest.java

@Test
public void durationReminderOf0HourAndWithAnotherUserZoneIdOnGenericContributionShouldWork() throws Exception {
    receiver.getUserPreferences().setZoneId(ZoneId.of("Asia/Muscat"));
    final DurationReminder durationReminder = initReminderBuilder().triggerBefore(0, TimeUnit.HOUR, "");
    triggerDateTime(durationReminder, OffsetDateTime.parse("2018-02-21T00:00:00Z"));
    final Map<String, String> titles = computeNotificationTitles(durationReminder);
    assertThat(titles.get(DE), is("Reminder about the contribution super test - 21.02.2018 00:00 (UTC)"));
    assertThat(titles.get(EN), is("Reminder about the contribution super test - 02/21/2018 00:00 (UTC)"));
    assertThat(titles.get(FR), is("Rappel sur la contribution super test - 21/02/2018 00:00 (UTC)"));
    final Map<String, String> contents = computeNotificationContents(durationReminder);
    assertThat(contents.get(DE), is(//from  w  ww . ja va 2 s .com
            "You set a reminder <b>just</b> before the contribution <b>super test</b> (21.02.2018 00:00 (UTC))."));
    assertThat(contents.get(EN), is(
            "You set a reminder <b>just</b> before the contribution <b>super test</b> (02/21/2018 00:00 (UTC))."));
    assertThat(contents.get(FR), is(
            "Vous avez demand un rappel <b>juste</b> avant la contribution <b>super test</b> (21/02/2018 00:00 (UTC))."));
}

From source file:ox.softeng.gel.filereceive.FileReceive.java

public void generateStartupMessage() throws IOException {

    try {/*from  ww  w .j a va2  s  .com*/
        StringWriter writer;
        MessageDTO message = new MessageDTO();
        message.setSource("file-receiver");
        message.setDetails("Burst Service starting\n" + version());
        message.setSeverity(SeverityEnum.INFORMATIONAL);
        message.setDateTimeCreated(OffsetDateTime.now(ZoneId.of("UTC")));
        message.setTitle("File Receiver Startup");
        message.addTopic("service");
        message.addTopic("startup");
        message.addTopic("file-receiver");
        message.addMetadata("gmc", "gel");
        message.addMetadata("file_receiver_service_version", version());

        writer = new StringWriter();
        getMarshaller().marshal(message, writer);

        AMQP.BasicProperties.Builder builder = new AMQP.BasicProperties().builder();
        builder.deliveryMode(2);
        builder.contentType("text/xml");
        builder.timestamp(Date.from(OffsetDateTime.now(ZoneId.systemDefault()).toInstant()));

        Channel channel = factory.newConnection().createChannel();
        channel.exchangeDeclare(exchangeName, "topic", true);
        channel.basicPublish(exchangeName, burstQueue, builder.build(), writer.toString().getBytes());
        channel.close();

    } catch (JAXBException | TimeoutException ignored) {
    }
}

From source file:org.eclipse.smarthome.core.internal.i18n.I18nProviderImpl.java

private void setTimeZone(final @Nullable String zoneId) {
    ZoneId oldTimeZone = this.timeZone;
    if (StringUtils.isBlank(zoneId)) {
        timeZone = null;// w w w. ja v a2  s.c o  m
    } else {
        try {
            timeZone = ZoneId.of(zoneId);
        } catch (DateTimeException e) {
            logger.warn("Error setting time zone '{}', falling back to the default time zone: {}", zoneId,
                    e.getMessage());
            timeZone = null;
        }
    }

    if (oldTimeZone != null && this.timeZone == null) {
        logger.info("Time zone is not set, falling back to the default time zone.");
    } else if (this.timeZone != null && !this.timeZone.equals(oldTimeZone)) {
        logger.info("Time zone set to '{}'.", this.timeZone);
    }
}

From source file:com.streamsets.pipeline.stage.origin.tcp.TCPServerSource.java

private boolean validateEls(List<ConfigIssue> issues) {

    final int numStartingIssues = issues.size();

    if (!Strings.isNullOrEmpty(config.recordProcessedAckMessage)) {
        final ELEval eval = getContext().createELEval("recordProcessedAckMessage");

        final Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone(ZoneId.of(config.timeZoneID)));
        TimeEL.setCalendarInContext(getContext().createELVars(), calendar);
        final ELVars vars = getContext().createELVars();
        Record validationRecord = getContext().createRecord("recordProcessedAckMessageValidationRecord");
        RecordEL.setRecordInContext(vars, validationRecord);

        ELUtils.validateExpression(config.recordProcessedAckMessage, getContext(), Groups.TCP.name(),
                CONF_PREFIX + "recordProcessedAckMessage", Errors.TCP_30, issues);
    }//from ww w . j a  v  a  2s.  c o m

    if (!Strings.isNullOrEmpty(config.batchCompletedAckMessage)) {
        final ELEval eval = getContext().createELEval("batchCompletedAckMessage");

        final Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone(ZoneId.of(config.timeZoneID)));
        TimeEL.setCalendarInContext(getContext().createELVars(), calendar);
        final ELVars vars = getContext().createELVars();
        vars.addVariable("batchSize", 0);
        Record validationRecord = getContext().createRecord("batchCompletedAckMessageValidationRecord");
        RecordEL.setRecordInContext(vars, validationRecord);

        ELUtils.validateExpression(config.batchCompletedAckMessage, getContext(), Groups.TCP.name(),
                CONF_PREFIX + "batchCompletedAckMessage", Errors.TCP_31, issues);
    }

    return issues.size() == numStartingIssues;
}

From source file:org.apache.james.mailbox.elasticsearch.json.MailboxMessageToElasticSearchJsonTest.java

@Test(expected = NullPointerException.class)
public void emailWithNoMailboxIdShouldThrow() throws IOException {
    MessageToElasticSearchJson messageToElasticSearchJson = new MessageToElasticSearchJson(
            new DefaultTextExtractor(), ZoneId.of("Europe/Paris"));
    MailboxMessage mailWithNoMailboxId;/* w  w w .  ja v  a 2 s . com*/
    try {
        mailWithNoMailboxId = new SimpleMailboxMessage(date, SIZE, BODY_START_OCTET,
                new SharedByteArrayInputStream(
                        IOUtils.toByteArray(ClassLoader.getSystemResourceAsStream("eml/recursiveMail.eml"))),
                new FlagsBuilder().add(Flags.Flag.DELETED, Flags.Flag.SEEN).add("debian", "security").build(),
                propertyBuilder, null);
        mailWithNoMailboxId.setModSeq(MOD_SEQ);
        mailWithNoMailboxId.setUid(UID);
    } catch (Exception exception) {
        throw Throwables.propagate(exception);
    }
    messageToElasticSearchJson.convertToJson(mailWithNoMailboxId,
            ImmutableList.of(new MockMailboxSession("username").getUser()));
}

From source file:com.streamsets.pipeline.stage.origin.jdbc.cdc.postgres.PostgresCDCSource.java

private Optional<List<ConfigIssue>> validatePostgresCDCConfigBean(PostgresCDCConfigBean configBean) {
    List<ConfigIssue> issues = new ArrayList<>();

    if (configBean.minVersion == null) {
        this.getConfigBean().minVersion = PgVersionValues.NINEFOUR;
    }//from ww w .j  a  va 2  s . c o m

    if (configBean.decoderValue == null) {
        this.getConfigBean().decoderValue = DecoderValues.WAL2JSON;
    }

    if (configBean.replicationType == null) {
        this.getConfigBean().replicationType = "database";
    }

    switch (configBean.startValue) {

    case LSN:
        //Validate startLSN
        if (configBean.startLSN == null || configBean.startLSN.isEmpty()
                || (LogSequenceNumber.valueOf(configBean.startLSN).equals(LogSequenceNumber.INVALID_LSN))) {
            issues.add(getContext().createConfigIssue(Groups.CDC.name(),
                    configBean.startLSN + " is invalid LSN.", JdbcErrors.JDBC_408));
            this.setOffset("0/0"); //Valid "non-LSN" LSN or set to latest.
        } else {
            this.setOffset(configBean.startLSN);
        }
        break;

    case DATE:
        //Validate startDate
        zoneId = ZoneId.of(configBean.dbTimeZone);
        dateTimeColumnHandler = new DateTimeColumnHandler(zoneId);
        try {
            startDate = LocalDateTime.parse(configBean.startDate,
                    DateTimeFormatter.ofPattern("MM-dd-yyyy HH:mm:ss"));
            /* Valid offset that should be as early as possible to get the most number of WAL
            records available for the date filter to process. */
            this.setOffset(LogSequenceNumber.valueOf(1L).asString());
        } catch (DateTimeParseException e) {
            issues.add(getContext().createConfigIssue(Groups.CDC.name(),
                    configBean.startDate + " doesn't parse as DateTime.", JdbcErrors.JDBC_408));
        }
        break;

    case LATEST:
        this.setOffset("0/0"); //Valid "non-LSN" LSN or set to latest.
        break;

    default:
        //Should never happen
        issues.add(getContext().createConfigIssue(Groups.CDC.name(), configBean.startValue.getLabel(),
                JdbcErrors.JDBC_408));
    }

    return Optional.ofNullable(issues);
}