List of usage examples for java.time Instant toEpochMilli
public long toEpochMilli()
From source file:com.github.ithildir.airbot.service.impl.AirNowMeasurementServiceImpl.java
private long _parseTime(String dateString, String timeString, String timeZoneString) { int year = Integer.parseInt(dateString.substring(6)) + 2000; int month = Integer.parseInt(dateString.substring(0, 2)); int dayOfMonth = Integer.parseInt(dateString.substring(3, 5)); int hour = Integer.parseInt(timeString.substring(0, timeString.length() - 3)); int minute = Integer.parseInt(timeString.substring(timeString.length() - 2)); ZoneId zoneId = ZoneId.of(timeZoneString, _shortZoneIds); ZonedDateTime zonedDateTime = ZonedDateTime.of(year, month, dayOfMonth, hour, minute, 0, 0, zoneId); Instant instant = zonedDateTime.toInstant(); return instant.toEpochMilli(); }
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 ww w. j ava2 s. c o 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:ai.grakn.engine.controller.TasksControllerTest.java
@Test public void afterSendingTaskWithRunAt_ItIsDelayedInStorage() { Instant runAt = now(); Map<String, String> defaultParams = defaultParams(); defaultParams.put(TASK_RUN_AT_PARAMETER, Long.toString(runAt.toEpochMilli())); send(Collections.emptyMap(), defaultParams); verify(manager).addTask(argThat(argument -> argument.schedule().runAt().equals(runAt)), any()); }
From source file:de.qaware.chronix.solr.ingestion.format.GraphiteFormatParser.java
@Override public Iterable<MetricTimeSeries> parse(InputStream stream) throws FormatParseException { Map<String, MetricTimeSeries.Builder> metrics = new HashMap<>(); BufferedReader reader = new BufferedReader(new InputStreamReader(stream, UTF_8)); String line;//from w w w .j a v a2s . c o m try { while ((line = reader.readLine()) != null) { // Format is: <metric path> <metric value> <metric timestamp> String[] parts = StringUtils.split(line, ' '); if (parts.length != 3) { throw new FormatParseException( "Expected 3 parts, found " + parts.length + " in line '" + line + "'"); } String metricName = getMetricName(parts); double value = getMetricValue(parts); Instant timestamp = getMetricTimestamp(parts); // If the metric is already known, add a point. Otherwise create the metric and add the point. MetricTimeSeries.Builder metricBuilder = metrics.get(metricName); if (metricBuilder == null) { metricBuilder = new MetricTimeSeries.Builder(metricName, METRIC_TYPE); metrics.put(metricName, metricBuilder); } metricBuilder.point(timestamp.toEpochMilli(), value); } } catch (IOException e) { throw new FormatParseException("IO exception while parsing Graphite format", e); } return metrics.values().stream().map(MetricTimeSeries.Builder::build).collect(Collectors.toList()); }
From source file:eu.fthevenet.binjr.sources.jrds.adapters.JrdsDataAdapter.java
@Override protected URI craftFetchUri(String path, Instant begin, Instant end) throws DataAdapterException { try {/* w w w . j a v a 2 s. co m*/ return new URIBuilder(getBaseAddress().toURI()).setPath(getBaseAddress().getPath() + "/download") .addParameter("id", path).addParameter("begin", Long.toString(begin.toEpochMilli())) .addParameter("end", Long.toString(end.toEpochMilli())).build(); } catch (URISyntaxException e) { throw new SourceCommunicationException("Error building URI for request", e); } }
From source file:ws.salient.session.Session.java
public final void accept(Command request) { Instant instant = request.getTimestamp(); MDC.put("sessionId", sessionId); MDC.put("instant", instant.toString()); try {//from w w w .j av a2s . c om log.info(knowledgeBase.getJson().writeValueAsString(request)); } catch (JsonProcessingException ex) { } long sessionTime = getClock().getCurrentTime(); long advanceTime = instant.toEpochMilli() - sessionTime; getClock().advanceTime(advanceTime, TimeUnit.MILLISECONDS); ksession.fireAllRules(); if (request instanceof Insert) { Insert insert = (Insert) request; ArrayNode inserts = insert.getObjects(); List objects = inserts(inserts); insertAll(objects); } else if (request instanceof CompleteWorkItem) { CompleteWorkItem workItem = (CompleteWorkItem) request; Long workItemId = workItem.getWorkItemId(); Map<String, ?> source = workItem.getResult(); completeWorkItem(workItemId, source); } else if (request instanceof AbortWorkItem) { AbortWorkItem workItem = (AbortWorkItem) request; Long workItemId = workItem.getWorkItemId(); ksession.getWorkItemManager().abortWorkItem(workItemId); } else if (request instanceof WorkItemException) { WorkItemException workItem = (WorkItemException) request; Long workItemId = workItem.getWorkItemId(); Exception exception = workItem.getException(); handleException(workItemId, exception); } if (eventCounter != null) { eventCounter.incrementAndGet(); } }
From source file:de.qaware.chronix.solr.ingestion.format.PrometheusTextFormatParser.java
/** * Adds a point to the given metrics map. If the metric doesn't exist in the map, it will be created. * * @param metrics Metric map.// w ww . ja va 2 s . c o m * @param metricName Name of the metric. * @param timestamp Timestamp of the point. * @param value Value of the point. * @param tags Tags for the metric. These are only used if the metric doesn't already exist in the metrics map. */ private void addPoint(Map<Metric, MetricTimeSeries.Builder> metrics, String metricName, Instant timestamp, double value, Map<String, String> tags) { Metric metric = new Metric(metricName, tags); MetricTimeSeries.Builder metricBuilder = metrics.get(metric); if (metricBuilder == null) { metricBuilder = new MetricTimeSeries.Builder(metricName, METRIC_TYPE); for (Map.Entry<String, String> tagEntry : tags.entrySet()) { metricBuilder.attribute(tagEntry.getKey(), tagEntry.getValue()); } metrics.put(metric, metricBuilder); } metricBuilder.point(timestamp.toEpochMilli(), value); }
From source file:com.netflix.genie.web.jpa.services.JpaJobPersistenceServiceImpl.java
/** * {@inheritDoc}/*from ww w .ja va 2 s . co m*/ */ @Override public long deleteBatchOfJobsCreatedBeforeDate(@NotNull final Instant date, @Min(1) final int maxDeleted, @Min(1) final int pageSize) { log.info("Attempting to delete batch of jobs (at most {}) created before {} ms from epoch", maxDeleted, date.toEpochMilli()); long jobsDeleted = 0; long totalAttemptedDeletions = 0; final Pageable page = PageRequest.of(0, pageSize); Slice<IdProjection> idProjections; do { idProjections = this.jobRepository.findByCreatedBefore(date, page); if (idProjections.hasContent()) { final List<Long> ids = idProjections.getContent().stream().map(IdProjection::getId) .collect(Collectors.toList()); final long toBeDeleted = ids.size(); totalAttemptedDeletions += toBeDeleted; log.debug("Attempting to delete {} rows from jobs...", toBeDeleted); final long deletedJobs = this.jobRepository.deleteByIdIn(ids); log.debug("Successfully deleted {} rows from jobs...", deletedJobs); if (deletedJobs != toBeDeleted) { log.error("Deleted {} job records but expected to delete {}", deletedJobs, toBeDeleted); } jobsDeleted += deletedJobs; } } while (idProjections.hasNext() && totalAttemptedDeletions < maxDeleted); log.info("Deleted a chunk of {} job records: {} job", totalAttemptedDeletions, jobsDeleted); return totalAttemptedDeletions; }
From source file:ai.grakn.engine.controller.TasksControllerTest.java
@Test public void whenGettingTaskByIdDelayed_TaskIdReturned() { Instant runAt = Instant.now().plusMillis(10); TaskState task = createTask(ShortExecutionMockTask.class, TaskSchedule.at(runAt)); when(manager.storage().getState(task.getId())).thenReturn(task); Response response = get(task.getId()); Json json = response.as(Json.class, jsonMapper); assertThat(json.at("id").asString(), equalTo(task.getId().getValue())); assertThat(json.at(TASK_RUN_AT_PARAMETER).asLong(), equalTo(runAt.toEpochMilli())); }
From source file:ws.salient.session.Session.java
public void init(KnowledgeBase knowledgeBase, Properties properties, Injector parentInjector, Instant instant, byte[] sessionBytes, Sessions sessions) { this.knowledgeBase = knowledgeBase; this.properties = properties; eventCounter = null;/*from w w w . ja va 2 s. co m*/ injector = parentInjector.createChildInjector(new SessionModule(properties, knowledgeBase)); ksession = (StatefulKnowledgeSessionImpl) injector.getInstance(KieSession.class); setGlobals(injector); SessionPseudoClock clock = (SessionPseudoClock) ksession.getSessionClock(); clock.advanceTime(instant.toEpochMilli(), TimeUnit.MILLISECONDS); workItemHandlers = new LinkedList(); ksession.getKnowledgeBase().getProcesses().forEach((process) -> { for (Node node : ((RuleFlowProcess) process).getNodes()) { if (node instanceof WorkItemNode) { try { WorkItemNode workItemNode = (WorkItemNode) node; String handlerName = workItemNode.getWork().getName(); System.out.println(handlerName); Class handlerType = knowledgeBase.getContainer().getClassLoader().loadClass(handlerName); AsyncTaskHandler handler = new AsyncTaskHandler(sessionId, (WorkItemHandler) injector.getInstance(handlerType), sessions); workItemHandlers.add(handler); ksession.getWorkItemManager().registerWorkItemHandler(handlerName, handler); } catch (ClassNotFoundException ex) { throw new RuntimeException(ex); } } } }); ksession.addEventListener(new DefaultProcessEventListener() { @Override public void afterNodeTriggered(ProcessNodeTriggeredEvent pnte) { ksession.fireAllRules(); } }); if (sessionBytes != null) { try { knowledgeBase.getMarshaller().unmarshall(new ByteArrayInputStream(sessionBytes), ksession); // Bug in DefaultProcessInstanceManager, doesn't reset processCounter after unmarshal Optional<Long> maxId = ksession.getProcessInstances().stream().map(ProcessInstance::getId) .max(Long::compare); if (maxId.isPresent()) { ProcessRuntimeImpl processRuntime = (ProcessRuntimeImpl) ksession.getProcessRuntime(); DefaultProcessInstanceManager processManager = (DefaultProcessInstanceManager) processRuntime .getProcessInstanceManager(); Field counterField = processManager.getClass().getDeclaredField("processCounter"); counterField.setAccessible(true); AtomicLong counter = (AtomicLong) counterField.get(processManager); counter.set(maxId.get()); } } catch (IllegalAccessException | NoSuchFieldException | ClassNotFoundException | IOException ex) { log.error("Error unmarshalling session: " + sessionId, ex); throw new RuntimeException(ex); } } }