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:dk.dma.ais.packet.AisPacketCSVOutputSink.java

protected String formatEta(Date eta) {
    LocalDateTime time = LocalDateTime.ofInstant(Instant.ofEpochMilli(eta.getTime()), ZoneId.systemDefault());
    return formatEta(time.getDayOfMonth(), time.getMonthValue(), time.getHour(), time.getMinute());
}

From source file:fi.hsl.parkandride.itest.PredictionITest.java

private static void assertIsNear(DateTime expected, DateTime actual) {
    Instant i1 = Instant.ofEpochMilli(expected.getMillis());
    Instant i2 = Instant.ofEpochMilli(actual.getMillis());
    Duration d = Duration.between(i1, i2).abs();
    assertThat(d.toMinutes()).as("distance to " + expected + " in minutes")
            .isLessThanOrEqualTo(PredictionRepository.PREDICTION_RESOLUTION.getMinutes());
}

From source file:com.vmware.admiral.compute.container.HostContainerListDataCollection.java

@Override
public void handlePatch(Operation op) {
    ContainerListCallback body = op.getBody(ContainerListCallback.class);

    if (body.hostAdapterReference == null) {
        body.hostAdapterReference = ContainerHostDataCollectionService.getDefaultHostAdapter(getHost());
    }// ww w  .  j a  va  2s.  com

    String containerHostLink = body.containerHostLink;
    if (containerHostLink == null) {
        logWarning("'containerHostLink' is required");
        op.complete();
        return;
    }

    HostContainerListDataCollectionState state = getState(op);
    if (body.unlockDataCollectionForHost) {
        // patch to mark that there is no active list containers data collection for a given
        // host.
        state.containerHostLinks.remove(containerHostLink);
        op.complete();
        return;
    }

    AssertUtil.assertNotNull(body.containerIdsAndNames, "containerIdsAndNames");

    if (Logger.getLogger(this.getClass().getName()).isLoggable(Level.FINE)) {
        logFine("Host container list callback invoked for host [%s] with container IDs: %s", containerHostLink,
                body.containerIdsAndNames.keySet().stream().collect(Collectors.toList()));
    }

    // the patch will succeed regardless of the synchronization process
    if (state.containerHostLinks.get(containerHostLink) != null && Instant.now()
            .isBefore(Instant.ofEpochMilli((state.containerHostLinks.get(containerHostLink))))) {
        if (Logger.getLogger(this.getClass().getName()).isLoggable(Level.FINE)) {
            logFine("Host container list callback for host [%s] with container IDs: %s "
                    + "skipped, another instance is active", containerHostLink,
                    body.containerIdsAndNames.keySet().stream().collect(Collectors.toList()));
        }
        op.complete();
        return; // return since there is an active data collection for this host.
    } else {
        state.containerHostLinks.put(containerHostLink,
                Instant.now().toEpochMilli() + DATA_COLLECTION_LOCK_TIMEOUT_MILLISECONDS);
        op.complete();
        // continue with the data collection.
    }

    List<ContainerState> containerStates = new ArrayList<ContainerState>();
    QueryTask queryTask = QueryUtil.buildPropertyQuery(ContainerState.class,
            ContainerState.FIELD_NAME_PARENT_LINK, containerHostLink);
    QueryUtil.addExpandOption(queryTask);

    QueryUtil.addBroadcastOption(queryTask);
    new ServiceDocumentQuery<ContainerState>(getHost(), ContainerState.class).query(queryTask, (r) -> {
        if (r.hasException()) {
            logSevere("Failed to query for existing ContainerState instances: %s",
                    r.getException() instanceof CancellationException ? r.getException().getMessage()
                            : Utils.toString(r.getException()));
            unlockCurrentDataCollectionForHost(containerHostLink);
        } else if (r.hasResult()) {
            containerStates.add(r.getResult());
        } else {
            AdapterRequest request = new AdapterRequest();
            request.operationTypeId = ContainerHostOperationType.LIST_CONTAINERS.id;
            request.serviceTaskCallback = ServiceTaskCallback.createEmpty();
            request.resourceReference = UriUtils.buildUri(getHost(), containerHostLink);
            sendRequest(Operation.createPatch(body.hostAdapterReference).setBody(request)
                    .addPragmaDirective(Operation.PRAGMA_DIRECTIVE_QUEUE_FOR_SERVICE_AVAILABILITY)
                    .setCompletion((o, ex) -> {
                        if (ex == null) {
                            ContainerListCallback callback = o.getBody(ContainerListCallback.class);
                            if (callback.hostAdapterReference == null) {
                                callback.hostAdapterReference = ContainerHostDataCollectionService
                                        .getDefaultHostAdapter(getHost());
                            }
                            updateContainerStates(callback, containerStates, containerHostLink);
                        } else {
                            unlockCurrentDataCollectionForHost(containerHostLink);
                        }
                    }));
        }
    });
}

