Example usage for java.time Instant ofEpochMilli

List of usage examples for java.time Instant ofEpochMilli

Introduction

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

Prototype

public static Instant ofEpochMilli(long epochMilli) 

Source Link

Document

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

Usage

From source file:fi.luontola.cqrshotel.JsonSerializationTest.java

private static Object randomValue(Class<?> type) {
    ThreadLocalRandom random = ThreadLocalRandom.current();
    if (type == UUID.class) {
        return UUID.randomUUID();
    }/*from  w ww. ja  va  2 s  .c o m*/
    if (type == LocalDate.class) {
        return LocalDate.of(random.nextInt(2000, 2100),
                random.nextInt(Month.JANUARY.getValue(), Month.DECEMBER.getValue() + 1),
                random.nextInt(1, Month.FEBRUARY.minLength() + 1));
    }
    if (type == Money.class) {
        return Money.of(random.nextDouble(0, 1000), pickRandom(Monetary.getCurrencies()));
    }
    if (type == Instant.class) {
        return Instant.ofEpochMilli(random.nextLong());
    }
    if (type == String.class) {
        return RandomStringUtils.randomAlphanumeric(random.nextInt(10));
    }
    if (type == int.class) {
        return random.nextInt();
    }
    throw new IllegalArgumentException("Unsupported type: " + type);
}

From source file:edu.usu.sdl.openstorefront.service.message.SystemErrorAlertMessageGenerator.java

@Override
protected String generateMessageInternal(Email email) {
    StringBuilder message = new StringBuilder();
    SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss z");

    ErrorTicket errorTicketExample = new ErrorTicket();
    errorTicketExample.setActiveStatus(ErrorTicket.ACTIVE_STATUS);

    //We need to back up a bit to capture the error that triggered the message. It's possible it will pick old ones if they'are are close.
    ErrorTicket errorTicketStartExample = new ErrorTicket();
    Instant instant = Instant.ofEpochMilli(messageContext.getUserMessage().getCreateDts().getTime());
    instant = instant.minusSeconds(1);//from w  w  w .j a va2s.  co  m
    errorTicketStartExample.setCreateDts(new Date(instant.toEpochMilli()));

    QueryByExample queryByExample = new QueryByExample(errorTicketExample);
    SpecialOperatorModel specialOperatorModel = new SpecialOperatorModel();
    specialOperatorModel.getGenerateStatementOption()
            .setOperation(GenerateStatementOption.OPERATION_GREATER_THAN_EQUAL);
    specialOperatorModel.setExample(errorTicketStartExample);
    queryByExample.getExtraWhereCauses().add(specialOperatorModel);

    List<ErrorTicket> tickets = serviceProxy.getPersistenceService().queryByExample(ErrorTicket.class,
            queryByExample);
    if (!tickets.isEmpty()) {
        message.append("System errors have occured.  ").append(tickets.size()).append("  error(s) since: ")
                .append(sdf.format(messageContext.getUserMessage().getCreateDts())).append("<hr>");

        message.append("<ul>");
        for (ErrorTicket ticket : tickets) {
            message.append("  <li> ")
                    .append(TranslateUtil.translate(ErrorTypeCode.class, ticket.getErrorTypeCode()))
                    .append(" - ").append(ticket.getMessage()).append(" - ").append(ticket.getErrorTicketId())
                    .append("</li><br>");
        }
        message.append("</ul>");
        message.append("See attached for details.<br>");

        int max = tickets.size();
        if (tickets.size() > MAX_TICKETS_TO_ATTACH) {
            message.append("(Only ").append(MAX_TICKETS_TO_ATTACH)
                    .append(" are attached login to view more.<br>");
            max = MAX_TICKETS_TO_ATTACH;
        }

        for (int i = 0; i < max; i++) {
            ErrorTicket ticket = tickets.get(i);
            String ticketData = serviceProxy.getSystemService().errorTicketInfo(ticket.getErrorTicketId());
            if (StringUtils.isNotBlank(ticketData)) {
                email.addAttachment("error-" + ticket.getErrorTicketId() + ".txt",
                        ticketData.getBytes(Charset.defaultCharset()), "text/plain");
            }
        }
    } else {
        log.log(Level.WARNING,
                MessageFormat.format(
                        "System Error Message was queue...however no error tickets found within window. "
                                + " Likely, the error occur before message time window.  "
                                + "Use the System tool to find error.  Message Time: {0}",
                        sdf.format(messageContext.getUserMessage().getCreateDts())));
    }

    return message.toString();
}

