List of usage examples for java.time ZonedDateTime ofInstant
public static ZonedDateTime ofInstant(Instant instant, ZoneId zone)
From source file:org.hawkular.alerts.actions.elasticsearch.ElasticsearchPlugin.java
private void transformTimestamp(String pattern, Object input) { if (input == null) { return;/*w w w . java 2 s . com*/ } 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:com.example.app.support.service.AppUtil.java
/** * Convert the given Date from UTC to a ZonedDateTime at the given TimeZone * * @param date the UTC date//from w w w.ja v a 2 s .c o m * @param zone the TimeZone to convert the time to * * @return a ZonedDateTime that represents the same instant as the UTC date, but at the given TimeZone. */ @Nullable @Contract(value = "null,_->null;_,null->null;!null,!null->!null", pure = true) public static ZonedDateTime convertFromPersisted(@Nullable Date date, @Nullable TimeZone zone) { if (date == null || zone == null) return null; ZonedDateTime from = ZonedDateTime.ofInstant(date.toInstant(), ZoneOffset.UTC); return from.withZoneSameInstant(zone.toZoneId()); }
From source file:org.wso2.carbon.uuf.internal.io.StaticResolver.java
private ZonedDateTime getLastModifiedDate(Path resourcePath) { if (!Files.isReadable(resourcePath)) { throw new ResourceNotFoundException("Static resource file '" + resourcePath + "' is not readable."); }//from w ww .j a va2s. com BasicFileAttributes fileAttributes; try { fileAttributes = Files.readAttributes(resourcePath, BasicFileAttributes.class); } catch (NoSuchFileException | FileNotFoundException e) { // This shouldn't be happening because we checked the file's readability before. But just in case. throw new ResourceNotFoundException("Static resource file '" + resourcePath + "' does not exists.", e); } catch (Exception e) { // UnsupportedOperationException, IOException or any other Exception that might occur. throw new FileOperationException( "Cannot read file attributes from static resource file '" + resourcePath + "'.", e); } if (fileAttributes.isRegularFile()) { return ZonedDateTime.ofInstant(fileAttributes.lastModifiedTime().toInstant(), GMT_TIME_ZONE); } else { /* * From book "OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide" page 478: * Java defines a regular file as one that contains content, as opposed to a symbolic link, * directory, resource (e.g. port, pipe), or other non-regular files that may be present in some * operating systems. [...] It is possible for isRegularFile() to return true for a symbolic link, * as long as the link resolves to a regular file. * Hence, checking 'isRegularFile' of a file is enough to determine its existence and not being a directory. */ throw new ResourceNotFoundException( "Static resource file '" + resourcePath + "' is not a regular file."); } }
From source file:org.eclipse.smarthome.ui.internal.chart.defaultchartprovider.DefaultChartProvider.java
boolean addItem(Chart chart, QueryablePersistenceService service, Date timeBegin, Date timeEnd, Item item, int seriesCounter, ChartTheme chartTheme, int dpi) { Color color = chartTheme.getLineColor(seriesCounter); // Get the item label String label = null;// w w w . j av a 2s . c om if (itemUIRegistry != null) { // Get the item label label = itemUIRegistry.getLabel(item.getName()); if (label != null && label.contains("[") && label.contains("]")) { label = label.substring(0, label.indexOf('[')); } } if (label == null) { label = item.getName(); } Iterable<HistoricItem> result; FilterCriteria filter; // Generate data collections List<Date> xData = new ArrayList<Date>(); List<Number> yData = new ArrayList<Number>(); // Declare state here so it will hold the last value at the end of the process State state = null; // First, get the value at the start time. // This is necessary for values that don't change often otherwise data will start // after the start of the graph (or not at all if there's no change during the graph period) filter = new FilterCriteria(); filter.setEndDate(ZonedDateTime.ofInstant(timeBegin.toInstant(), timeZoneProvider.getTimeZone())); filter.setItemName(item.getName()); filter.setPageSize(1); filter.setOrdering(Ordering.DESCENDING); result = service.query(filter); if (result.iterator().hasNext()) { HistoricItem historicItem = result.iterator().next(); state = historicItem.getState(); xData.add(timeBegin); yData.add(convertData(state)); } // Now, get all the data between the start and end time filter.setBeginDate(ZonedDateTime.ofInstant(timeBegin.toInstant(), timeZoneProvider.getTimeZone())); filter.setEndDate(ZonedDateTime.ofInstant(timeEnd.toInstant(), timeZoneProvider.getTimeZone())); filter.setPageSize(Integer.MAX_VALUE); filter.setOrdering(Ordering.ASCENDING); // Get the data from the persistence store result = service.query(filter); Iterator<HistoricItem> it = result.iterator(); // Iterate through the data while (it.hasNext()) { HistoricItem historicItem = it.next(); // For 'binary' states, we need to replicate the data // to avoid diagonal lines if (state instanceof OnOffType || state instanceof OpenClosedType) { Calendar cal = Calendar.getInstance(); cal.setTime(historicItem.getTimestamp()); cal.add(Calendar.MILLISECOND, -1); xData.add(cal.getTime()); yData.add(convertData(state)); } state = historicItem.getState(); xData.add(historicItem.getTimestamp()); yData.add(convertData(state)); } // Lastly, add the final state at the endtime if (state != null) { xData.add(timeEnd); yData.add(convertData(state)); } // Add the new series to the chart - only if there's data elements to display // The chart engine will throw an exception if there's no data if (xData.size() == 0) { return false; } // If there's only 1 data point, plot it again! if (xData.size() == 1) { xData.add(xData.iterator().next()); yData.add(yData.iterator().next()); } Series series = chart.addSeries(label, xData, yData); float lineWidth = (float) chartTheme.getLineWidth(dpi); series.setLineStyle(new BasicStroke(lineWidth, BasicStroke.CAP_ROUND, BasicStroke.JOIN_MITER)); series.setMarker(SeriesMarker.NONE); series.setLineColor(color); // If the start value is below the median, then count legend position down // Otherwise count up. // We use this to decide whether to put the legend in the top or bottom corner. if (yData.iterator().next().floatValue() > ((series.getYMax() - series.getYMin()) / 2 + series.getYMin())) { legendPosition++; } else { legendPosition--; } return true; }
From source file:alfio.util.TemplateResource.java
public static Map<String, Object> prepareModelForConfirmationEmail(Organization organization, Event event, TicketReservation reservation, Optional<String> vat, List<Ticket> tickets, OrderSummary orderSummary, String reservationUrl, String reservationShortID, Optional<String> invoiceAddress, Optional<String> bankAccountNr, Optional<String> bankAccountOwner) { Map<String, Object> model = new HashMap<>(); model.put("organization", organization); model.put("event", event); model.put("ticketReservation", reservation); model.put("hasVat", vat.isPresent()); model.put("vatNr", vat.orElse("")); model.put("tickets", tickets); model.put("orderSummary", orderSummary); model.put("reservationUrl", reservationUrl); model.put("locale", reservation.getUserLanguage()); ZonedDateTime confirmationTimestamp = Optional.ofNullable(reservation.getConfirmationTimestamp()) .orElseGet(ZonedDateTime::now); model.put("confirmationDate", confirmationTimestamp.withZoneSameInstant(event.getZoneId())); if (reservation.getValidity() != null) { model.put("expirationDate", ZonedDateTime.ofInstant(reservation.getValidity().toInstant(), event.getZoneId())); }/*from www . j a v a2 s . c o m*/ model.put("reservationShortID", reservationShortID); model.put("hasInvoiceAddress", invoiceAddress.isPresent()); invoiceAddress.ifPresent(addr -> { model.put("invoiceAddress", StringUtils.replace(addr, "\n", ", ")); model.put("invoiceAddressAsList", Arrays.asList(StringUtils.split(addr, '\n'))); }); model.put("hasBankAccountNr", bankAccountNr.isPresent()); bankAccountNr.ifPresent(nr -> { model.put("bankAccountNr", nr); }); model.put("isOfflinePayment", reservation.getStatus() == TicketReservation.TicketReservationStatus.OFFLINE_PAYMENT); model.put("paymentReason", event.getShortName() + " " + reservationShortID); model.put("hasBankAccountOnwer", bankAccountOwner.isPresent()); bankAccountOwner.ifPresent(owner -> { model.put("bankAccountOnwer", StringUtils.replace(owner, "\n", ", ")); model.put("bankAccountOnwerAsList", Arrays.asList(StringUtils.split(owner, '\n'))); }); return model; }
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 w w w .j a va 2s .c o 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./* w ww . j a v a2 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:com.esri.geoportal.harvester.agp.AgpOutputBroker.java
private String fromatDate(Date date) { ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault()); return FORMATTER.format(zonedDateTime); }