Example usage for java.time Instant ofEpochSecond

List of usage examples for java.time Instant ofEpochSecond

Introduction

In this page you can find the example usage for java.time Instant ofEpochSecond.

Prototype

public static Instant ofEpochSecond(long epochSecond) 

Source Link

Document

Obtains an instance of Instant using seconds from the epoch of 1970-01-01T00:00:00Z.

Usage

From source file:net.dv8tion.jda.handle.UserTypingHandler.java

@Override
protected String handleInternally(JSONObject content) {
    MessageChannel channel = api.getChannelMap().get(content.getString("channel_id"));

    if (channel == null) {
        channel = api.getPmChannelMap().get(content.getString("channel_id"));
    } else if (GuildLock.get(api).isLocked(((TextChannel) channel).getGuild().getId())) {
        return ((TextChannel) channel).getGuild().getId();
    }/* www . j  a  v  a  2 s .  c  o  m*/

    User user = api.getUserMap().get(content.getString("user_id"));
    if (user == null)
        return null;

    OffsetDateTime timestamp = Instant.ofEpochSecond(content.getInt("timestamp")).atOffset(ZoneOffset.UTC);
    api.getEventManager().handle(new UserTypingEvent(api, responseNumber, user, channel, timestamp));
    api.getEventManager().handle(new GenericUserEvent(api, responseNumber, user));
    return null;
}

From source file:com.create.batch.integration.FileMessageToJobRequestTest.java

@Test
public void testMessageFileToJobLaunchRequestConversion() {
    // given//from  ww w  .  j a v a2s . c  om
    final Message<File> message = mock(Message.class);
    final File file = mock(File.class);
    when(file.getAbsolutePath()).thenReturn(PATH);
    when(message.getPayload()).thenReturn(file);
    final Instant timestamp = Instant.ofEpochSecond(TIMESTAMP);
    when(clock.instant()).thenReturn(timestamp);

    // when
    final JobLaunchRequest jobLaunchRequest = transformer.toRequest(message);

    // then
    assertThat(jobLaunchRequest.getJob(), is(job));
    assertThat(jobLaunchRequest.getJobParameters().getLong(FileMessageToJobRequest.TIMESTAMP_PARAMETER),
            equalTo(TIMESTAMP));
    assertThat(jobLaunchRequest.getJobParameters().getString(PARAMETER), equalTo(PATH));
}

From source file:com.netflix.metacat.connector.hive.converters.HiveConnectorInfoConverter.java

/**
 * Converts epoch time to Date./*from  w ww .  j av  a2 s  .c  om*/
 *
 * @param seconds time in seconds
 * @return Date
 */
public static Date epochSecondsToDate(final long seconds) {
    return Date.from(Instant.ofEpochSecond(seconds));
}

From source file:org.openmhealth.shim.withings.mapper.WithingsSleepDurationDataPointMapper.java

/**
 * Maps an individual list node from the array in the Withings sleep summary endpoint response into a {@link
 * SleepDuration} data point.//from w w  w. j av a 2s  .co m
 *
 * @param node activity node from the array "series" contained in the "body" of the endpoint response
 * @return a {@link DataPoint} object containing a {@link SleepDuration} measure with the appropriate values from
 * the JSON node parameter, wrapped as an {@link Optional}
 */
