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:org.pdfsam.ui.StatefullPreferencesStageService.java

public Instant getLatestNewsStageDisplayInstant() {
    return Instant.ofEpochMilli(Preferences.userRoot().node(STAGE_PATH).getLong(NEWS_STAGE_DISPLAY_TIME_KEY,
            Instant.EPOCH.toEpochMilli()));
}

From source file:org.commonjava.indy.ftest.core.AbstractIndyFunctionalTest.java

@SuppressWarnings("resource")
@Before//ww  w .  j  a va 2s .co  m
public void start() throws Throwable {
    try {
        final long start = System.currentTimeMillis();
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                long time = System.currentTimeMillis();
                System.out.printf("\n\n\nDate: %s\nElapsed: %s\n\n\n", new Date(time),
                        Duration.between(Instant.ofEpochMilli(start), Instant.ofEpochMilli(time)));
            }
        };

        new Timer().scheduleAtFixedRate(task, 0, 5000);

        Thread.currentThread().setName(getClass().getSimpleName() + "." + name.getMethodName());

        fixture = newServerFixture();
        fixture.start();

        if (!fixture.isStarted()) {
            final BootStatus status = fixture.getBootStatus();
            throw new IllegalStateException("server fixture failed to boot.", status.getError());
        }

        client = createIndyClient();
    } catch (Throwable t) {
        logger.error("Error initializing test", t);
        throw t;
    }
}

From source file:io.gravitee.management.service.impl.InstanceServiceImpl.java

@Override
public Collection<InstanceListItem> findInstances(boolean includeStopped) {
    Set<EventEntity> events;

    if (includeStopped) {
        events = eventService.findByType(instancesAllState);
    } else {/* w ww  . jav a2  s.  c o m*/
        events = eventService.findByType(instancesRunningOnly);
    }

    Instant nowMinusXMinutes = Instant.now().minus(5, ChronoUnit.MINUTES);
    return events.stream().map(event -> {
        Map<String, String> props = event.getProperties();
        InstanceListItem instance = new InstanceListItem(props.get("id"));
        instance.setEvent(event.getId());
        instance.setLastHeartbeatAt(new Date(Long.parseLong(props.get("last_heartbeat_at"))));
        instance.setStartedAt(new Date(Long.parseLong(props.get("started_at"))));

        if (event.getPayload() != null) {
            try {
                InstanceInfo info = objectMapper.readValue(event.getPayload(), InstanceInfo.class);
                instance.setHostname(info.getHostname());
                instance.setIp(info.getIp());
                instance.setVersion(info.getVersion());
                instance.setTags(info.getTags());
                instance.setOperatingSystemName(info.getSystemProperties().get("os.name"));
            } catch (IOException ioe) {
                LOGGER.error("Unexpected error while getting instance informations from event payload", ioe);
            }
        }

        if (event.getType() == EventType.GATEWAY_STARTED) {
            instance.setState(InstanceState.STARTED);
            // If last heartbeat timestamp is < now - 5m, set as unknown state
            Instant lastHeartbeat = Instant.ofEpochMilli(instance.getLastHeartbeatAt().getTime());
            if (lastHeartbeat.isBefore(nowMinusXMinutes)) {
                instance.setState(InstanceState.UNKNOWN);
            }
        } else {
            instance.setState(InstanceState.STOPPED);
            instance.setStoppedAt(new Date(Long.parseLong(props.get("stopped_at"))));
        }

        return instance;
    }).collect(Collectors.toList());
}

From source file:com.hotelbeds.hotelapimodel.auto.util.AssignUtils.java

public static LocalDateTime getLocalDateTime(Date date) {
    Instant instant = Instant.ofEpochMilli(date.getTime());
    return LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
}

From source file:com.netflix.genie.agent.execution.services.impl.grpc.GrpcAgentHeartBeatServiceImpl.java

private synchronized void setDisconnected() {
    this.isConnected = false;

    // Schedule a stream reset
    this.taskScheduler.schedule(this::resetStreamTask,
            Instant.ofEpochMilli(System.currentTimeMillis() + STREAM_RESET_DELAY_MILLIS));
}

From source file:io.adeptj.runtime.servlet.ToolsServlet.java

/**
 * Renders tools page./*w ww. j a v  a 2  s  . c  o m*/
 */
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
    Bundle[] bundles = BundleContextHolder.getInstance().getBundleContext().getBundles();
    long startTime = ManagementFactory.getRuntimeMXBean().getStartTime();
    MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();
    TemplateEngines.getDefault().render(TemplateContext.builder().request(req).response(resp)
            .template(TOOLS_TEMPLATE).locale(req.getLocale())
            .contextObject(ContextObject.newContextObject().put("username", req.getRemoteUser())
                    .put("sysProps", System.getProperties().entrySet()).put("totalBundles", bundles.length)
                    .put("bundles", bundles)
                    .put("runtime", JAVA_RUNTIME_NAME + "(build " + JAVA_RUNTIME_VERSION + ")")
                    .put("jvm", JAVA_VM_NAME + "(build " + JAVA_VM_VERSION + ", " + JAVA_VM_INFO + ")")
                    .put("startTime", Date.from(Instant.ofEpochMilli(startTime)))
                    .put("upTime", Times.format(startTime))
                    .put("maxMemory",
                            FileUtils.byteCountToDisplaySize(memoryMXBean.getHeapMemoryUsage().getMax()))
                    .put("usedMemory",
                            FileUtils.byteCountToDisplaySize(memoryMXBean.getHeapMemoryUsage().getUsed()))
                    .put("processors", Runtime.getRuntime().availableProcessors()))
            .build());
}