From source file:org.codelibs.fess.web.IndexAction.java

@Execute(validator = true, input = "index")
public String go() throws IOException {
    Map<String, Object> doc = null;
    try {/*from ww w .j a v a2s.c  o m*/
        doc = searchService.getDocument(fieldHelper.docIdField + ":" + indexForm.docId,
                queryHelper.getResponseFields(), new String[] { fieldHelper.clickCountField });
    } catch (final Exception e) {
        logger.warn("Failed to request: " + indexForm.docId, e);
    }
    if (doc == null) {
        errorMessage = MessageResourcesUtil.getMessage(RequestUtil.getRequest().getLocale(),
                "errors.docid_not_found", indexForm.docId);
        return "error.jsp";
    }
    final Object urlObj = doc.get(fieldHelper.urlField);
    if (urlObj == null) {
        errorMessage = MessageResourcesUtil.getMessage(RequestUtil.getRequest().getLocale(),
                "errors.document_not_found", indexForm.docId);
        return "error.jsp";
    }
    final String url = urlObj.toString();

    if (Constants.TRUE.equals(crawlerProperties.getProperty(Constants.SEARCH_LOG_PROPERTY, Constants.TRUE))) {
        final String userSessionId = userInfoHelper.getUserCode();
        if (userSessionId != null) {
            final SearchLogHelper searchLogHelper = ComponentUtil.getSearchLogHelper();
            final ClickLog clickLog = new ClickLog();
            clickLog.setUrl(url);
            LocalDateTime now = systemHelper.getCurrentTime();
            clickLog.setRequestedTime(now);
            clickLog.setQueryRequestedTime(LocalDateTime
                    .ofInstant(Instant.ofEpochMilli(Long.parseLong(indexForm.rt)), ZoneId.systemDefault()));
            clickLog.setUserSessionId(userSessionId);
            clickLog.setDocId(indexForm.docId);
            long clickCount = 0;
            final Object count = doc.get(fieldHelper.clickCountField);
            if (count instanceof Long) {
                clickCount = ((Long) count).longValue();
            }
            clickLog.setClickCount(clickCount);
            searchLogHelper.addClickLog(clickLog);
        }
    }

    String hash;
    if (StringUtil.isNotBlank(indexForm.hash)) {
        final String value = URLUtil.decode(indexForm.hash, Constants.UTF_8);
        final StringBuilder buf = new StringBuilder(value.length() + 100);
        for (final char c : value.toCharArray()) {
            if (CharUtil.isUrlChar(c) || c == ' ') {
                buf.append(c);
            } else {
                try {
                    buf.append(URLEncoder.encode(String.valueOf(c), Constants.UTF_8));
                } catch (final UnsupportedEncodingException e) {
                    // NOP
                }
            }
        }
        hash = buf.toString();
    } else {
        hash = StringUtil.EMPTY;
    }

    if (isFileSystemPath(url)) {
        if (Constants.TRUE
                .equals(crawlerProperties.getProperty(Constants.SEARCH_FILE_PROXY_PROPERTY, Constants.TRUE))) {
            final CrawlingConfigHelper crawlingConfigHelper = ComponentUtil.getCrawlingConfigHelper();
            try {
                crawlingConfigHelper.writeContent(doc);
                return null;
            } catch (final Exception e) {
                logger.error("Failed to load: " + doc, e);
                errorMessage = MessageResourcesUtil.getMessage(RequestUtil.getRequest().getLocale(),
                        "errors.not_load_from_server", url);
                return "error.jsp";
            }
        } else if (Constants.TRUE
                .equals(crawlerProperties.getProperty(Constants.SEARCH_DESKTOP_PROPERTY, Constants.FALSE))) {
            final String path = url.replaceFirst("file:/+", "//");
            final File file = new File(path);
            if (!file.exists()) {
                errorMessage = MessageResourcesUtil.getMessage(RequestUtil.getRequest().getLocale(),
                        "errors.not_found_on_file_system", url);
                return "error.jsp";
            }
            final Desktop desktop = Desktop.getDesktop();
            try {
                desktop.open(file);
            } catch (final Exception e) {
                errorMessage = MessageResourcesUtil.getMessage(RequestUtil.getRequest().getLocale(),
                        "errors.could_not_open_on_system", url);
                logger.warn("Could not open " + path, e);
                return "error.jsp";
            }

            ResponseUtil.getResponse().setStatus(HttpServletResponse.SC_NO_CONTENT);
            return null;
        } else {
            ResponseUtil.getResponse().sendRedirect(url + hash);
        }
    } else {
        ResponseUtil.getResponse().sendRedirect(url + hash);
    }
    return null;
}

