Example usage for java.time ZonedDateTime ofInstant

List of usage examples for java.time ZonedDateTime ofInstant

Introduction

In this page you can find the example usage for java.time ZonedDateTime ofInstant.

Prototype

public static ZonedDateTime ofInstant(Instant instant, ZoneId zone) 

Source Link

Document

Obtains an instance of ZonedDateTime from an Instant .

Usage

From source file:com.example.app.support.AppUtil.java

/**
 * Convert the given Date from UTC to a ZonedDateTime at the given TimeZone
 *
 * @param date the UTC date//from   w  ww .j a  va  2 s .com
 * @param zone the TimeZone to convert the time to
 *
 * @return a ZonedDateTime that represents the same instant as the UTC date, but at the given TimeZone.
 */
@Nullable
public static ZonedDateTime convertFromPersisted(@Nullable Date date, @Nullable TimeZone zone) {
    if (date == null || zone == null)
        return null;
    ZonedDateTime from = ZonedDateTime.ofInstant(date.toInstant(), ZoneOffset.UTC);
    return from.withZoneSameInstant(zone.toZoneId());
}

From source file:org.openhab.binding.airvisualnode.internal.handler.AirVisualNodeHandler.java

private State getChannelState(String channelId, NodeData nodeData) {
    State state = UnDefType.UNDEF;

    // Handle system channel IDs separately, because 'switch/case' expressions must be constant expressions
    if (CHANNEL_BATTERY_LEVEL.equals(channelId)) {
        state = new DecimalType(BigDecimal.valueOf(nodeData.getStatus().getBattery()).longValue());
    } else if (CHANNEL_WIFI_STRENGTH.equals(channelId)) {
        state = new DecimalType(
                BigDecimal.valueOf(Math.max(0, nodeData.getStatus().getWifiStrength() - 1)).longValue());
    } else {/*from   w ww  . j  a v  a 2s  .  c  o m*/
        // Handle binding-specific channel IDs
        switch (channelId) {
        case CHANNEL_CO2:
            state = new QuantityType<>(nodeData.getMeasurements().getCo2Ppm(), PARTS_PER_MILLION);
            break;
        case CHANNEL_HUMIDITY:
            state = new QuantityType<>(nodeData.getMeasurements().getHumidityRH(), PERCENT);
            break;
        case CHANNEL_AQI_US:
            state = new QuantityType<>(nodeData.getMeasurements().getPm25AQIUS(), ONE);
            break;
        case CHANNEL_PM_25:
            // PM2.5 is in ug/m3
            state = new QuantityType<>(nodeData.getMeasurements().getPm25Ugm3(),
                    MICRO(GRAM).divide(CUBIC_METRE));
            break;
        case CHANNEL_TEMP_CELSIUS:
            state = new QuantityType<>(nodeData.getMeasurements().getTemperatureC(), CELSIUS);
            break;
        case CHANNEL_TIMESTAMP:
            // It seem the Node timestamp is Unix timestamp converted from UTC time plus timezone offset.
            // Not sure about DST though, but it's best guess at now
            Instant instant = Instant.ofEpochMilli(nodeData.getStatus().getDatetime() * 1000L);
            ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(instant, ZoneId.of("UTC"));
            ZoneId zoneId = ZoneId.of(nodeData.getSettings().getTimezone());
            ZoneRules zoneRules = zoneId.getRules();
            zonedDateTime.minus(Duration.ofSeconds(zoneRules.getOffset(instant).getTotalSeconds()));
            if (zoneRules.isDaylightSavings(instant)) {
                zonedDateTime.minus(Duration.ofSeconds(zoneRules.getDaylightSavings(instant).getSeconds()));
            }
            state = new DateTimeType(zonedDateTime);
            break;
        case CHANNEL_USED_MEMORY:
            state = new DecimalType(BigDecimal.valueOf(nodeData.getStatus().getUsedMemory()).longValue());
            break;
        }
    }

    return state;
}

From source file:org.openhab.binding.ntp.internal.handler.NtpHandler.java

private synchronized void refreshTimeDate() {
    if (timeZone != null && locale != null) {
        long networkTimeInMillis;
        if (refreshNtpCount <= 0) {
            networkTimeInMillis = getTime(hostname);
            timeOffset = networkTimeInMillis - System.currentTimeMillis();
            logger.debug("{} delta system time: {}", getThing().getUID(), timeOffset);
            refreshNtpCount = refreshNtp.intValue();
        } else {/*www.j  ava2s.  c o  m*/
            networkTimeInMillis = System.currentTimeMillis() + timeOffset;
            refreshNtpCount--;
        }

        ZonedDateTime zoned = ZonedDateTime.ofInstant(Instant.ofEpochMilli(networkTimeInMillis),
                timeZone.toZoneId());
        updateState(dateTimeChannelUID, new DateTimeType(zoned));
        updateState(stringChannelUID, new StringType(dateTimeFormat.format(zoned)));
    } else {
        logger.debug("Not refreshing, since we do not seem to be initialized yet");
    }
}