From source file:Jimbo.Cheerlights.MQTTListener.java

/**
 * Receive an MQTT message./* w ww  . j a v a  2s  .  c o m*/
 * 
 * @param topic The topic it's on
 * @param message The message itself
 */
@Override
public void receive(String topic, String message) {
    try {
        JSONObject j = new JSONObject(message);

        final Instant instant = Instant.ofEpochMilli(j.getLong("sent")).truncatedTo(ChronoUnit.SECONDS);
        final LocalDateTime stamp = LocalDateTime.ofInstant(instant, ZONE);
        final String when = stamp.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME);

        LOG.log(Level.INFO, "{0} (@{1}) sent {2}: {3}",
                new Object[] { j.getString("name"), j.getString("screen"), when, j.getString("text") });
        target.update(j.getInt("colour"));
    }

    catch (JSONException | IOException e) {
        LOG.log(Level.WARNING, "Unable to parse: \"{0}\": {1}",
                new Object[] { message, e.getLocalizedMessage() });
    }
}

From source file:org.jimsey.projects.turbine.fuel.domain.IndicatorJson.java

@JsonCreator
public IndicatorJson(@JsonProperty("date") long date, @JsonProperty("close") double close,
        @JsonProperty("indicators") Map<String, Double> indicators, @JsonProperty("symbol") String symbol,
        @JsonProperty("market") String market, @JsonProperty("name") String name,
        @JsonProperty("timestamp") String timestamp) {
    this(OffsetDateTime.ofInstant(Instant.ofEpochMilli(date), ZoneId.systemDefault()), close, indicators,
            symbol, market, name, timestamp);
}

From source file:ddf.security.samlp.impl.SamlValidator.java

protected void checkTimestamp() throws ValidationException {
    DateTime issueInstant = getIssueInstant();
    if (issueInstant == null) {
        throw new ValidationException("Issue Instant cannot be null!");
    }/*from   www . ja  v  a 2 s  .  c  o  m*/

    Instant instant = Instant.ofEpochMilli(issueInstant.getMillis());
    Instant now = Instant.now();
    if (instant.minus(builder.clockSkew).isAfter(now)) {
        throw new ValidationException("Issue Instant cannot be in the future");
    }

    if (instant.plus(builder.clockSkew).isBefore(now.minus(builder.timeout))) {
        throw new ValidationException("Issue Instant was outside valid time range");
    }

}

From source file:de.qaware.chronix.solr.type.metric.functions.analyses.Frequency.java

/**
 * The frequency detector splits a time series into windows, counts the data points, and checks if the delta
 * between two windows is above a predefined threshold.
 * <p>/*from  w  w  w  .jav a2s.  c o m*/
 * The frequency detector splits a time series using the constructor argument.
 *
 * @param functionValueMap
 * @return true if the time series has a pair of windows 1 and 2 where 2 has th
 */
@Override
public void execute(MetricTimeSeries timeSeries, FunctionValueMap functionValueMap) {

    LongList timestamps = timeSeries.getTimestamps();

    final List<Long> currentWindow = new ArrayList<>();
    final List<Integer> windowCount = new ArrayList<>();

    //start and end of the window
    long windowStart = timestamps.get(0);
    //calculate the end
    long windowEnd = Instant.ofEpochMilli(windowStart).plus(windowSize, ChronoUnit.MINUTES).toEpochMilli();

    for (int i = 1; i < timeSeries.size(); i++) {
        long current = timestamps.get(i);
        //Add the occurrence of the current window.
        if (current > windowStart - 1 && current < (windowEnd)) {
            currentWindow.add(current);
        } else {
            //We reached the end. Lets add it to the window count
            windowCount.add(currentWindow.size());
            windowStart = current;
            windowEnd = Instant.ofEpochMilli(windowStart).plus(windowSize, ChronoUnit.MINUTES).toEpochMilli();
            currentWindow.clear();
        }
    }
    //we are done, add the last window
    windowCount.add(currentWindow.size());

    //check deltas
    for (int i = 1; i < windowCount.size(); i++) {

        int former = windowCount.get(i - 1);
        int current = windowCount.get(i);

        //The threshold
        int result = current - former;
        if (result >= windowThreshold) {
            //add the time series as there are more points per window than the threshold
            functionValueMap.add(this, true, null);
            return;
        }
    }
    //Nothing bad found
    functionValueMap.add(this, false, null);

}

