List of usage examples for org.apache.commons.lang3.time DateUtils addSeconds
public static Date addSeconds(final Date date, final int amount)
From source file:eionet.webq.task.RemoveExpiredUserFilesTaskIntegrationTest.java
private void setFileAsExpired() { Date expired = DateUtils.addSeconds(DateUtils.addHours(new Date(), -task.getExpirationHours()), -1); factory.getCurrentSession().createQuery("UPDATE UserFile SET updated=:updated") .setTimestamp("updated", new Timestamp(expired.getTime())).executeUpdate(); }
From source file:io.cloudex.cloud.impl.google.auth.InstanceAuthenticationProvider.java
/** * Retrieves a service account access token from the metadata server, the response has the format * {/*from w ww . j a v a 2s . com*/ "access_token":"ya29.AHES6ZRN3-HlhAPya30GnW_bHSb_QtAS08i85nHq39HE3C2LTrCARA", "expires_in":3599, "token_type":"Bearer" } * @throws IOException * For more details see https://developers.google.com/compute/docs/authentication */ protected void refreshOAuthToken() throws IOException { log.debug("Refreshing OAuth token from metadata server"); Map<String, Object> token = ObjectUtils.jsonToMap(GoogleMetaData.getMetaData(TOKEN_PATH)); this.accessToken = (String) token.get(ACCESS_TOKEN); Double expiresIn = (Double) token.get(EXPIRES_IN); this.tokenExpire = DateUtils.addSeconds(new Date(), expiresIn.intValue()); log.debug("Successfully refreshed OAuth token from metadata server"); }
From source file:com.stratelia.webactiv.util.DateUtilTest.java
@Test public void testGetOutputDateAndHour() { Date date = DateUtil.resetHour(java.sql.Date.valueOf("2013-05-21")); assertThat(DateUtil.getOutputDateAndHour(date, LANGUAGE), is("2013/05/21")); Date year = DateUtils.addYears(date, 1); assertThat(DateUtil.getOutputDateAndHour(year, LANGUAGE), is("2014/05/21")); Date month = DateUtils.addMonths(date, 1); assertThat(DateUtil.getOutputDateAndHour(month, LANGUAGE), is("2013/06/21")); Date day = DateUtils.addDays(date, 1); assertThat(DateUtil.getOutputDateAndHour(day, LANGUAGE), is("2013/05/22")); Date hour = DateUtils.addHours(date, 1); assertThat(DateUtil.getOutputDateAndHour(hour, LANGUAGE), is("2013/05/21 01:00")); hour = DateUtils.addHours(date, 12); assertThat(DateUtil.getOutputDateAndHour(hour, LANGUAGE), is("2013/05/21 12:00")); hour = DateUtils.addHours(date, 22); assertThat(DateUtil.getOutputDateAndHour(hour, LANGUAGE), is("2013/05/21 22:00")); Date minute = DateUtils.addMinutes(date, 1); assertThat(DateUtil.getOutputDateAndHour(minute, LANGUAGE), is("2013/05/21 00:01")); minute = DateUtils.addMinutes(date, 59); assertThat(DateUtil.getOutputDateAndHour(minute, LANGUAGE), is("2013/05/21 00:59")); minute = DateUtils.addMinutes(date, 60); assertThat(DateUtil.getOutputDateAndHour(minute, LANGUAGE), is("2013/05/21 01:00")); minute = DateUtils.addMinutes(date, 61); assertThat(DateUtil.getOutputDateAndHour(minute, LANGUAGE), is("2013/05/21 01:01")); Date second = DateUtils.addSeconds(date, 1); assertThat(DateUtil.getOutputDateAndHour(second, LANGUAGE), is("2013/05/21 00:00")); second = DateUtils.addSeconds(date, 59); assertThat(DateUtil.getOutputDateAndHour(second, LANGUAGE), is("2013/05/21 00:00")); second = DateUtils.addSeconds(date, 60); assertThat(DateUtil.getOutputDateAndHour(second, LANGUAGE), is("2013/05/21 00:01")); second = DateUtils.addSeconds(date, 61); assertThat(DateUtil.getOutputDateAndHour(second, LANGUAGE), is("2013/05/21 00:01")); Date millisecond = DateUtils.addMilliseconds(date, 1); assertThat(DateUtil.getOutputDateAndHour(millisecond, LANGUAGE), is("2013/05/21 00:00")); millisecond = DateUtils.addMilliseconds(date, 999); assertThat(DateUtil.getOutputDateAndHour(millisecond, LANGUAGE), is("2013/05/21 00:00")); millisecond = DateUtils.addMilliseconds(date, 1000); assertThat(DateUtil.getOutputDateAndHour(millisecond, LANGUAGE), is("2013/05/21 00:00")); millisecond = DateUtils.addMilliseconds(date, 1001); assertThat(DateUtil.getOutputDateAndHour(millisecond, LANGUAGE), is("2013/05/21 00:00")); // 2013-05-21 23:59:59.999 date = DateUtils.addHours(/*from w ww.j a v a2s. com*/ DateUtils.addMinutes(DateUtils.addSeconds(DateUtils.addMilliseconds(date, 999), 59), 59), 23); assertThat(DateUtil.getOutputDateAndHour(date, LANGUAGE), is("2013/05/21 23:59")); // 2013-05-22 00:00:00.000 date = DateUtils.addMilliseconds(date, 1); assertThat(DateUtil.getOutputDateAndHour(date, LANGUAGE), is("2013/05/22")); // 2013-05-22 00:00:00.001 date = DateUtils.addMilliseconds(date, 1); assertThat(DateUtil.getOutputDateAndHour(date, LANGUAGE), is("2013/05/22 00:00")); }
From source file:com.francetelecom.clara.cloud.coremodel.EnvironmentRepositoryPurgeTest.java
@Test @Transactional// w ww. j ava2 s. co m public void should_find_older_removed_environments() { // GIVEN int fiveDay = 5; Date jMinusFourDayAndTwentyThreeHours = DateHelper.getDateDeltaDay(-4); jMinusFourDayAndTwentyThreeHours = DateUtils.addHours(jMinusFourDayAndTwentyThreeHours, -23); Date jMinusFiveDayAndOneSecond = DateHelper.getDateDeltaDay(-5); jMinusFiveDayAndOneSecond = DateUtils.addSeconds(jMinusFiveDayAndOneSecond, -1); Date jMinusHeight = DateHelper.getDateDeltaDay(-8); // default environment Environment environment = new Environment(DeploymentProfileEnum.PRODUCTION, "default", release, bob, technicalDeploymentInstance); environmentRepository.save(environment); LOG.info("test env {}", environment); // default old environment DateHelper.setNowDate(jMinusFiveDayAndOneSecond); Environment environmentOld = new Environment(DeploymentProfileEnum.PRODUCTION, "old", release, bob, technicalDeploymentInstance); Assume.assumeTrue(environmentOld.getCreationDate().equals(jMinusFiveDayAndOneSecond)); DateHelper.resetNow(); environmentRepository.save(environmentOld); LOG.info("test env {}", environmentOld); // given default removed environment DateHelper.setNowDate(jMinusFourDayAndTwentyThreeHours); Environment removed = new Environment(DeploymentProfileEnum.PRODUCTION, "defaultRemoved", release, bob, technicalDeploymentInstance); removed.setStatus(EnvironmentStatus.REMOVED); DateHelper.resetNow(); environmentRepository.save(removed); LOG.info("test env {}", removed); // given older removed environment A (j-6) DateHelper.setNowDate(jMinusFiveDayAndOneSecond); Environment oldRemovedA = new Environment(DeploymentProfileEnum.PRODUCTION, "oldRemovedA", release, bob, technicalDeploymentInstance); oldRemovedA.setStatus(EnvironmentStatus.REMOVED); DateHelper.resetNow(); Assume.assumeTrue(oldRemovedA.getDeletionDate().equals(jMinusFiveDayAndOneSecond)); environmentRepository.save(oldRemovedA); LOG.info("test env {}", oldRemovedA); // given older removed environment B (j-8) DateHelper.setNowDate(jMinusHeight); Environment oldRemovedB = new Environment(DeploymentProfileEnum.PRODUCTION, "oldRemovedB", release, bob, technicalDeploymentInstance); oldRemovedB.setStatus(EnvironmentStatus.REMOVED); DateHelper.resetNow(); Assume.assumeTrue(oldRemovedB.getDeletionDate().equals(jMinusHeight)); environmentRepository.save(oldRemovedB); LOG.info("test env {}", oldRemovedA); // WHEN List<Environment> results = environmentRepository .findRemovedOlderThanNDays(DateHelper.getDateDeltaDay(-fiveDay)); // THEN assertThat(results).containsExactly(oldRemovedA, oldRemovedB); }
From source file:ee.ria.xroad.asyncdb.messagequeue.QueueInfo.java
/** * Returns time when next request will be sent. * * @return - time in the future when next request will be sent. *///from w w w . j a v a 2 s. c o m public Date getNextAttempt() { if (requestCount == 0) { return null; } if (lastSentTime == null) { return new Date(); } AsyncSenderConf conf = new AsyncSenderConf(); int maxDelay = conf.getMaxDelay(); int delayInSeconds; // Number small enough to prevent integer overflow and large enough // to enable delays always larger than largest realistic base delay. if (firstRequestSendCount == 0) { delayInSeconds = 0; } else if (firstRequestSendCount <= NEXT_ATTEMPT_POWER_LIMIT) { int rawDelay = (int) Math.pow(2, firstRequestSendCount - 1) * conf.getBaseDelay(); delayInSeconds = rawDelay > maxDelay ? maxDelay : rawDelay; } else { delayInSeconds = maxDelay; } return DateUtils.addSeconds(lastSentTime, delayInSeconds); }
From source file:com.pinterest.rocksplicator.controller.mysql.MySQLTaskQueue.java
private TaskEntity enqueueTaskImpl(final TaskBase taskBase, final Cluster cluster, final int runDelaySeconds, final TaskState state, final String claimedWorker) { TagEntity tagEntity = getEntityManager().find(TagEntity.class, new TagId(cluster), LockModeType.PESSIMISTIC_WRITE); if (tagEntity == null) { LOG.error("Cluster {} is not created", cluster); getEntityManager().getTransaction().rollback(); return null; }/* w w w. j av a2 s . c om*/ TaskEntity entity = new TaskEntity().setName(taskBase.name).setPriority(taskBase.priority) .setBody(taskBase.body).setCluster(tagEntity).setLastAliveAt(new Date()) .setClaimedWorker(claimedWorker).setState(state.intValue()) .setRunAfter(DateUtils.addSeconds(new Date(), runDelaySeconds)); getEntityManager().persist(entity); getEntityManager().flush(); return entity; }
From source file:com.francetelecom.clara.cloud.coremodel.EnvironmentRepositoryPurgeTest.java
@Test @Transactional/*from w ww . j av a 2 s . c o m*/ public void retention_delay_should_prevent_to_find_older_environments_recently_removed() { // GIVEN int retentionDelayIsFiveDay = 5; Date jMinusFiveDayAndOneSecond = DateHelper.getDateDeltaDay(-5); jMinusFiveDayAndOneSecond = DateUtils.addSeconds(jMinusFiveDayAndOneSecond, -1); // oldEnv but recently removed DateHelper.setNowDate(jMinusFiveDayAndOneSecond); Environment oldEnv = new Environment(DeploymentProfileEnum.PRODUCTION, "default", release, bob, technicalDeploymentInstance); Assume.assumeTrue(oldEnv.getCreationDate().equals(jMinusFiveDayAndOneSecond)); DateHelper.resetNow(); Date removedDate = new Date(); DateHelper.setNowDate(removedDate); oldEnv.setStatus(EnvironmentStatus.REMOVED); DateHelper.resetNow(); Assume.assumeTrue(oldEnv.getDeletionDate().equals(removedDate)); environmentRepository.save(oldEnv); LOG.info("test env {}", oldEnv); // WHEN List<Environment> results = environmentRepository .findRemovedOlderThanNDays(DateHelper.getDateDeltaDay(-retentionDelayIsFiveDay)); // THEN assertThat(results).isEmpty(); }
From source file:alfio.controller.api.admin.CheckInApiController.java
@RequestMapping(value = "/check-in/{eventName}/offline-identifiers", method = GET) public List<Integer> getOfflineIdentifiers(@PathVariable("eventName") String eventName, @RequestParam(value = "changedSince", required = false) Long changedSince, HttpServletResponse resp, Principal principal) {//ww w .j a v a 2 s.c om Date since = changedSince == null ? new Date(0) : DateUtils.addSeconds(new Date(changedSince), -1); Optional<List<Integer>> ids = optionally(() -> eventManager.getSingleEvent(eventName, principal.getName())) .filter(checkInManager.isOfflineCheckInEnabled()) .map(event -> checkInManager.getAttendeesIdentifiers(event, since, principal.getName())); resp.setHeader(ALFIO_TIMESTAMP_HEADER, ids.isPresent() ? Long.toString(new Date().getTime()) : "0"); return ids.orElse(Collections.emptyList()); }
From source file:io.wcm.wcm.commons.caching.CacheHeader.java
/** * Set expires header to given amount of seconds in the future. * @param response Response/*from www .jav a 2s. c om*/ * @param seconds Seconds to expire */ public static void setExpiresSeconds(HttpServletResponse response, int seconds) { Date expiresDate = DateUtils.addSeconds(new Date(), seconds); setExpires(response, expiresDate); }
From source file:com.opentransport.rdfmapper.nmbs.ScrapeTrip.java
private GtfsRealtime.FeedEntity.Builder parseJson(int identifier, String fileName, boolean canceled, String trainName) {//from ww w . ja va 2 s . c o m GtfsRealtime.FeedEntity.Builder feedEntity = GtfsRealtime.FeedEntity.newBuilder(); feedEntity.setId(Integer.toString(identifier)); feedEntity.setIsDeleted(false); //Data that doesnt Update GtfsRealtime.TripUpdate.Builder tripUpdate = GtfsRealtime.TripUpdate.newBuilder(); GtfsRealtime.VehicleDescriptor.Builder vehicleDescription = GtfsRealtime.VehicleDescriptor.newBuilder(); GtfsRealtime.TripDescriptor.Builder tripDescription = GtfsRealtime.TripDescriptor.newBuilder(); GtfsRealtime.TripUpdate.StopTimeUpdate.Builder stopTimeUpdate = GtfsRealtime.TripUpdate.StopTimeUpdate .newBuilder(); //Each StopTime Update contains StopTimeEvents with the stop Arrival and Departure Time GtfsRealtime.TripUpdate.StopTimeEvent.Builder stopTimeArrival = GtfsRealtime.TripUpdate.StopTimeEvent .newBuilder(); GtfsRealtime.TripUpdate.StopTimeEvent.Builder stopTimeDeparture = GtfsRealtime.TripUpdate.StopTimeEvent .newBuilder(); JSONParser parser = new JSONParser(); try { FileReader fr = new FileReader(fileName); JSONObject json = (JSONObject) parser.parse(fr); String trainId = (String) json.get("vehicle"); //Setting the VehicleData String routeId = trainName; vehicleDescription.setId(routeId); vehicleDescription.setLicensePlate(trainId); //Handling Departure Date String unixSeconds = (String) json.get("timestamp"); Long unixSec = Long.parseLong(unixSeconds); Date date = new Date(unixSec * 1000L); // *1000 is to convert seconds to milliseconds SimpleDateFormat sdfStartDate = new SimpleDateFormat("yyyyMMdd"); // the format of your date sdfStartDate.setTimeZone(TimeZone.getTimeZone("GMT+2")); // give a timezone reference for formating SimpleDateFormat sdfStartTimeHour = new SimpleDateFormat("HH:mm:ss"); String formattedDepartureDate = sdfStartDate.format(date); // String formattedDepartureHour = sdfStartTimeHour.format(date); // Setting the Trip Description // tripDescription.setStartTime(formattedDepartureHour); //YYYYMMDD format tripDescription.setStartDate(formattedDepartureDate); tripDescription.setRouteId(routeId); String tripId = tr.getTripIdFromRouteId(routeId, cdr); tripDescription.setTripId(tripId); //Get Information about stops JSONObject rootStop = (JSONObject) json.get("stops"); JSONArray stops = (JSONArray) rootStop.get("stop"); String arrivalDelay = "0"; String departureDelay = "0"; int maxDelay = 0; String firstStopName = ""; String lastStopName = ""; boolean wholeTripCanceled = true; // True when all stoptimes since now are canceled for (int i = 0; i < stops.size(); i++) { //Information about the stops JSONObject stop = (JSONObject) stops.get(i); // String stopSeq = (String) stop.get("id"); stopTimeUpdate.setStopSequence(i); try { JSONObject station = (JSONObject) stop.get("stationinfo"); // tripDescription.setRouteId((String) station.get("@id")); String stopId = (String) station.get("id"); stopId = stopId.replaceFirst("[^0-9]+", "") + ":"; stopId = stopId.substring(2); // remove first '00' if (!stop.get("platform").equals("") && !stop.get("platform").equals("?")) { stopId += stop.get("platform"); } else { stopId += "0"; } stopTimeUpdate.setStopId(stopId); // Constructing route long name from first and last stop if (i == 0) { firstStopName = (String) station.get("standardname"); } else if (i == stops.size() - 1) { lastStopName = (String) station.get("standardname"); } } catch (Exception e) { errorWriter.writeError(e.toString() + fileName); System.out.println(fileName); System.out.println(e); } // delays arrivalDelay = (String) stop.get("arrivalDelay"); departureDelay = (String) stop.get("departureDelay"); int arrivalDelayInt = Integer.parseInt(arrivalDelay); int departureDelayInt = Integer.parseInt(departureDelay); if (maxDelay < arrivalDelayInt) { maxDelay = arrivalDelayInt; } if (maxDelay < departureDelayInt) { maxDelay = departureDelayInt; } long now = System.currentTimeMillis(); //Calculate arrival times long scheduledArrivalTimeUnixSeconds = Long.parseLong((String) stop.get("scheduledArrivalTime")); java.util.Date scheduledArrivalTime = new java.util.Date( (long) scheduledArrivalTimeUnixSeconds * 1000); // add arrivalDelay to get real arrival time long arrivalTimeMillis = (DateUtils.addSeconds(scheduledArrivalTime, arrivalDelayInt)).getTime(); //Calculate departure times long scheduledDepartureTimeUnixSeconds = Long .parseLong((String) stop.get("scheduledDepartureTime")); java.util.Date scheduledDepartureTime = new java.util.Date( (long) scheduledDepartureTimeUnixSeconds * 1000); // add departureDelay to get real departure time long departureTimeMillis = (DateUtils.addSeconds(scheduledDepartureTime, departureDelayInt)) .getTime(); // If stoptime is (partially) canceled String isCanceled = (String) stop.get("canceled"); if (!isCanceled.equals("0")) { // Set ScheduleRelationship of stoptime to SKIPPED stopTimeUpdate.setScheduleRelationship( GtfsRealtime.TripUpdate.StopTimeUpdate.ScheduleRelationship.SKIPPED); } else { // If a current or future stoptime isn't canceled, the whole trip isn't canceled if (wholeTripCanceled && arrivalTimeMillis >= now) { wholeTripCanceled = false; } } // Set Arrival in the object stopTimeArrival.setDelay(arrivalDelayInt); // setTime takes parameter in seconds stopTimeArrival.setTime(arrivalTimeMillis / 1000); stopTimeUpdate.setArrival(stopTimeArrival); // Do the same for departure stopTimeDeparture.setDelay(Integer.parseInt(departureDelay)); // setTime takes parameter in seconds stopTimeDeparture.setTime(departureTimeMillis / 1000); stopTimeUpdate.setDeparture(stopTimeDeparture); tripUpdate.addStopTimeUpdate(stopTimeUpdate); } tripDescription.setScheduleRelationship(GtfsRealtime.TripDescriptor.ScheduleRelationship.SCHEDULED); if (wholeTripCanceled) { // Can be partially canceled tripDescription.setScheduleRelationship(GtfsRealtime.TripDescriptor.ScheduleRelationship.CANCELED); } String route_long_name = firstStopName + " - " + lastStopName; vehicleDescription.setLabel(route_long_name); tripUpdate.setTrip(tripDescription); tripUpdate.setVehicle(vehicleDescription); tripUpdate.setDelay(maxDelay); feedEntity.setTripUpdate(tripUpdate); fr.close(); } catch (FileNotFoundException ex) { System.out.println(ex); errorWriter.writeError(ex.toString()); } catch (IOException ex) { System.out.println("IO exception" + ex); } catch (ParseException ex) { System.out.println("Parse exception " + ex + " " + fileName); } catch (NullPointerException npe) { System.out.println(npe.toString()); } return feedEntity; }