@Override
Optional<DataPoint<SleepDuration>> asDataPoint(JsonNode node) {

    Long lightSleepInSeconds = asRequiredLong(node, "data.lightsleepduration");
    Long deepSleepInSeconds = asRequiredLong(node, "data.deepsleepduration");
    Long remSleepInSeconds = asRequiredLong(node, "data.remsleepduration");

    Long totalSleepInSeconds = lightSleepInSeconds + deepSleepInSeconds + remSleepInSeconds;

    SleepDuration.Builder sleepDurationBuilder = new SleepDuration.Builder(
            new DurationUnitValue(DurationUnit.SECOND, totalSleepInSeconds));

    Optional<Long> startDateInEpochSeconds = asOptionalLong(node, "startdate");
    Optional<Long> endDateInEpochSeconds = asOptionalLong(node, "enddate");

    if (startDateInEpochSeconds.isPresent() && endDateInEpochSeconds.isPresent()) {
        OffsetDateTime offsetStartDateTime = OffsetDateTime
                .ofInstant(Instant.ofEpochSecond(startDateInEpochSeconds.get()), of("Z"));
        OffsetDateTime offsetEndDateTime = OffsetDateTime
                .ofInstant(Instant.ofEpochSecond(endDateInEpochSeconds.get()), of("Z"));
        sleepDurationBuilder.setEffectiveTimeFrame(
                TimeInterval.ofStartDateTimeAndEndDateTime(offsetStartDateTime, offsetEndDateTime));
    }

    Optional<Long> externalId = asOptionalLong(node, "id");
    Optional<Long> modelId = asOptionalLong(node, "model");
    String modelName = null;

    if (modelId.isPresent()) {
        modelName = SleepDeviceTypes.valueOf(modelId.get());
    }

    SleepDuration sleepDuration = sleepDurationBuilder.build();
    Optional<Long> wakeupCount = asOptionalLong(node, "data.wakeupcount");
    if (wakeupCount.isPresent()) {
        sleepDuration.setAdditionalProperty("wakeup_count", new Integer(wakeupCount.get().intValue()));
    }

    // These sleep phase values are Withings platform-specific, so we pass them through as additionalProperties to
    // ensure we keep relevant platform specific values. Should be interpreted according to Withings API spec
    sleepDuration.setAdditionalProperty("light_sleep_duration",
            new DurationUnitValue(DurationUnit.SECOND, lightSleepInSeconds));
    sleepDuration.setAdditionalProperty("deep_sleep_duration",
            new DurationUnitValue(DurationUnit.SECOND, deepSleepInSeconds));
    sleepDuration.setAdditionalProperty("rem_sleep_duration",
            new DurationUnitValue(DurationUnit.SECOND, remSleepInSeconds));

    // This is an additional piece of information captured by Withings devices around sleep and should be
    // interpreted according to the Withings API specification. We do not capture durationtowakeup or
    // wakeupduration properties from the Withings API because it is unclear the distinction between them and we
    // aim to avoid creating more ambiguity through passing through these properties
    Optional<Long> timeToSleepValue = asOptionalLong(node, "data.durationtosleep");
    if (timeToSleepValue.isPresent()) {
        sleepDuration.setAdditionalProperty("duration_to_sleep",
                new DurationUnitValue(DurationUnit.SECOND, timeToSleepValue.get()));
    }

    return Optional.of(newDataPoint(sleepDuration, externalId.orElse(null), true, modelName));
}

From source file:net.dv8tion.jda.core.handle.TypingStartHandler.java

@Override
protected Long handleInternally(JSONObject content) {
    final long channelId = content.getLong("channel_id");
    MessageChannel channel = api.getTextChannelMap().get(channelId);
    if (channel == null)
        channel = api.getPrivateChannelMap().get(channelId);
    if (channel == null)
        channel = api.getFakePrivateChannelMap().get(channelId);
    if (channel == null && api.getAccountType() == AccountType.CLIENT)
        channel = api.asClient().getGroupById(channelId);
    if (channel == null)
        return null; //We don't have the channel cached yet. We chose not to cache this event
                     // because that happen very often and could easily fill up the EventCache if
                     // we, for some reason, never get the channel. Especially in an active channel.

    if (channel instanceof TextChannel) {
        final long guildId = ((TextChannel) channel).getGuild().getIdLong();
        if (api.getGuildLock().isLocked(guildId))
            return guildId;
    }/*from  w  w  w.ja  v a2 s .  co m*/

    final long userId = content.getLong("user_id");
    User user;
    if (channel instanceof PrivateChannel)
        user = ((PrivateChannel) channel).getUser();
    else if (channel instanceof Group)
        user = ((GroupImpl) channel).getUserMap().get(userId);
    else
        user = api.getUserMap().get(userId);

    if (user == null)
        return null; //Just like in the comment above, if for some reason we don't have the user for some reason
                     // then we will just throw the event away.

    OffsetDateTime timestamp = Instant.ofEpochSecond(content.getInt("timestamp")).atOffset(ZoneOffset.UTC);
    api.getEventManager().handle(new UserTypingEvent(api, responseNumber, user, channel, timestamp));
    return null;
}

From source file:mcp.tools.nmap.parser.NmapXmlParser.java