From source file:io.stallion.jobs.Schedule.java

/**
 * Runs the given days of the week, every other week.
 *
 * @param startingAt//from  w  w w  . ja v  a  2 s .c o  m
 * @param days
 * @return
 */
public Schedule daysBiweekly(Long startingAt, DayOfWeek... days) {
    this._days.verifyAndUpdateUnset();
    this._days.setIntervalType(Days.IntervalType.BIWEEKLY_DAY_OF_WEEK);
    for (DayOfWeek day : days) {
        this._days.add(day.getValue());
    }
    ZonedDateTime startingWeek = ZonedDateTime.ofInstant(Instant.ofEpochMilli(startingAt), ZoneId.of("UTC"));
    // Get the Monday 12PM of that week
    startingWeek = startingWeek.minusDays(startingWeek.getDayOfWeek().getValue() - 1).withSecond(0).withHour(12)
            .withMinute(0).withNano(0);
    this._days.setStartingDate(startingWeek);
    return this;
}

From source file:org.openhab.binding.wemo.internal.handler.WemoHandler.java

@Override
public void onValueReceived(String variable, String value, String service) {
    logger.debug("Received pair '{}':'{}' (service '{}') for thing '{}'",
            new Object[] { variable, value, service, this.getThing().getUID() });

    updateStatus(ThingStatus.ONLINE);/*from   www.j a  va2s .c om*/

    this.stateMap.put(variable, value);

    if (getThing().getThingTypeUID().getId().equals("insight")) {
        String insightParams = stateMap.get("InsightParams");

        if (insightParams != null) {
            String[] splitInsightParams = insightParams.split("\\|");

            if (splitInsightParams[0] != null) {
                OnOffType binaryState = null;
                binaryState = splitInsightParams[0].equals("0") ? OnOffType.OFF : OnOffType.ON;
                if (binaryState != null) {
                    logger.trace("New InsightParam binaryState '{}' for device '{}' received", binaryState,
                            getThing().getUID());
                    updateState(CHANNEL_STATE, binaryState);
                }
            }

            long lastChangedAt = 0;
            try {
                lastChangedAt = Long.parseLong(splitInsightParams[1]) * 1000; // convert s to ms
            } catch (NumberFormatException e) {
                logger.error("Unable to parse lastChangedAt value '{}' for device '{}'; expected long",
                        splitInsightParams[1], getThing().getUID());
            }
            ZonedDateTime zoned = ZonedDateTime.ofInstant(Instant.ofEpochMilli(lastChangedAt),
                    TimeZone.getDefault().toZoneId());

            State lastChangedAtState = new DateTimeType(zoned);
            if (lastChangedAt != 0) {
                logger.trace("New InsightParam lastChangedAt '{}' for device '{}' received", lastChangedAtState,
                        getThing().getUID());
                updateState(CHANNEL_LASTCHANGEDAT, lastChangedAtState);
            }

            State lastOnFor = DecimalType.valueOf(splitInsightParams[2]);
            if (lastOnFor != null) {
                logger.trace("New InsightParam lastOnFor '{}' for device '{}' received", lastOnFor,
                        getThing().getUID());
                updateState(CHANNEL_LASTONFOR, lastOnFor);
            }

            State onToday = DecimalType.valueOf(splitInsightParams[3]);
            if (onToday != null) {
                logger.trace("New InsightParam onToday '{}' for device '{}' received", onToday,
                        getThing().getUID());
                updateState(CHANNEL_ONTODAY, onToday);
            }

            State onTotal = DecimalType.valueOf(splitInsightParams[4]);
            if (onTotal != null) {
                logger.trace("New InsightParam onTotal '{}' for device '{}' received", onTotal,
                        getThing().getUID());
                updateState(CHANNEL_ONTOTAL, onTotal);
            }

            State timespan = DecimalType.valueOf(splitInsightParams[5]);
            if (timespan != null) {
                logger.trace("New InsightParam timespan '{}' for device '{}' received", timespan,
                        getThing().getUID());
                updateState(CHANNEL_TIMESPAN, timespan);
            }

            State averagePower = DecimalType.valueOf(splitInsightParams[6]); // natively given in W
            if (averagePower != null) {
                logger.trace("New InsightParam averagePower '{}' for device '{}' received", averagePower,
                        getThing().getUID());
                updateState(CHANNEL_AVERAGEPOWER, averagePower);
            }

            BigDecimal currentMW = new BigDecimal(splitInsightParams[7]);
            State currentPower = new DecimalType(currentMW.divide(new BigDecimal(1000), RoundingMode.HALF_UP)); // recalculate
            // mW to W
            if (currentPower != null) {
                logger.trace("New InsightParam currentPower '{}' for device '{}' received", currentPower,
                        getThing().getUID());
                updateState(CHANNEL_CURRENTPOWER, currentPower);
            }

            BigDecimal energyTodayMWMin = new BigDecimal(splitInsightParams[8]);
            // recalculate mW-mins to Wh
            State energyToday = new DecimalType(
                    energyTodayMWMin.divide(new BigDecimal(60000), RoundingMode.HALF_UP));
            if (energyToday != null) {
                logger.trace("New InsightParam energyToday '{}' for device '{}' received", energyToday,
                        getThing().getUID());
                updateState(CHANNEL_ENERGYTODAY, energyToday);
            }

            BigDecimal energyTotalMWMin = new BigDecimal(splitInsightParams[9]);
            // recalculate mW-mins to Wh
            State energyTotal = new DecimalType(
                    energyTotalMWMin.divide(new BigDecimal(60000), RoundingMode.HALF_UP));
            if (energyTotal != null) {
                logger.trace("New InsightParam energyTotal '{}' for device '{}' received", energyTotal,
                        getThing().getUID());
                updateState(CHANNEL_ENERGYTOTAL, energyTotal);
            }

            BigDecimal standByLimitMW = new BigDecimal(splitInsightParams[10]);
            State standByLimit = new DecimalType(
                    standByLimitMW.divide(new BigDecimal(1000), RoundingMode.HALF_UP)); // recalculate
            // mW to W
            if (standByLimit != null) {
                logger.trace("New InsightParam standByLimit '{}' for device '{}' received", standByLimit,
                        getThing().getUID());
                updateState(CHANNEL_STANDBYLIMIT, standByLimit);
            }
            if (currentMW.divide(new BigDecimal(1000), RoundingMode.HALF_UP).intValue() > standByLimitMW
                    .divide(new BigDecimal(1000), RoundingMode.HALF_UP).intValue()) {
                updateState(CHANNEL_ONSTANDBY, OnOffType.OFF);
            } else {
                updateState(CHANNEL_ONSTANDBY, OnOffType.ON);
            }
        }
    } else {
        State state = stateMap.get("BinaryState").equals("0") ? OnOffType.OFF : OnOffType.ON;

        logger.debug("State '{}' for device '{}' received", state, getThing().getUID());

        if (state != null) {
            if (getThing().getThingTypeUID().getId().equals("motion")) {
                updateState(CHANNEL_MOTIONDETECTION, state);
                if (state.equals(OnOffType.ON)) {
                    State lastMotionDetected = new DateTimeType();
                    updateState(CHANNEL_LASTMOTIONDETECTED, lastMotionDetected);
                }
            } else {
                updateState(CHANNEL_STATE, state);
            }
        }
    }
}