From source file:de.qaware.chronix.solr.query.analysis.functions.analyses.Frequency.java

/**
 * Detects if a points occurs multiple times within a defined time range
 *
 * @param args the time series/* w w w. ja  v a 2 s  .  c  o m*/
 * @return 1 if there are more points than the defined threshold, otherwise -1
 */
@Override
public boolean execute(MetricTimeSeries... args) {
    if (args.length <= 0) {
        throw new IllegalArgumentException("Frequency needs at least one time series");
    }
    MetricTimeSeries timeSeries = args[0];
    LongList timestamps = timeSeries.getTimestamps();

    final List<Long> currentWindow = new ArrayList<>();
    final List<Integer> windowCount = new ArrayList<>();

    //start and end of the window
    long windowStart = timestamps.get(0);
    //calculate the end
    long windowEnd = Instant.ofEpochMilli(windowStart).plus(windowSize, ChronoUnit.MINUTES).toEpochMilli();

    for (int i = 1; i < timeSeries.size(); i++) {
        long current = timestamps.get(i);
        //Add the occurrence of the current window.
        if (current > windowStart - 1 && current < (windowEnd)) {
            currentWindow.add(current);
        } else {
            //We reached the end. Lets add it to the window count
            windowCount.add(currentWindow.size());
            windowStart = current;
            windowEnd = Instant.ofEpochMilli(windowStart).plus(windowSize, ChronoUnit.MINUTES).toEpochMilli();
            currentWindow.clear();
        }
    }
    //we are done, add the last window
    windowCount.add(currentWindow.size());

    //check deltas
    for (int i = 1; i < windowCount.size(); i++) {

        int former = windowCount.get(i - 1);
        int current = windowCount.get(i);

        //The threshold
        int result = current - former;
        if (result >= windowThreshold) {
            //add the time series as there are more points per window than the threshold
            return true;
        }
    }
    //Nothing bad found
    return false;
}

From source file:Graphite.java

private String getDateAsString(long start) {
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm_yyyyMMdd").withZone(zoneId);
    return formatter.format(Instant.ofEpochMilli(start));
}

From source file:org.jimsey.projects.turbine.fuel.domain.StrategyJson.java

@JsonCreator
public StrategyJson(@JsonProperty("date") long date, @JsonProperty("symbol") String symbol,
        @JsonProperty("market") String market, @JsonProperty("close") double close,
        @JsonProperty("name") String name, @JsonProperty("action") String action,
        @JsonProperty("amount") Integer amount, @JsonProperty("position") Integer position,
        @JsonProperty("cash") Double cash, @JsonProperty("value") Double value,
        @JsonProperty("timestamp") String timestamp) {
    this(OffsetDateTime.ofInstant(Instant.ofEpochMilli(date), ZoneId.systemDefault()), market, symbol, close,
            name, action, amount, position, cash, value, timestamp);
}

From source file:org.ops4j.pax.web.resources.extender.internal.IndexedOsgiResourceLocator.java

@Override
public void register(final Bundle bundle) {
    Collection<URL> urls;
    try {/*from w w w.  ja  va2s  . c  o m*/
        urls = Collections.list(bundle.findEntries(RESOURCE_ROOT, "*.*", true));
    } catch (IllegalStateException e) {
        logger.error("Error retrieving bundle-resources from bundle '{}'", bundle.getSymbolicName(), e);
        urls = Collections.emptyList();
    }

    urls.forEach(
            url -> index.addResourceToIndex(url.getPath(),
                    new ResourceInfo(url, LocalDateTime
                            .ofInstant(Instant.ofEpochMilli(bundle.getLastModified()), ZoneId.systemDefault()),
                            bundle.getBundleId()),
                    bundle));

    logger.info("Bundle '{}' scanned for resources in '{}': {} entries added to index.",
            new Object[] { bundle.getSymbolicName(), RESOURCE_ROOT, urls.size() });
}