public static void parse(File xmlResultsFile, String scanDescription, String commandLine) {
    Pattern endTimePattern = Pattern.compile("<runstats><finished time=\"(\\d+)");
    String xmlResults;/*from w  ww  . ja  va  2 s .c  om*/
    try {
        xmlResults = FileUtils.readFileToString(xmlResultsFile);
    } catch (IOException e) {
        logger.error("Failed to parse nmap results file '" + xmlResultsFile.toString() + "': "
                + e.getLocalizedMessage(), e);
        return;
    }

    Matcher m = endTimePattern.matcher(xmlResults);
    Instant scanTime = null;
    if (m.find()) {
        int t;
        try {
            t = Integer.parseInt(m.group(1));
            scanTime = Instant.ofEpochSecond(t);
        } catch (NumberFormatException e) {

        }
    }

    if (scanTime == null) {
        logger.debug("Failed to find scan completion time in nmap results. Using current time.");
        scanTime = Instant.now();
    }
    String path;
    try {
        path = xmlResultsFile.getCanonicalPath();
    } catch (IOException e1) {
        logger.debug("Why did the canonical path fail?");
        path = xmlResultsFile.getAbsolutePath();
    }

    NmapScanSource source = new NmapScanSourceImpl(path, scanDescription, commandLine);

    NMapXmlHandler nmxh = new NMapXmlHandler(scanTime, source);
    SAXParserFactory spf = SAXParserFactory.newInstance();

    SAXParser sp;
    try {
        sp = spf.newSAXParser();
    } catch (ParserConfigurationException e) {
        throw new UnexpectedException("This shouldn't have happened: " + e.getLocalizedMessage(), e);
    } catch (SAXException e) {
        throw new UnexpectedException("This shouldn't have happened: " + e.getLocalizedMessage(), e);
    }

    try {
        sp.parse(xmlResultsFile, nmxh);
    } catch (SAXException e) {
        logger.error("Failed to parse nmap results file '" + xmlResultsFile.toString() + "': "
                + e.getLocalizedMessage(), e);
        return;
    } catch (IOException e) {
        logger.error("Failed to parse nmap results file '" + xmlResultsFile.toString() + "': "
                + e.getLocalizedMessage(), e);
        return;
    }
}

From source file:de.qaware.chronix.solr.ingestion.format.GraphiteFormatParser.java

/**
 * Extracts the metric timestamp from the parts.
 *
 * @param parts Parts./*from  w w  w . j  a v  a 2 s.c o  m*/
 * @return Metric timestamp.
 * @throws FormatParseException If something went wrong while extracting.
 */
private Instant getMetricTimestamp(String[] parts) throws FormatParseException {
    String value = parts[2];
    try {
        long epochTime = Long.parseLong(value);
        return Instant.ofEpochSecond(epochTime);
    } catch (NumberFormatException e) {
        throw new FormatParseException("Can't convert '" + value + "' to long", e);
    }
}

From source file:org.openmhealth.shim.withings.mapper.WithingsBodyMeasureDataPointMapper.java

@Override
public List<DataPoint<T>> asDataPoints(List<JsonNode> responseNodes) {

    checkNotNull(responseNodes);//from   www .ja v  a 2s.  com
    checkNotNull(responseNodes.size() == 1, "A single response node is allowed per call.");

    JsonNode responseNodeBody = asRequiredNode(responseNodes.get(0), BODY_NODE_PROPERTY);
    List<DataPoint<T>> dataPoints = Lists.newArrayList();

    for (JsonNode measureGroupNode : asRequiredNode(responseNodeBody, "measuregrps")) {

        if (isGoal(measureGroupNode)) {
            continue;
        }

        if (isOwnerAmbiguous(measureGroupNode)) {
            logger.warn(
                    "The following Withings measure group is being ignored because its owner is ambiguous.\n{}",
                    measureGroupNode);
            continue;
        }

        JsonNode measuresNode = asRequiredNode(measureGroupNode, "measures");

        Measure.Builder<T, ?> measureBuilder = newMeasureBuilder(measuresNode).orElse(null);
        if (measureBuilder == null) {
            continue;
        }

        Optional<Long> dateTimeInEpochSeconds = asOptionalLong(measureGroupNode, "date");
        if (dateTimeInEpochSeconds.isPresent()) {

            Instant dateTimeInstant = Instant.ofEpochSecond(dateTimeInEpochSeconds.get());
            measureBuilder.setEffectiveTimeFrame(OffsetDateTime.ofInstant(dateTimeInstant, UTC));
        }

        Optional<String> userComment = asOptionalString(measureGroupNode, "comment");
        if (userComment.isPresent()) {
            measureBuilder.setUserNotes(userComment.get());
        }

        T measure = measureBuilder.build();

        Optional<Long> externalId = asOptionalLong(measureGroupNode, "grpid");

        dataPoints.add(newDataPoint(measure, externalId.orElse(null), isSensed(measureGroupNode), null));
    }

    return dataPoints;
}

