List of usage examples for java.time Instant ofEpochMilli
public static Instant ofEpochMilli(long epochMilli)
From source file:ubicrypt.core.provider.lock.LockChecker.java
private void nextAttempt(Subscriber<? super LockStatus> subscriber, ProviderLock lock) { final long delay = lock.getExpires().toEpochMilli() - System.currentTimeMillis() + RandomUtils.nextLong(minDelayAttempt, maxDelayAttempt); log.debug("lock attempt acquire on:{}", Instant.ofEpochMilli(delay + System.currentTimeMillis())); timer(delay, MILLISECONDS).subscribe(Actions.empty(), subscriber::onError, () -> call(subscriber)); }
From source file:co.rsk.peg.BridgeSerializationUtilsTest.java
@Test public void serializeFederation() throws Exception { PowerMockito.mockStatic(RLP.class); mock_RLP_encodeBigInteger();/*from www .ja va 2s . c o m*/ mock_RLP_encodeList(); mock_RLP_encodeElement(); byte[][] publicKeyBytes = new byte[][] { BtcECKey.fromPrivate(BigInteger.valueOf(100)).getPubKey(), BtcECKey.fromPrivate(BigInteger.valueOf(200)).getPubKey(), BtcECKey.fromPrivate(BigInteger.valueOf(300)).getPubKey(), BtcECKey.fromPrivate(BigInteger.valueOf(400)).getPubKey(), BtcECKey.fromPrivate(BigInteger.valueOf(500)).getPubKey(), BtcECKey.fromPrivate(BigInteger.valueOf(600)).getPubKey(), }; Federation federation = new Federation( Arrays.asList(new BtcECKey[] { BtcECKey.fromPublicOnly(publicKeyBytes[0]), BtcECKey.fromPublicOnly(publicKeyBytes[1]), BtcECKey.fromPublicOnly(publicKeyBytes[2]), BtcECKey.fromPublicOnly(publicKeyBytes[3]), BtcECKey.fromPublicOnly(publicKeyBytes[4]), BtcECKey.fromPublicOnly(publicKeyBytes[5]), }), Instant.ofEpochMilli(0xabcdef), // 42L, NetworkParameters.fromID(NetworkParameters.ID_REGTEST)); byte[] result = BridgeSerializationUtils.serializeFederation(federation); StringBuilder expectedBuilder = new StringBuilder(); expectedBuilder.append("ff00abcdef"); // Creation time expectedBuilder.append("ff2a"); // Creation block number federation.getPublicKeys().stream().sorted(BtcECKey.PUBKEY_COMPARATOR).forEach(key -> { expectedBuilder.append("dd"); expectedBuilder.append(Hex.toHexString(key.getPubKey())); }); byte[] expected = Hex.decode(expectedBuilder.toString()); Assert.assertTrue(Arrays.equals(expected, result)); }
From source file:ubicrypt.core.provider.lock.LockChecker.java
private Instant nextExpires() { return Instant.ofEpochMilli(System.currentTimeMillis() + durationLockMs); }
From source file:io.stallion.utils.GeneralUtils.java
@Deprecated public static String formatLocalDateFromLong(long epochMillis, String formatPattern) { if (epochMillis == 0L) { return ""; }/*from w ww . ja v a2s. c o m*/ return formatLocalDateFromZonedDate(ZonedDateTime.ofInstant(Instant.ofEpochMilli(epochMillis), UTC), formatPattern); }
From source file:de.qaware.chronix.solr.ingestion.format.PrometheusTextFormatParser.java
/** * Extracts the metric timestamp from the parts. * * @param parts Parts./*from w w w. java2 s . c o m*/ * @return Metric timestamp. * @throws FormatParseException If something went wrong while extracting. */ private Instant getMetricTimestamp(String[] parts) throws FormatParseException { // If the timestamp is missing, wall clock time is assumed. if (parts.length < 3) { return clock.now(); } String value = parts[2]; try { long epochTime = Long.parseLong(value); return Instant.ofEpochMilli(epochTime); } catch (NumberFormatException e) { throw new FormatParseException("Can't convert '" + value + "' to long", e); } }
From source file:de.qaware.chronix.importer.csv.FileImporter.java
/** * Reads the given file / folder and calls the bi consumer with the extracted points * * @param points//from w w w . j a v a2s . c o m * @param folder * @param databases * @return */ public Pair<Integer, Integer> importPoints(Map<Attributes, Pair<Instant, Instant>> points, File folder, BiConsumer<List<ImportPoint>, Attributes>... databases) { final AtomicInteger pointCounter = new AtomicInteger(0); final AtomicInteger tsCounter = new AtomicInteger(0); final File metricsFile = new File(METRICS_FILE_PATH); LOGGER.info("Writing imported metrics to {}", metricsFile); LOGGER.info("Import supports csv files as well as gz compressed csv files."); try { final FileWriter metricsFileWriter = new FileWriter(metricsFile); Collection<File> files = new ArrayList<>(); if (folder.isFile()) { files.add(folder); } else { files.addAll(FileUtils.listFiles(folder, new String[] { "gz", "csv" }, true)); } AtomicInteger counter = new AtomicInteger(0); files.parallelStream().forEach(file -> { SimpleDateFormat sdf = new SimpleDateFormat(dateFormat); NumberFormat nf = DecimalFormat.getInstance(numberLocal); InputStream inputStream = null; BufferedReader reader = null; try { inputStream = new FileInputStream(file); if (file.getName().endsWith("gz")) { inputStream = new GZIPInputStream(inputStream); } reader = new BufferedReader(new InputStreamReader(inputStream)); //Read the first line String headerLine = reader.readLine(); if (headerLine == null || headerLine.isEmpty()) { boolean deleted = deleteFile(file, inputStream, reader); LOGGER.debug("File is empty {}. File {} removed {}", file.getName(), deleted); return; } //Extract the attributes from the file name //E.g. first_second_third_attribute.csv String[] fileNameMetaData = file.getName().split("_"); String[] metrics = headerLine.split(csvDelimiter); Map<Integer, Attributes> attributesPerTimeSeries = new HashMap<>(metrics.length); for (int i = 1; i < metrics.length; i++) { String metric = metrics[i]; String metricOnlyAscii = Normalizer.normalize(metric, Normalizer.Form.NFD); metricOnlyAscii = metric.replaceAll("[^\\x00-\\x7F]", ""); Attributes attributes = new Attributes(metricOnlyAscii, fileNameMetaData); //Check if meta data is completely set if (isEmpty(attributes)) { boolean deleted = deleteFile(file, inputStream, reader); LOGGER.info("Attributes contains empty values {}. File {} deleted {}", attributes, file.getName(), deleted); continue; } if (attributes.getMetric().equals(".*")) { boolean deleted = deleteFile(file, inputStream, reader); LOGGER.info("Attributes metric{}. File {} deleted {}", attributes.getMetric(), file.getName(), deleted); continue; } attributesPerTimeSeries.put(i, attributes); tsCounter.incrementAndGet(); } Map<Integer, List<ImportPoint>> dataPoints = new HashMap<>(); String line; while ((line = reader.readLine()) != null) { String[] splits = line.split(csvDelimiter); String date = splits[0]; Instant dateObject; if (instantDate) { dateObject = Instant.parse(date); } else if (sdfDate) { dateObject = sdf.parse(date).toInstant(); } else { dateObject = Instant.ofEpochMilli(Long.valueOf(date)); } for (int column = 1; column < splits.length; column++) { String value = splits[column]; double numericValue = nf.parse(value).doubleValue(); ImportPoint point = new ImportPoint(dateObject, numericValue); if (!dataPoints.containsKey(column)) { dataPoints.put(column, new ArrayList<>()); } dataPoints.get(column).add(point); pointCounter.incrementAndGet(); } } dataPoints.values().forEach(Collections::sort); IOUtils.closeQuietly(reader); IOUtils.closeQuietly(inputStream); dataPoints.forEach((key, importPoints) -> { for (BiConsumer<List<ImportPoint>, Attributes> database : databases) { database.accept(importPoints, attributesPerTimeSeries.get(key)); } points.put(attributesPerTimeSeries.get(key), Pair.of(importPoints.get(0).getDate(), importPoints.get(importPoints.size() - 1).getDate())); //write the stats to the file Instant start = importPoints.get(0).getDate(); Instant end = importPoints.get(importPoints.size() - 1).getDate(); try { writeStatsLine(metricsFileWriter, attributesPerTimeSeries.get(key), start, end); } catch (IOException e) { LOGGER.error("Could not write stats line", e); } LOGGER.info("{} of {} time series imported", counter.incrementAndGet(), tsCounter.get()); }); } catch (Exception e) { LOGGER.info("Exception while reading points.", e); } finally { //close all streams IOUtils.closeQuietly(reader); IOUtils.closeQuietly(inputStream); } }); } catch (Exception e) { LOGGER.error("Exception occurred during reading points."); } return Pair.of(tsCounter.get(), pointCounter.get()); }
From source file:dk.dma.ais.packet.AisPacketCSVOutputSink.java
private void addTimestampPretty(List fields, AisPacket packet) { final long timestamp = packet.getBestTimestamp(); if (timestamp >= 0) fields.add(DateTimeFormatter.ofPattern("dd/MM/uuuu HH:mm:ss") .format(ZonedDateTime.ofInstant(Instant.ofEpochMilli(timestamp), ZoneId.of("UTC")))); else/*w w w .ja va 2 s . c om*/ fields.add("null"); }
From source file:io.stallion.utils.GeneralUtils.java
@Deprecated public static String formatLocalDateFromLong(Long epochMillis, String formatPattern) { if (epochMillis == 0L || epochMillis == null) { return ""; }/*from w w w .java 2s . c o m*/ return formatLocalDateFromZonedDate(ZonedDateTime.ofInstant(Instant.ofEpochMilli(epochMillis), UTC), formatPattern); }
From source file:org.jesterj.ingest.scanners.JdbcScanner.java
private static String convertDateToString(Object value) { Instant instant = Instant.ofEpochMilli(((Date) value).getTime()); return DATE_FORMATTER.format(instant); }
From source file:com.bdb.weather.display.summary.WindSummary.java
@Override public void chartMouseClicked(ChartMouseEventFX event) { ChartEntity entity = event.getEntity(); ///*from w w w . java 2 s.c o m*/ // Was a point on the plot selected? // if (entity instanceof XYItemEntity) { XYItemEntity itemEntity = (XYItemEntity) entity; XYDataset dataset = itemEntity.getDataset(); Number x = dataset.getXValue(itemEntity.getSeriesIndex(), itemEntity.getItem()); LocalDate date = LocalDate.from(Instant.ofEpochMilli(x.longValue())); if (event.getTrigger().getClickCount() == 2) supporter.launchView(launcher, date); } }