From source file:com.jsmartframework.web.manager.ExpressionHandler.java

private void setExpressionDate(String expr, String jParam) throws ServletException {
    if (isReadOnlyParameter(jParam)) {
        return;//from ww  w .  j ava  2  s .  co m
    }

    Matcher matcher = EL_PATTERN.matcher(expr);
    if (matcher.find()) {

        String beanMethod = matcher.group(1);
        String[] methodSign = beanMethod.split(Constants.EL_SEPARATOR);

        if (methodSign.length > 0 && WebContext.containsAttribute(methodSign[0])) {
            beanMethod = String.format(Constants.JSP_EL, beanMethod);

            ELContext context = WebContext.getPageContext().getELContext();
            ValueExpression valueExpr = WebContext.getExpressionFactory().createValueExpression(context,
                    beanMethod, Object.class);
            String value = WebContext.getRequest().getParameter(TagHandler.J_DATE + jParam);

            if (StringUtils.isNotBlank(value)) {
                Throwable throwable = null;
                try {
                    valueExpr.setValue(context, value);
                    return;
                } catch (Exception ex) {
                    throwable = ex;
                }

                Long timeMillis = Long.parseLong(value);
                try {
                    valueExpr.setValue(context, new Date(timeMillis));
                    return;
                } catch (Exception ex) {
                    throwable = ex;
                }

                try {
                    valueExpr.setValue(context,
                            Instant.ofEpochMilli(timeMillis).atZone(ZoneId.systemDefault()).toLocalDateTime());
                    return;
                } catch (Exception ex) {
                    throwable = ex;
                }

                try {
                    valueExpr.setValue(context, new DateTime(timeMillis));
                    return;
                } catch (Exception ex) {
                    throwable = ex;
                }

                if (throwable != null) {
                    throw new ServletException(throwable.getMessage());
                }
            } else {
                valueExpr.setValue(context, null);
            }
        }
    }
}

From source file:org.hawkular.alerter.elasticsearch.ElasticsearchQuery.java

public String formatTimestamp(Date date) {
    String definedPattern = properties.get(TIMESTAMP_PATTERN);
    if (definedPattern != null) {
        DateTimeFormatter formatter = null;
        try {//from  ww w.  ja va  2 s . co  m
            formatter = DateTimeFormatter.ofPattern(definedPattern);
            return formatter.format(ZonedDateTime.ofInstant(Instant.ofEpochMilli(date.getTime()), UTC));
        } catch (Exception e) {
            log.debugf("Not able to format [%s] with pattern [%s]", date, formatter);
        }
    }
    return DEFAULT_DATE_FORMATS[0].format(ZonedDateTime.ofInstant(Instant.ofEpochMilli(date.getTime()), UTC));
}

From source file:io.stallion.reflection.PropertyUtils.java

/**
 * Try to transform the passed in value into the destinationClass, via a applying a boatload of
 * heuristics.//from  www .jav a 2 s. c  om
 *
 * @param value
 * @param destinationClass
 * @return
 */