From source file:com.qwazr.externalizor.SimpleTime.java

public SimpleTime() {

    calNullValue = null;// w ww  .  j  a  v a 2s.c  o m
    calValue = Calendar.getInstance();
    calValue.setTimeInMillis(RandomUtils.nextLong());
    calArray = new Calendar[] { calNullValue, calValue };
    calList = new ArrayList(Arrays.asList(calValue, calNullValue));

    dateNullValue = null;
    dateValue = new Date(RandomUtils.nextLong());
    dateArray = new Date[] { dateNullValue, dateValue };
    dateList = new ArrayList(Arrays.asList(dateValue, dateNullValue));

    durationNullValue = null;
    durationValue = Duration.ofSeconds(RandomUtils.nextLong());
    durationArray = new Duration[] { durationNullValue, durationValue };
    durationList = new ArrayList(Arrays.asList(durationValue, durationNullValue));

    instantNullValue = null;
    instantValue = Instant.ofEpochSecond(RandomUtils.nextLong(0, Instant.MAX.getEpochSecond()));
    instantArray = new Instant[] { instantNullValue, instantValue };
    instantList = new ArrayList(Arrays.asList(instantValue, instantNullValue));

    localTimeNullValue = null;
    localTimeValue = LocalTime.of(RandomUtils.nextInt(0, 24), RandomUtils.nextInt(0, 60),
            RandomUtils.nextInt(0, 60));
    localTimeArray = new LocalTime[] { localTimeNullValue, localTimeValue };
    localTimeList = new ArrayList(Arrays.asList(localTimeValue, localTimeNullValue));

    localDateNullValue = null;
    localDateValue = LocalDate.of(RandomUtils.nextInt(2000, 3000), RandomUtils.nextInt(1, 13),
            RandomUtils.nextInt(1, 29));
    localDateArray = new LocalDate[] { localDateNullValue, localDateValue };
    localDateList = new ArrayList(Arrays.asList(localDateValue, localDateNullValue));

    localDateTimeNullValue = null;
    localDateTimeValue = LocalDateTime.of(
            LocalDate.of(RandomUtils.nextInt(2000, 3000), RandomUtils.nextInt(1, 13),
                    RandomUtils.nextInt(1, 29)),
            LocalTime.of(RandomUtils.nextInt(0, 24), RandomUtils.nextInt(0, 60), RandomUtils.nextInt(0, 60)));
    localDateTimeArray = new LocalDateTime[] { localDateTimeNullValue, localDateTimeValue };
    localDateTimeList = new ArrayList(Arrays.asList(localDateTimeValue, localDateTimeNullValue));

    monthDayNullValue = null;
    monthDayValue = MonthDay.of(RandomUtils.nextInt(1, 13), RandomUtils.nextInt(1, 29));
    monthDayArray = new MonthDay[] { monthDayNullValue, monthDayValue };
    monthDayList = new ArrayList(Arrays.asList(monthDayValue, monthDayNullValue));

    periodNullValue = null;
    periodValue = Period.of(RandomUtils.nextInt(0, Year.MAX_VALUE), RandomUtils.nextInt(1, 13),
            RandomUtils.nextInt(1, 29));
    periodArray = new Period[] { periodNullValue, periodValue };
    periodList = new ArrayList(Arrays.asList(periodValue, periodNullValue));

    yearNullValue = null;
    yearValue = Year.of(RandomUtils.nextInt(0, Year.MAX_VALUE));
    yearArray = new Year[] { yearNullValue, yearValue };
    yearList = new ArrayList(Arrays.asList(yearValue, yearNullValue));

}

From source file:org.janusgraph.diskstorage.es.ElasticSearchMultiTypeIndexTest.java

@Test
@Override// ww w  .  j a v a 2  s .com
public void clearStorageTest() throws Exception {
    final String store = "vertex";
    initialize(store);
    final Multimap<String, Object> doc1 = getDocument("Hello world", 1001, 5.2, Geoshape.point(48.0, 0.0),
            Geoshape.polygon(Arrays.asList(new double[][] { { -0.1, 47.9 }, { 0.1, 47.9 }, { 0.1, 48.1 },
                    { -0.1, 48.1 }, { -0.1, 47.9 } })),
            Arrays.asList("1", "2", "3"), Sets.newHashSet("1", "2"), Instant.ofEpochSecond(1));
    add(store, "doc1", doc1, true);
    clopen();
    assertTrue(index.exists());
    super.tearDown();
    super.setUp();
    assertFalse(index.exists());
}