From source file:com.adeptj.runtime.servlet.ToolsServlet.java

/**
 * Renders tools page./*from   w  ww.  j av  a2s. c  o m*/
 */
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
    Bundle[] bundles = BundleContextHolder.getInstance().getBundleContext().getBundles();
    long startTime = ManagementFactory.getRuntimeMXBean().getStartTime();
    MemoryUsage memoryUsage = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage();
    TemplateEngine.getInstance()
            .render(TemplateContext.builder().request(req).response(resp).template(TOOLS_TEMPLATE)
                    .locale(req.getLocale())
                    .templateData(TemplateData.newTemplateData().put("username", req.getRemoteUser())
                            .put("sysProps", System.getProperties().entrySet())
                            .put("totalBundles", bundles.length).put("bundles", bundles)
                            .put("runtime", JAVA_RUNTIME_NAME + "(build " + JAVA_RUNTIME_VERSION + ")")
                            .put("jvm", JAVA_VM_NAME + "(build " + JAVA_VM_VERSION + ", " + JAVA_VM_INFO + ")")
                            .put("startTime", Date.from(Instant.ofEpochMilli(startTime)))
                            .put("upTime", Times.format(startTime))
                            .put("maxMemory", FileUtils.byteCountToDisplaySize(memoryUsage.getMax()))
                            .put("usedMemory", FileUtils.byteCountToDisplaySize(memoryUsage.getUsed()))
                            .put("processors", Runtime.getRuntime().availableProcessors()))
                    .build());
}

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

@JsonCreator
public TickJson(@JsonProperty("date") long date, @JsonProperty("open") double open,
        @JsonProperty("high") double high, @JsonProperty("low") double low, @JsonProperty("close") double close,
        @JsonProperty("volume") double volume, @JsonProperty("symbol") String symbol,
        @JsonProperty("market") String market, @JsonProperty("timestamp") String timestamp) {
    this(OffsetDateTime.ofInstant(Instant.ofEpochMilli(date), ZoneId.systemDefault()), open, high, low, close,
            volume, symbol, market, timestamp);
}

From source file:br.ufac.sion.service.AuditoriaService.java

public Set<AuditoriaDTO> findAllRevisions(FiltroAuditoria filtro) throws NegocioException {
    if (filtro.getDataInicio() != null && filtro.getDataFim() != null) {
        if (!filtro.getDataFim().isAfter(filtro.getDataInicio())) {
            throw new NegocioException("A data de termino deve ser maior que a data de incio!");
        }/*from w  w  w .  ja  v a 2 s  .  co  m*/
    }
    Set<AuditoriaDTO> dtos = new HashSet<>();

    AuditReader reader = AuditReaderFactory.get(em);

    AuditQuery query = reader.createQuery().forRevisionsOfEntity(filtro.getClasse(), false, true);

    if (filtro.getDataInicio() != null) {
        query.add(AuditEntity.revisionProperty("timestamp")
                .gt(Timestamp.from(filtro.getDataInicio().toInstant(ZoneOffset.UTC)).getTime()));
    }
    if (filtro.getDataFim() != null) {
        query.add(AuditEntity.revisionProperty("timestamp")
                .lt(Timestamp.from(filtro.getDataFim().toInstant(ZoneOffset.UTC)).getTime()));
    }

    if (StringUtils.isNotEmpty(filtro.getLogin())) {
        query.add(AuditEntity.revisionProperty("username").ilike(filtro.getLogin(), MatchMode.EXACT));
    }

    if (filtro.getTiposRevisao().length > 0) {
        System.out.println("entra id tipo revisao");
        query.add(AuditEntity.property("REVTYPE").in(filtro.getTiposRevisao()));
    }

    List<Object[]> result = query.getResultList();

    for (Object[] o : result) {
        try {
            //                Object instancia = filtro.getClass().cast(o[0]);
            Object instancia = Class.forName(filtro.getClasse().getName()).cast(o[0]);
            //                Method metodo;
            //                metodo = instancia.getClass().getMethod("getId");
            //                Long id = (Long) metodo.invoke(instancia);

            CustomRevisionEntity revision = (CustomRevisionEntity) o[1];
            RevisionType revisionType = (RevisionType) o[2];

            Instant instant = Instant.ofEpochMilli(revision.getTimestamp());

            AuditoriaDTO dto = new AuditoriaDTO(instancia, revisionType, filtro.getEntidade(), revision);

            dtos.add(dto);
        } catch (Exception ex) {
            throw new NegocioException(ex.getMessage());
        }
    }
    return dtos;
}