public static Object transform(Object value, Class destinationClass) {
    if (value == null) {
        return null;
    }
    if (value.getClass() == destinationClass)
        return value;
    if (destinationClass.isInstance(value)) {
        return value;
    }

    // If target type is Date and json was a long, convert the long to a date
    if (destinationClass == Date.class && (value.getClass() == long.class || value.getClass() == Long.class)) {
        return new Date((long) value);
    }
    // Convert integers to longs, if target type is long
    if ((destinationClass == Long.class || destinationClass == long.class)
            && (value.getClass() == int.class || value.getClass() == Integer.class)) {
        return new Long((int) value);
    }
    // Convert ints and longs to ZonedDateTime, if ZonedDateTime was a long
    if (destinationClass == ZonedDateTime.class
            && (value.getClass() == long.class || value.getClass() == Long.class
                    || value.getClass() == int.class || value.getClass() == Integer.class)) {
        if (value.getClass() == Integer.class || value.getClass() == int.class) {
            return ZonedDateTime.ofInstant(Instant.ofEpochMilli(((int) value) * 1000), GeneralUtils.UTC);
        } else {
            return ZonedDateTime.ofInstant(Instant.ofEpochMilli((long) value), GeneralUtils.UTC);
        }
    }

    if (destinationClass == ZonedDateTime.class && value instanceof Timestamp) {
        return ZonedDateTime.ofInstant(((Timestamp) value).toInstant(), UTC);
    }
    if (destinationClass == Long.class && value instanceof BigInteger) {
        return ((BigInteger) value).longValue();
    }

    if (destinationClass == ZonedDateTime.class
            && (value.getClass() == double.class || value.getClass() == Double.class)) {
        return ZonedDateTime.ofInstant(Instant.ofEpochMilli(Math.round((Double) value)), GeneralUtils.UTC);
    }

    // Convert Strings to Enums, if target type was an enum
    if (destinationClass.isEnum()) {
        return Enum.valueOf(destinationClass, value.toString());
    }

    if ((destinationClass == boolean.class || destinationClass == Boolean.class)) {
        if (value instanceof String) {
            return Boolean.valueOf((String) value);
        } else if (value instanceof Integer) {
            return (Integer) value > 0;
        } else if (value instanceof Long) {
            return (Long) value > 0;
        }
    }

    if ((destinationClass == byte.class || destinationClass == Byte.class)
            && value.getClass() == String.class) {
        return new Byte((String) value);
    }
    if ((destinationClass == short.class || destinationClass == Short.class)
            && value.getClass() == String.class) {
        return new Short((String) value);
    }
    if ((destinationClass == int.class || destinationClass == Integer.class)
            && value.getClass() == String.class) {
        return new Integer((String) value);
    }
    if ((destinationClass == long.class || destinationClass == Long.class)
            && value.getClass() == String.class) {
        return new Long((String) value);
    }
    if ((destinationClass == long.class || destinationClass == Long.class) && value instanceof Integer) {
        return new Long((Integer) value);
    }
    if ((destinationClass == float.class || destinationClass == Float.class)
            && value.getClass() == String.class) {
        return new Float((String) value);
    }
    if ((destinationClass == float.class || destinationClass == Float.class)
            && value.getClass() == Integer.class) {
        return ((Integer) value).floatValue();
    }
    if ((destinationClass == float.class || destinationClass == Float.class)
            && value.getClass() == Long.class) {
        return ((Long) value).floatValue();
    }
    if ((destinationClass == float.class || destinationClass == Float.class)
            && value.getClass() == Double.class) {
        return ((Double) value).floatValue();
    }

    if ((destinationClass == double.class || destinationClass == Double.class)
            && value.getClass() == Long.class) {
        return ((Long) value).floatValue();
    }

    if ((destinationClass == float.class || destinationClass == Float.class)
            && value.getClass() == String.class) {
        return new Float((String) value);
    }

    if ((destinationClass == double.class || destinationClass == Double.class)
            && value.getClass() == String.class) {
        return new Double((String) value);
    }

    // If the type mis-match is due to boxing, just return the value
    if (value.getClass() == boolean.class || value.getClass() == Boolean.class || value.getClass() == byte.class
            || value.getClass() == Byte.class || value.getClass() == short.class
            || value.getClass() == Short.class || value.getClass() == int.class
            || value.getClass() == Integer.class || value.getClass() == long.class
            || value.getClass() == Long.class || value.getClass() == float.class
            || value.getClass() == Float.class || value.getClass() == double.class
            || value.getClass() == Double.class)
        return value;

    throw new PropertyException("cannot convert values of type '" + value.getClass().getName() + "' into type '"
            + destinationClass + "'");
}

From source file:org.eclipse.smarthome.binding.wemo.handler.WemoCoffeeHandler.java

public State getDateTimeState(String attributeValue) {
    if (attributeValue != null) {
        long value = 0;
        try {/* w w w. j  a v  a 2s.c  o m*/
            value = Long.parseLong(attributeValue) * 1000; // convert s to ms
        } catch (NumberFormatException e) {
            logger.error("Unable to parse attributeValue '{}' for device '{}'; expected long", attributeValue,
                    getThing().getUID());
            return null;
        }
        ZonedDateTime zoned = ZonedDateTime.ofInstant(Instant.ofEpochMilli(value),
                TimeZone.getDefault().toZoneId());
        State dateTimeState = new DateTimeType(zoned);
        if (dateTimeState != null) {
            logger.trace("New attribute brewed '{}' received", dateTimeState);
            return dateTimeState;
        }
    }
    return null;
}

From source file:org.apache.nifi.processors.solr.SolrUtils.java

private static LocalDate getLocalDateFromEpochTime(String fieldName, Object coercedValue) {
    Long date = DataTypeUtils.toLong(coercedValue, fieldName);
    return Instant.ofEpochMilli(date).atZone(ZoneId.systemDefault()).toLocalDate();
}

From source file:org.apache.nifi.processors.solr.SolrUtils.java

private static LocalDateTime getLocalDateTimeFromEpochTime(String fieldName, Object coercedValue) {
    Long date = DataTypeUtils.toLong(coercedValue, fieldName);
    return Instant.ofEpochMilli(date).atZone(ZoneId.systemDefault()).toLocalDateTime();
}