List of usage examples for java.time Instant ofEpochMilli
public static Instant ofEpochMilli(long epochMilli)
From source file:com.bdb.weather.display.summary.HighLowPanel.java
@Override public void chartMouseClicked(ChartMouseEventFX event) { ChartEntity entity = event.getEntity(); ///*from w w w .j a va2 s . c om*/ // 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())); boolean doubleClick = event.getTrigger().getClickCount() == 2; if (doubleClick) { supporter.launchView(launcher, date); } } }
From source file:io.stallion.dataAccess.db.DB.java
/** * Intialize the database based on the passed in configuration object. * @param config// w w w.j av a 2 s. c om */ public void initialize(DbConfig config) { try { dbImplementation = (DbImplementation) StallionClassLoader.loadClass(config.getImplementationClass()) .newInstance(); } catch (InstantiationException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } // Test out the connection. We do this directly, because if we test via the ComboPooledDataSource // exceptions will make the driver hang while retrying, and will also bury the underlying cause try { Driver driver = (Driver) StallionClassLoader.loadClass(config.getDriverClass()).newInstance(); Properties props = new Properties(); props.setProperty("user", config.getUsername()); props.setProperty("password", config.getPassword()); try (Connection conn = driver.connect(config.getUrl(), props)) { Statement st = conn.createStatement(); ResultSet results = st.executeQuery("SELECT 1 AS oneCol"); results.next(); Long i = results.getLong("oneCol"); assert i == 1L; } } catch (SQLException e) { throw new RuntimeException(e); } catch (InstantiationException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } ComboPooledDataSource cpds = new ComboPooledDataSource(); /* try { try (Connection conn = cpds.getConnection()) { Statement st = conn.createStatement(); ResultSet results = st.executeQuery("SELECT 1"); Long i = results.getLong(0); assert i == 1L; } } catch (SQLException e) { throw new RuntimeException(e); } */ try { cpds.setDriverClass(config.getDriverClass()); //loads the jdbc driver } catch (PropertyVetoException e) { throw new RuntimeException(e); } String url = config.getUrl(); if (!url.contains("?")) { url += "?"; } // Assume the database server is in UTC if (!url.contains("&useLegacyDatetimeCode=")) { url += "&useLegacyDatetimeCode=false"; } if (!url.contains("&serverTimezone=")) { url += "&serverTimezone=UTC"; } //&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC cpds.setJdbcUrl(url); cpds.setUser(config.getUsername()); cpds.setPassword(config.getPassword()); if (url.contains("utf8mb4_unicode_ci")) { cpds.setConnectionCustomizerClassName("io.stallion.dataAccess.db.mysql.Utf8InitCustomizer"); } cpds.setAcquireRetryAttempts(10); cpds.setAcquireRetryDelay(200); //cpds.setCheckoutTimeout(1); // the settings below are optional -- c3p0 can work with defaults cpds.setMinPoolSize(5); cpds.setAcquireIncrement(5); cpds.setMaxPoolSize(20); cpds.setIdleConnectionTestPeriod(5000); cpds.setTestConnectionOnCheckin(true); this.dataSource = cpds; // Make sure the database server time is UTC and in sync with the local server time // or else stop execution to prevent nasty and insiduious errors. //Timestamp date = this.queryScalar(dbImplementation.getCurrentTimeStampQuery()); Timestamp date = this.queryScalar(dbImplementation.getCurrentTimeStampQuery()); ZonedDateTime now = utcNow(); ZonedDateTime dbTime = ZonedDateTime.ofInstant(Instant.ofEpochMilli(date.getTime()), ZoneId.of("UTC")); //LocalDateTime now = utcNow().toLocalDateTime(); ZonedDateTime max = now.plusMinutes(2); ZonedDateTime min = now.minusMinutes(2); //LocalDateTime dbTime = date.toLocalDateTime(); if (dbTime.isAfter(max) || dbTime.isBefore(min)) { throw new ConfigException( "The database CURRENT_TIMESTAMP() is mismatched with the server time. Db time is " + dbTime + ". Server time is " + now + ". Make sure the database server is in UTC and that all your servers clocks are matched. "); } // Todo: why not lazy load converters??? registerConverter(new JsonMapConverter()); registerConverter(new JsonSetConverter()); registerConverter(new JsonObjectConverter()); registerConverter(new JsonListConverter()); this.tickets = dbImplementation.initTicketsService(this); }
From source file:software.reinvent.dependency.parser.service.ArtifactDependencyGraph.java
/** * Adds a non parent {@link Model} as {@link Artifact}. * * @param model the model to parse/* w ww . j a v a2 s. c o m*/ */ private void addArtifact(final Model model) { final Properties properties = model.getProperties(); final List<Dependency> dependencies = model.getDependencies(); setVersionToDepencies(model, dependencies); final Set<ArtifactDependency> artifactDependencies = addDependencies(dependencies); final String groupId = model.getGroupId() == null ? model.getParent().getGroupId() : model.getGroupId(); final ArtifactParent artifactParent = model.getParent() == null ? null : new ArtifactParent(model.getParent()); Artifact artifact = new Artifact( groupId, model.getArtifactId(), model.getVersion(), model.getPackaging(), LocalDateTime .ofInstant(Instant.ofEpochMilli(model.getPomFile().lastModified()), ZoneId.systemDefault()), artifactParent); if (artifacts.contains(artifact)) { artifacts.stream().filter(x -> x.equals(artifact)).findFirst().ifPresent(x -> { if (x.getFileDate().isBefore(artifact.getFileDate())) { artifacts.remove(artifact); } else { x.getDependencies().addAll(artifactDependencies); } }); artifact.getDependencies().addAll(artifactDependencies); artifacts.add(artifact); } else { artifact.getDependencies().addAll(artifactDependencies); artifacts.add(artifact); } }
From source file:com.joyent.manta.util.MantaUtilsTest.java
public void canCreateStringMapFromObjectMap() { Map<String, Object> objectMap = new LinkedHashMap<>(); objectMap.put("key1", 12); objectMap.put("key2", Instant.ofEpochMilli(72)); objectMap.put("key3", Arrays.asList("hello", "goodbye")); objectMap.put("key4", Arrays.asList("one", "two", "three")); Map<String, String> stringMap = MantaUtils.asStringMap(objectMap); String expected = "{key1=12, key2=1970-01-01T00:00:00.072Z, key3=hello, goodbye, key4=one, two, three}"; @SuppressWarnings("unchecked") String actual = StringUtils.join(stringMap); assertEquals(actual, expected,//from w w w . j ava2s .c o m "We should be able to transparently " + "convert object maps to string maps"); }
From source file:org.apache.solr.schema.TestUseDocValuesAsStored.java
private String[] nextValues(int arity, String valueType) throws Exception { String[] values = new String[arity]; for (int i = 0; i < arity; ++i) { switch (valueType) { case "int": values[i] = String.valueOf(random().nextInt()); break; case "double": values[i] = String.valueOf(Double.longBitsToDouble(random().nextLong())); break; case "long": values[i] = String.valueOf(random().nextLong()); break; case "float": values[i] = String.valueOf(Float.intBitsToFloat(random().nextInt())); break; case "enum": values[i] = SEVERITY[TestUtil.nextInt(random(), 0, SEVERITY.length - 1)]; break; case "str": { String str = TestUtil.randomRealisticUnicodeString(random()); values[i] = BAD_CHAR_PATTERN.matcher(str).replaceAll("\uFFFD"); break; }/* w w w.j a v a2s .com*/ case "date": { long epochMillis = TestUtil.nextLong(random(), START_RANDOM_EPOCH_MILLIS, END_RANDOM_EPOCH_MILLIS); values[i] = Instant.ofEpochMilli(epochMillis).toString(); break; } default: throw new Exception("unknown type '" + valueType + "'"); } } return values; }
From source file:org.springframework.web.reactive.resource.ResourceWebHandler.java
/** * Processes a resource request.// www .jav a2s . c o m * <p>Checks for the existence of the requested resource in the configured list of locations. * If the resource does not exist, a {@code 404} response will be returned to the client. * If the resource exists, the request will be checked for the presence of the * {@code Last-Modified} header, and its value will be compared against the last-modified * timestamp of the given resource, returning a {@code 304} status code if the * {@code Last-Modified} value is greater. If the resource is newer than the * {@code Last-Modified} value, or the header is not present, the content resource * of the resource will be written to the response with caching headers * set to expire one year in the future. */ @Override public Mono<Void> handle(ServerWebExchange exchange) { return getResource(exchange).switchIfEmpty(Mono.defer(() -> { logger.trace("No matching resource found - returning 404"); return Mono.error(NOT_FOUND_EXCEPTION); })).flatMap(resource -> { try { if (HttpMethod.OPTIONS.matches(exchange.getRequest().getMethodValue())) { exchange.getResponse().getHeaders().add("Allow", "GET,HEAD,OPTIONS"); return Mono.empty(); } // Supported methods and required session HttpMethod httpMethod = exchange.getRequest().getMethod(); if (!SUPPORTED_METHODS.contains(httpMethod)) { return Mono.error(new MethodNotAllowedException(exchange.getRequest().getMethodValue(), SUPPORTED_METHODS)); } // Header phase if (exchange.checkNotModified(Instant.ofEpochMilli(resource.lastModified()))) { logger.trace("Resource not modified - returning 304"); return Mono.empty(); } // Apply cache settings, if any if (getCacheControl() != null) { String value = getCacheControl().getHeaderValue(); if (value != null) { exchange.getResponse().getHeaders().setCacheControl(value); } } // Check the media type for the resource MediaType mediaType = MediaTypeFactory.getMediaType(resource).orElse(null); if (mediaType != null) { if (logger.isTraceEnabled()) { logger.trace("Determined media type '" + mediaType + "' for " + resource); } } else { if (logger.isTraceEnabled()) { logger.trace("No media type found " + "for " + resource + " - not sending a content-type header"); } } // Content phase if (HttpMethod.HEAD.matches(exchange.getRequest().getMethodValue())) { setHeaders(exchange, resource, mediaType); exchange.getResponse().getHeaders().set(HttpHeaders.ACCEPT_RANGES, "bytes"); logger.trace("HEAD request - skipping content"); return Mono.empty(); } setHeaders(exchange, resource, mediaType); ResourceHttpMessageWriter writer = getResourceHttpMessageWriter(); Assert.state(writer != null, "No ResourceHttpMessageWriter"); return writer.write(Mono.just(resource), null, ResolvableType.forClass(Resource.class), mediaType, exchange.getRequest(), exchange.getResponse(), Collections.emptyMap()); } catch (IOException ex) { return Mono.error(ex); } }); }
From source file:org.hawkular.alerts.actions.elasticsearch.ElasticsearchPlugin.java
private void transformTimestamp(String pattern, Object input) { if (input == null) { return;/*from ww w . j av a2 s . c o m*/ } if (input instanceof Map.Entry) { Map.Entry<String, Object> entry = (Map.Entry<String, Object>) input; if (entry.getValue() instanceof Map || entry.getValue() instanceof List) { transformTimestamp(pattern, entry.getValue()); } else { if (TIMESTAMP_FIELDS.contains(entry.getKey())) { try { Long timestamp = (Long) entry.getValue(); entry.setValue(DateTimeFormatter.ofPattern(pattern) .format(ZonedDateTime.ofInstant(Instant.ofEpochMilli(timestamp), UTC))); } catch (Exception e) { log.warnf("Cannot parse %s timestamp", entry.getKey()); } } } } else if (input instanceof Map) { Map<String, Object> map = (Map<String, Object>) input; map.entrySet().stream().forEach(e -> transformTimestamp(pattern, e)); } else if (input instanceof List) { List list = (List) input; list.stream().forEach(e -> transformTimestamp(pattern, e)); } }
From source file:io.stallion.utils.GeneralUtils.java
@Deprecated public static String slugifyDate(Long epochMillis) { return slugifyDate(ZonedDateTime.ofInstant(Instant.ofEpochMilli(epochMillis), UTC)); }
From source file:objective.taskboard.data.Issue.java
public Optional<Double> getCycleTime(ZoneId timezone) { return cycleTime.getCycleTime(Instant.ofEpochMilli(startDateStepMillis), timezone, status); }
From source file:org.sleuthkit.autopsy.timeline.ShowInTimelineDialog.java
/** * Construct this Dialog's "result" from the given event. * * @param selectedEvent The SingleEvent to include in the EventInTimeRange * * @return The EventInTimeRange that is the "result" of this dialog. *//* w w w. ja v a 2 s .c o m*/ private ViewInTimelineRequestedEvent makeEventInTimeRange(SingleEvent selectedEvent) { Duration selectedDuration = unitComboBox.getSelectionModel().getSelectedItem().getBaseUnit().getDuration() .multipliedBy(amountSpinner.getValue()); Interval range = IntervalUtils.getIntervalAround(Instant.ofEpochMilli(selectedEvent.getStartMillis()), selectedDuration); return new ViewInTimelineRequestedEvent(Collections.singleton(selectedEvent.getEventID()), range); }