List of usage examples for java.time ZoneOffset UTC
ZoneOffset UTC
To view the source code for java.time ZoneOffset UTC.
Click Source Link
From source file:com.match_tracker.twitter.TwitterSearch.java
protected long calculateSearchDelay(ZonedDateTime startTime) { long searchDelay = 0; ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC); ZonedDateTime offsetStartTime = startTime.plusSeconds(SEARCH_START_DELAY_SECONDS); if (now.isBefore(offsetStartTime)) { searchDelay = now.until(offsetStartTime, ChronoUnit.MILLIS); }//from ww w .ja v a 2s . c o m return searchDelay; }
From source file:org.openmhealth.shim.googlefit.GoogleFitShim.java
protected ResponseEntity<ShimDataResponse> getData(OAuth2RestOperations restTemplate, ShimDataRequest shimDataRequest) throws ShimException { final GoogleFitDataTypes googleFitDataType; try {/*from w ww.j a v a 2 s . c o m*/ googleFitDataType = GoogleFitDataTypes.valueOf(shimDataRequest.getDataTypeKey().trim().toUpperCase()); } catch (NullPointerException | IllegalArgumentException e) { throw new ShimException("Null or Invalid data type parameter: " + shimDataRequest.getDataTypeKey() + " in shimDataRequest, cannot retrieve data."); } OffsetDateTime todayInUTC = LocalDate.now().atStartOfDay().atOffset(ZoneOffset.UTC); OffsetDateTime startDateInUTC = shimDataRequest.getStartDateTime() == null ? todayInUTC.minusDays(1) : shimDataRequest.getStartDateTime(); long startTimeNanos = (startDateInUTC.toEpochSecond() * 1000000000) + startDateInUTC.toInstant().getNano(); OffsetDateTime endDateInUTC = shimDataRequest.getEndDateTime() == null ? todayInUTC.plusDays(1) : shimDataRequest.getEndDateTime().plusDays(1); // We are inclusive of the last day, so add 1 day to get // the end of day on the last day, which captures the // entire last day long endTimeNanos = (endDateInUTC.toEpochSecond() * 1000000000) + endDateInUTC.toInstant().getNano(); UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromUriString(DATA_URL) .pathSegment(googleFitDataType.getStreamId(), "datasets", "{startDate}-{endDate}"); // TODO: Add limits back into the request once Google has fixed the 'limit' query parameter and paging URI uriRequest = uriBuilder.buildAndExpand(startTimeNanos, endTimeNanos).encode().toUri(); ResponseEntity<JsonNode> responseEntity; try { responseEntity = restTemplate.getForEntity(uriRequest, JsonNode.class); } catch (HttpClientErrorException | HttpServerErrorException e) { // TODO figure out how to handle this logger.error("A request for Google Fit data failed.", e); throw e; } if (shimDataRequest.getNormalize()) { GoogleFitDataPointMapper<?> dataPointMapper; switch (googleFitDataType) { case BODY_WEIGHT: dataPointMapper = new GoogleFitBodyWeightDataPointMapper(); break; case BODY_HEIGHT: dataPointMapper = new GoogleFitBodyHeightDataPointMapper(); break; case ACTIVITY: dataPointMapper = new GoogleFitPhysicalActivityDataPointMapper(); break; case STEP_COUNT: dataPointMapper = new GoogleFitStepCountDataPointMapper(); break; case HEART_RATE: dataPointMapper = new GoogleFitHeartRateDataPointMapper(); break; case CALORIES_BURNED: dataPointMapper = new GoogleFitCaloriesBurnedDataPointMapper(); break; default: throw new UnsupportedOperationException(); } return ok().body(ShimDataResponse.result(GoogleFitShim.SHIM_KEY, dataPointMapper.asDataPoints(singletonList(responseEntity.getBody())))); } else { return ok().body(ShimDataResponse.result(GoogleFitShim.SHIM_KEY, responseEntity.getBody())); } }
From source file:org.openmhealth.shim.jawbone.mapper.JawboneDataPointMapper.java
/** * @param listEntryNode an individual entry node from the "items" array of a Jawbone endpoint response * @param unixEpochTimestamp unix epoch seconds timestamp from a time property in the list entry node * @return the appropriate {@link ZoneId} for the timestamp parameter based on the timezones contained within the * list entry node/* ww w .ja v a 2 s .c o m*/ */ static ZoneId getTimeZoneForTimestamp(JsonNode listEntryNode, Long unixEpochTimestamp) { Optional<JsonNode> optionalTimeZonesNode = asOptionalNode(listEntryNode, "details.tzs"); Optional<JsonNode> optionalTimeZoneNode = asOptionalNode(listEntryNode, "details.tz"); ZoneId zoneIdForTimestamp = ZoneOffset.UTC; // set default to Z in case problems with getting timezone if (optionalTimeZonesNode.isPresent() && optionalTimeZonesNode.get().size() > 0) { JsonNode timeZonesNode = optionalTimeZonesNode.get(); if (timeZonesNode.size() == 1) { zoneIdForTimestamp = parseZone(timeZonesNode.get(0).get(TIMEZONE_ENUM_INDEX_TZ)); } else { long currentLatestTimeZoneStart = 0; for (JsonNode timeZoneNodesEntry : timeZonesNode) { long timeZoneStartTime = timeZoneNodesEntry.get(TIMEZONE_ENUM_INDEX_START).asLong(); if (unixEpochTimestamp >= timeZoneStartTime) { if (timeZoneStartTime > currentLatestTimeZoneStart) { // we cannot guarantee the order of the // "tzs" array and we need to find the latest timezone that started before our time zoneIdForTimestamp = parseZone(timeZoneNodesEntry.get(TIMEZONE_ENUM_INDEX_TZ)); currentLatestTimeZoneStart = timeZoneStartTime; } } } } } else if (optionalTimeZoneNode.isPresent() && !optionalTimeZoneNode.get().isNull()) { zoneIdForTimestamp = parseZone(optionalTimeZoneNode.get()); } return zoneIdForTimestamp; }
From source file:com.jernejerin.traffic.helper.TripOperations.java
/** * Insert a trip into database.//from www . j ava 2 s .c o m * * @param trip trip to insert. * @param table table into which we need to insert trip */ public static void insertTrip(Trip trip, String table) { // LOGGER.log(Level.INFO, "Started inserting trip into DB for trip = " + // trip.toString() + " from thread = " + Thread.currentThread()); PreparedStatement insertTrip = null; Connection conn = null; try { // first we need to get connection from connection pool conn = DriverManager.getConnection("jdbc:apache:commons:dbcp:taxi"); // setting up prepared statement insertTrip = conn.prepareStatement("insert into " + table + " (eventId, medallion, hack_license, pickup_datetime, " + "dropoff_datetime, trip_time, trip_distance, pickup_longitude, pickup_latitude, dropoff_longitude, " + "dropoff_latitude, payment_type, fare_amount, surcharge, mta_tax, tip_amount, tolls_amount, " + "total_amount, timestampReceived) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); insertTrip.setInt(1, trip.getId()); insertTrip.setString(2, trip.getMedallion()); insertTrip.setString(3, trip.getHackLicense()); insertTrip.setTimestamp(4, new Timestamp(trip.getPickupDatetime().toEpochSecond(ZoneOffset.UTC) * 1000)); insertTrip.setTimestamp(5, new Timestamp(trip.getDropOffDatetime().toEpochSecond(ZoneOffset.UTC) * 1000)); insertTrip.setInt(6, trip.getTripTime()); insertTrip.setDouble(7, trip.getTripDistance()); insertTrip.setDouble(8, trip.getPickupLongitude()); insertTrip.setDouble(9, trip.getPickupLatitude()); insertTrip.setDouble(10, trip.getDropOffLongitude()); insertTrip.setDouble(11, trip.getDropOffLatitude()); insertTrip.setString(12, trip.getPaymentType() != null ? trip.getPaymentType().name() : null); insertTrip.setDouble(13, trip.getFareAmount()); insertTrip.setDouble(14, trip.getSurcharge()); insertTrip.setDouble(15, trip.getMtaTax()); insertTrip.setDouble(16, trip.getTipAmount()); insertTrip.setDouble(17, trip.getTollsAmount()); insertTrip.setDouble(18, trip.getTotalAmount()); insertTrip.setLong(19, trip.getTimestampReceived()); insertTrip.execute(); } catch (SQLException e) { LOGGER.log(Level.SEVERE, "Problem when inserting ticket into DB for ticket = " + trip + " from thread = " + Thread.currentThread()); } finally { try { if (insertTrip != null) insertTrip.close(); } catch (Exception e) { LOGGER.log(Level.SEVERE, "Problem with closing prepared statement for ticket = " + trip + " from thread = " + Thread.currentThread()); } try { if (conn != null) conn.close(); } catch (Exception e) { LOGGER.log(Level.SEVERE, "Problem with closing connection from thread = " + Thread.currentThread()); } // LOGGER.log(Level.INFO, "Finished inserting ticket into DB for for ticket = " + // trip + " from thread = " + Thread.currentThread()); } }
From source file:net.sf.gazpachoquest.velocity.loader.LocalizedTemplateResourceLoaderImpl.java
private long readLastModified(final Resource resource, final String operation) { String templateName = resource.getName(); Integer templateId = readTemplateId(templateName); logger.info("{} from mail message template {} ", operation, templateId); MailMessageTemplate template = templateRepository.findOne(templateId); return template.getLastModifiedDate().toEpochSecond(ZoneOffset.UTC); }
From source file:io.pivotal.demo.smartgrid.frontend.timeseries.AggregateCounterTimeSeriesRepository.java
private TimeSeriesCollection convertToTimeSeriesCollection(AggregateCounterCollection acc) { TimeSeriesCollection tsc = new TimeSeriesCollection(acc.getName()); for (Map.Entry<String, AggregateCounter> entry : acc.getAggregateCounters().entrySet()) { String timeSeriesName = entry.getKey(); AggregateCounter aggregateCounter = entry.getValue(); List<String> timeAxis = new ArrayList<>(); List<String> valueAxis = new ArrayList<>(); for (Map.Entry<String, String> dataPoint : aggregateCounter.getCounts().entrySet()) { String pit = dataPoint.getKey(); String value = dataPoint.getValue(); LocalDateTime ldt = LocalDateTime.parse(pit, DateTimeFormatter.ISO_DATE_TIME); timeAxis.add("" + ldt.toEpochSecond(ZoneOffset.UTC)); valueAxis.add(value);//w ww . j ava2 s . c o m } tsc.registerTimeSeries(timeSeriesName, timeAxis, valueAxis); } return tsc; }
From source file:org.openmrs.module.operationtheater.api.impl.OperationTheaterServiceImpl.java
@Override public Interval getLocationAvailableTime(Location location, LocalDate date) { Date date1 = Date.from(date.atStartOfDay(ZoneId.systemDefault()).toInstant()); Date date2 = Date.from(date.plusDays(1).atStartOfDay(ZoneId.systemDefault()).toInstant()); List<AppointmentBlock> blocks = appointmentService.getAppointmentBlocks(date1, date2, location.getId() + ",", null, null); // List<AppointmentBlock> blocks = new ArrayList<AppointmentBlock>(); if (blocks.size() == 1) { // return new Interval(new DateTime(blocks.get(0).getStartDate()), new DateTime(blocks.get(0).getEndDate())); Instant startInstant = LocalDateTime.from(blocks.get(0).getStartDate().toInstant()) .toInstant(ZoneOffset.UTC); Instant endInstant = LocalDateTime.from(blocks.get(0).getEndDate().toInstant()) .toInstant(ZoneOffset.UTC); return Interval.of(startInstant, endInstant); } else if (blocks.size() > 1) { throw new APIException("There shouldn't be multiple appointment blocks per location and date"); }/*from w w w . java2s .co m*/ DateTimeFormatter timeFormatter = OTMetadata.AVAILABLE_TIME_FORMATTER; LocalDateTime availableStart = null; LocalDateTime availableEnd = null; for (LocationAttribute attribute : location.getAttributes()) { if (attribute.getAttributeType().getUuid().equals(OTMetadata.DEFAULT_AVAILABLE_TIME_BEGIN_UUID)) { LocalTime beginTime = LocalTime.parse((String) attribute.getValue(), timeFormatter); // availableStart = date.withTime(beginTime.getHourOfDay(), beginTime.getMinuteOfHour(), 0, 0); availableStart = date.atTime(beginTime.getHour(), beginTime.getMinute()); } else if (attribute.getAttributeType().getUuid().equals(OTMetadata.DEFAULT_AVAILABLE_TIME_END_UUID)) { LocalTime endTime = LocalTime.parse((String) attribute.getValue(), timeFormatter); // availableEnd = date.withTime(endTime.getHourOfDay(), endTime.getMinuteOfHour(), 0, 0); availableEnd = date.atTime(endTime.getHour(), endTime.getMinute()); } } if (availableStart != null && availableEnd != null) { return Interval.of(availableStart.toInstant(ZoneOffset.UTC), availableEnd.toInstant(ZoneOffset.UTC)); } throw new APIException("Available times not defined. please make sure that the attributes " + "'default available time begin' and 'default available time end' for the location " + location.getName() + " are defined"); }
From source file:org.xlrnet.metadict.engines.leo.LeoEngine.java
private Connection buildTargetConnection(String searchString, Language inputLanguage, Language outputLanguage) { String targetDictionary = resolveDictionaryConfig(inputLanguage, outputLanguage); if (targetDictionary == null) { targetDictionary = resolveDictionaryConfig(outputLanguage, inputLanguage); if (targetDictionary == null) throw new IllegalArgumentException( "No suitable dictionary configuration found - this might be an internal metadict error"); }//from w w w . j a v a 2 s . c om return Jsoup.connect("https://dict.leo.org/dictQuery/m-vocab/" + targetDictionary + "/query.xml").userAgent( "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36") .data(DEFAULT_QUERY_DATA).data("lp", targetDictionary).data("search", searchString) .data("t", ZonedDateTime.now(ZoneOffset.UTC).toString()); }
From source file:org.cryptomator.frontend.webdav.servlet.DavNode.java
private Optional<DavProperty<?>> creationDateProperty(DavPropertyName name) { return attr.map(BasicFileAttributes::creationTime) // .map(FileTime::toInstant) // .map(creationTime -> OffsetDateTime.ofInstant(creationTime, ZoneOffset.UTC)) // .map(creationDate -> new DefaultDavProperty<>(name, DateTimeFormatter.RFC_1123_DATE_TIME.format(creationDate))); }
From source file:com.netflix.spinnaker.front50.model.SwiftStorageService.java
@Override public long getLastModified(ObjectType objectType) { List<? extends SwiftObject> objects = getSwift().objects().list(containerName, ObjectListOptions.create().path(objectType.group)); ZonedDateTime lastModified = Instant.now().atZone(ZoneOffset.UTC); for (SwiftObject o : objects) { ZonedDateTime timestamp = ZonedDateTime.parse( getSwift().objects().getMetadata(containerName, o.getName()).get("Last-Modified"), DateTimeFormatter.RFC_1123_DATE_TIME); if (timestamp.isBefore(lastModified)) { lastModified = timestamp;//from w ww .j a v a 2s . c o m } } return lastModified.toEpochSecond(); }