From source file:com.github.aptd.simulation.elements.IBaseElement.java

@IAgentActionFilter
@IAgentActionName(name = "simtime/max")
private ZonedDateTime maxTime() {
    return ZonedDateTime.ofInstant(Instant.now().plus(Duration.ofDays(9999)), m_timezone);
}

From source file:org.openhab.binding.dwdunwetter.internal.data.DwdWarningsData.java

public State getEffective(int number) {
    DwdWarningData data = getGemeindeData(number);
    if (data == null) {
        return UnDefType.NULL;
    }//  w  ww.j a va2  s .c o  m
    ZonedDateTime zoned = ZonedDateTime.ofInstant(data.getEffective(), ZoneId.systemDefault());
    return new DateTimeType(zoned);
}

From source file:org.openhab.binding.dwdunwetter.internal.data.DwdWarningsData.java

public State getExpires(int number) {
    DwdWarningData data = getGemeindeData(number);
    if (data == null) {
        return UnDefType.NULL;
    }/*from  www .ja v a 2  s .c o  m*/
    ZonedDateTime zoned = ZonedDateTime.ofInstant(data.getExpires(), ZoneId.systemDefault());
    return new DateTimeType(zoned);
}

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

/**
 * Intialize the database based on the passed in configuration object.
 * @param config//from  ww w.j av a  2s  .  c  om
 */
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.openhab.binding.dwdunwetter.internal.data.DwdWarningsData.java

public State getOnset(int number) {
    DwdWarningData data = getGemeindeData(number);
    if (data == null) {
        return UnDefType.NULL;
    }//from   w w w.  j a v  a 2 s.com
    ZonedDateTime zoned = ZonedDateTime.ofInstant(data.getOnset(), ZoneId.systemDefault());
    return new DateTimeType(zoned);
}