Java Code Examples for org.joda.time.DateTime#plus()
The following examples show how to use
org.joda.time.DateTime#plus() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SignatureVerificationResult.java From freehealth-connector with GNU Affero General Public License v3.0 | 6 votes |
public DateTime getVerifiedSigningTime(int amount, TimeUnit unit) { Iterator i$ = this.timestampGenTime.iterator(); DateTime start; DateTime end; do { if (!i$.hasNext()) { return new DateTime(); } DateTime genTime = (DateTime)i$.next(); start = genTime.minus(unit.toMillis((long)amount)); end = genTime.plus(unit.toMillis((long)amount)); } while(this.signingTime.isBefore(start) || this.signingTime.isAfter(end)); return this.signingTime; }
Example 2
Source File: SignatureVerificationResult.java From freehealth-connector with GNU Affero General Public License v3.0 | 6 votes |
public DateTime getVerifiedSigningTime(int amount, TimeUnit unit) { Iterator i$ = this.timestampGenTime.iterator(); DateTime start; DateTime end; do { if (!i$.hasNext()) { return new DateTime(); } DateTime genTime = (DateTime)i$.next(); start = genTime.minus(unit.toMillis((long)amount)); end = genTime.plus(unit.toMillis((long)amount)); } while(this.signingTime.isBefore(start) || this.signingTime.isAfter(end)); return this.signingTime; }
Example 3
Source File: SignatureVerificationResult.java From freehealth-connector with GNU Affero General Public License v3.0 | 6 votes |
public DateTime getVerifiedSigningTime(int amount, TimeUnit unit) { Iterator i$ = this.timestampGenTime.iterator(); DateTime start; DateTime end; do { if (!i$.hasNext()) { return new DateTime(); } DateTime genTime = (DateTime)i$.next(); start = genTime.minus(unit.toMillis((long)amount)); end = genTime.plus(unit.toMillis((long)amount)); } while(this.signingTime.isBefore(start) || this.signingTime.isAfter(end)); return this.signingTime; }
Example 4
Source File: SuplLppClient.java From supl-client with Apache License 2.0 | 6 votes |
private DateTime toGloTime(DateTime dateTime) { dateTime = dateTime.plus(TimeConstants.GPS_UTC_EPOCHS_OFFSET_MILLIS); int countLeapSec1 = getLeapSecond(dateTime); // The countLeapSec1 would produce the correct number of leap seconds except for an edge case // where a straddle leap second occurs (number of leap seconds now != number of leap seconds // after adjusting the time with the computed leap seconds). In such case, we need to add one to // the used leap second. DateTime gpsDateTimeMinusLeapSec = dateTime.minusSeconds(countLeapSec1); int countLeapSec2 = getLeapSecond(gpsDateTimeMinusLeapSec); gpsDateTimeMinusLeapSec = (countLeapSec1 == countLeapSec2) ? gpsDateTimeMinusLeapSec : gpsDateTimeMinusLeapSec.minusSeconds(countLeapSec2); gpsDateTimeMinusLeapSec.plusHours(TimeConstants.MOSCOW_UTC_TIME_OFFSET_HOURS); return gpsDateTimeMinusLeapSec; }
Example 5
Source File: TimeSeriesHandler.java From incubator-pinot with Apache License 2.0 | 6 votes |
/** * Handles the given time series request using the given time series parser. * * @param timeSeriesRequest the request to retrieve time series. * * @return the time series for the given request. * * @throws Exception Any exception that is thrown during the retrieval. */ public TimeSeriesResponse handle(TimeSeriesRequest timeSeriesRequest, TimeSeriesResponseParser timeSeriesResponseParser) throws Exception { // Time ranges for creating ThirdEye request DateTime start = timeSeriesRequest.getStart(); DateTime end = timeSeriesRequest.getEnd(); if (timeSeriesRequest.isEndDateInclusive()) { // ThirdEyeRequest is exclusive endpoint, so increment by one bucket TimeGranularity aggregationTimeGranularity = timeSeriesRequest.getAggregationTimeGranularity(); end = end.plus(aggregationTimeGranularity.toMillis()); } // Create request ThirdEyeRequest request = createThirdEyeRequest("timeseries", timeSeriesRequest, start, end); Future<ThirdEyeResponse> responseFuture = queryCache.getQueryResultAsync(request); // 5 minutes timeout ThirdEyeResponse response = responseFuture.get(5, TimeUnit.MINUTES); List<TimeSeriesRow> rows = timeSeriesResponseParser.parseResponse(response); // compute the derived metrics computeDerivedMetrics(timeSeriesRequest, rows); return new TimeSeriesResponse(rows); }
Example 6
Source File: RefreshDnsOnHostRenameActionTest.java From nomulus with Apache License 2.0 | 6 votes |
@Test public void testSuccess_multipleHostsProcessedInBatch() throws Exception { HostResource host1 = persistActiveHost("ns1.example.tld"); HostResource host2 = persistActiveHost("ns2.example.tld"); HostResource host3 = persistActiveHost("ns3.example.tld"); persistResource(newDomainBase("example1.tld", host1)); persistResource(newDomainBase("example2.tld", host2)); persistResource(newDomainBase("example3.tld", host3)); DateTime timeEnqueued = clock.nowUtc(); DateTime laterTimeEnqueued = timeEnqueued.plus(standardSeconds(10)); enqueuer.enqueueAsyncDnsRefresh(host1, timeEnqueued); enqueuer.enqueueAsyncDnsRefresh(host2, timeEnqueued); enqueuer.enqueueAsyncDnsRefresh(host3, laterTimeEnqueued); runMapreduce(); assertDnsTasksEnqueued("example1.tld", "example2.tld", "example3.tld"); assertNoTasksEnqueued(QUEUE_ASYNC_HOST_RENAME); verify(action.asyncTaskMetrics).recordDnsRefreshBatchSize(3L); verify(action.asyncTaskMetrics, times(2)) .recordAsyncFlowResult(DNS_REFRESH, OperationResult.SUCCESS, timeEnqueued); verify(action.asyncTaskMetrics) .recordAsyncFlowResult(DNS_REFRESH, OperationResult.SUCCESS, laterTimeEnqueued); verifyNoMoreInteractions(action.asyncTaskMetrics); }
Example 7
Source File: Lock.java From nomulus with Apache License 2.0 | 6 votes |
/** * Create a new {@link Lock} for the given resource name in the specified tld (which can be null * for cross-tld locks). */ public static Lock create( String resourceName, @Nullable String tld, String requestLogId, DateTime acquiredTime, Duration leaseLength) { checkArgument(!Strings.isNullOrEmpty(resourceName), "resourceName cannot be null or empty"); Lock instance = new Lock(); // Add the tld to the Lock's id so that it is unique for locks acquiring the same resource // across different TLDs. instance.lockId = makeLockId(resourceName, tld); instance.requestLogId = requestLogId; instance.expirationTime = acquiredTime.plus(leaseLength); instance.acquiredTime = acquiredTime; instance.resourceName = resourceName; instance.tld = tld; return instance; }
Example 8
Source File: AnomaliesResource.java From incubator-pinot with Apache License 2.0 | 6 votes |
private TimeRange getTimeRangeWithOffsets(AnomalyOffset offset, DateTime windowStart, DateTime windowEnd, DatasetConfigDTO datasetConfig) { Period preOffsetPeriod = offset.getPreOffsetPeriod(); Period postOffsetPeriod = offset.getPostOffsetPeriod(); DateTimeZone dateTimeZone = DateTimeZone.forID(datasetConfig.getTimezone()); DateTime windowStartDateTime = new DateTime(windowStart, dateTimeZone); DateTime windowEndDateTime = new DateTime(windowEnd, dateTimeZone); windowStartDateTime = windowStartDateTime.minus(preOffsetPeriod); windowEndDateTime = windowEndDateTime.plus(postOffsetPeriod); long windowStartTime = windowStartDateTime.getMillis(); long windowEndTime = windowEndDateTime.getMillis(); try { Long maxDataTime = CACHE_REGISTRY.getDatasetMaxDataTimeCache().get(datasetConfig.getDataset()); if (windowEndTime > maxDataTime) { windowEndTime = maxDataTime; } } catch (ExecutionException e) { LOG.error("Exception when reading max time for {}", datasetConfig.getDataset(), e); } TimeRange range = new TimeRange(windowStartTime, windowEndTime); return range; }
Example 9
Source File: DynamoDBFibonacciRetryer.java From emr-dynamodb-connector with Apache License 2.0 | 6 votes |
public <T> RetryResult<T> runWithRetry(Callable<T> callable, Reporter reporter, PrintCounter retryCounter) { fib1 = 0; fib2 = 1; retryCount = 0; DateTime currentTime = new DateTime(DateTimeZone.UTC); DateTime retryEndTime = currentTime.plus(retryPeriod); while (true) { if (isShutdown) { log.info("Is shut down, giving up and returning null"); return null; } try { T returnObj = callable.call(); return new RetryResult<>(returnObj, retryCount); } catch (Exception e) { handleException(retryEndTime, e, reporter, retryCounter); } } }
Example 10
Source File: MongoDB.java From jlogstash-input-plugin with Apache License 2.0 | 6 votes |
/** * 获取过滤条件 * * @return */ private Document getFilterDoc() { DateTime start = startTime.get(); if (start == null) { return queryDocument; } DateTime end = start.plus(getNextDuration()); Map<String, Object> condition = new HashMap<String, Object>(); if ("id".equals(since_type)) { condition.put("$gte", new ObjectId(start.toDate())); condition.put("$lt", new ObjectId(end.toDate())); } else { condition.put("$gte", start); condition.put("$lt", end); } queryDocument.put(since_column, condition); return queryDocument; }
Example 11
Source File: MockThirdEyeDataSource.java From incubator-pinot with Apache License 2.0 | 5 votes |
/** * Returns a DataFrame populated with mock data for a given config and time range. * * @param config metric generator config * @param start start time * @param end end time * @param interval time granularity * @return DataFrame with mock data */ private static DataFrame makeData(Map<String, Object> config, DateTime start, DateTime end, Period interval) { List<Long> timestamps = new ArrayList<>(); List<Double> values = new ArrayList<>(); double mean = MapUtils.getDoubleValue(config, "mean", 0); double std = MapUtils.getDoubleValue(config, "std", 1); double daily = MapUtils.getDoubleValue(config, "daily", mean); double weekly = MapUtils.getDoubleValue(config, "weekly", daily); NormalDistribution dist = new NormalDistribution(mean, std); DateTime origin = start.withFields(DataFrameUtils.makeOrigin(PeriodType.days())); while (origin.isBefore(end)) { if (origin.isBefore(start)) { origin = origin.plus(interval); continue; } timestamps.add(origin.getMillis()); double compDaily = weekly * (COMPONENT_ALPHA_WEEKLY + Math.sin(origin.getDayOfWeek() / 7.0 * 2 * Math.PI + 1) / 2 * (1 - COMPONENT_ALPHA_WEEKLY)); double compHourly = daily * (COMPONENT_ALPHA_DAILY + Math.sin(origin.getHourOfDay() / 24.0 * 2 * Math.PI + 1) / 2 * (1 - COMPONENT_ALPHA_DAILY)); double compEpsilon = dist.sample(); values.add((double) Math.max(Math.round(compDaily + compHourly + compEpsilon), 0)); origin = origin.plus(interval); } return new DataFrame() .addSeries(COL_TIME, ArrayUtils.toPrimitive(timestamps.toArray(new Long[0]))) .addSeries(COL_VALUE, ArrayUtils.toPrimitive(values.toArray(new Double[0]))) .setIndex(COL_TIME); }
Example 12
Source File: QueryLog.java From unitime with Apache License 2.0 | 5 votes |
public int[] countQueries(Map<String, int[]> table, DateTime date) { DateTime d = date; int[] ret = new int[Type.values().length]; for (int i = 0; i < ret.length; i++) ret[i] = 0; for (int i = 0; i < iWindow; i++) { int[] count = table.get(format(d)); if (count != null) for (int j = 0; j < count.length; j++) ret[j] += count[j]; d = d.plus(iIncrement); } return ret; }
Example 13
Source File: ClusterRepairScheduler.java From cassandra-reaper with Apache License 2.0 | 5 votes |
private DateTime nextActivationStartDate(int scheduleIndex) { DateTime timeBeforeFirstSchedule = DateTime.now().plus(context.config.getAutoScheduling().getTimeBeforeFirstSchedule().toMillis()); if (context.config.getAutoScheduling().hasScheduleSpreadPeriod()) { return timeBeforeFirstSchedule.plus( scheduleIndex * context.config.getAutoScheduling().getScheduleSpreadPeriod().toMillis()); } return timeBeforeFirstSchedule; }
Example 14
Source File: KerberosPrincipal.java From MaxKey with Apache License 2.0 | 5 votes |
/** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub String kerberosPrincipal="[email protected]"; kerberosPrincipal=kerberosPrincipal.substring(0, kerberosPrincipal.indexOf("@")); System.out.println(kerberosPrincipal); if (Pattern.matches("[0-9]+", "TWO_WEEK")){ System.out.println("true"); }else{ System.out.println("false"); } DateTime datetime=new DateTime(new Date(), ISOChronology.getInstanceUTC()); System.out.println(DateUtils.toUtc(datetime)); datetime=datetime.plus(10*1000); System.out.println(DateUtils.toUtc(datetime)); String json="{\"fullPrincipal\":\"[email protected]\",\"principal\":\"Administrator\",\"userDomain\":\"CONNSEC\",\"notOnOrAfter\":\"2014-01-18T07:10:16.624Z\"}"; KerberosToken kerberosToken=new KerberosToken(); kerberosToken=(KerberosToken)JsonUtils.json2Object(json, kerberosToken); System.out.println(kerberosToken); System.out.println(DateUtils.toUtcDate(kerberosToken.getNotOnOrAfter())); }
Example 15
Source File: AnomalyDetectorWrapper.java From incubator-pinot with Apache License 2.0 | 5 votes |
private List<DateTime> getMonitoringWindowEndTimes() { List<DateTime> endTimes = new ArrayList<>(); // get current hour/day, depending on granularity of dataset, DateTime currentEndTime = new DateTime(getBoundaryAlignedTimeForDataset(new DateTime(endTime, dateTimeZone)), dateTimeZone); DateTime lastDateTime = new DateTime(getBoundaryAlignedTimeForDataset(new DateTime(startTime, dateTimeZone)), dateTimeZone); while (lastDateTime.isBefore(currentEndTime)) { lastDateTime = lastDateTime.plus(this.bucketPeriod); endTimes.add(lastDateTime); } return endTimes; }
Example 16
Source File: Grouping.java From incubator-pinot with Apache License 2.0 | 5 votes |
private static long[] makeCutoffs(DateTime origin, DateTime max, Period bucketSize) { List<Long> offsets = new ArrayList<>(); DateTime offset = origin; while (offset.isBefore(max) || offset.isEqual(max)) { offsets.add(offset.getMillis()); offset = offset.plus(bucketSize); } return ArrayUtils.toPrimitive(offsets.toArray(new Long[offsets.size()])); }
Example 17
Source File: TransactionConfiguration.java From evt4j with MIT License | 5 votes |
public static String getExpirationTime(@NotNull String referenceTime, @Nullable String type) { int TIMESTAMP_LENGTH = 19; Duration expireDuration = Duration.standardSeconds(100); if (type != null && type.equals("everipay")) { expireDuration = Duration.standardSeconds(10); } DateTime dateTime = Utils.getCorrectedTime(referenceTime); DateTime expiration = dateTime.plus(expireDuration); return expiration.toString().substring(0, TIMESTAMP_LENGTH); }
Example 18
Source File: ProcessorListener.java From java with Apache License 2.0 | 4 votes |
public void determineNextResync(DateTime now) { this.nextResync = now.plus(this.resyncPeriod); }
Example 19
Source File: ContactTransferRequestFlow.java From nomulus with Apache License 2.0 | 4 votes |
@Override public final EppResponse run() throws EppException { extensionManager.register(MetadataExtension.class); extensionManager.validate(); validateClientIsLoggedIn(gainingClientId); DateTime now = tm().getTransactionTime(); ContactResource existingContact = loadAndVerifyExistence(ContactResource.class, targetId, now); verifyAuthInfoPresentForResourceTransfer(authInfo); verifyAuthInfo(authInfo.get(), existingContact); // Verify that the resource does not already have a pending transfer. if (TransferStatus.PENDING.equals(existingContact.getTransferData().getTransferStatus())) { throw new AlreadyPendingTransferException(targetId); } String losingClientId = existingContact.getCurrentSponsorClientId(); // Verify that this client doesn't already sponsor this resource. if (gainingClientId.equals(losingClientId)) { throw new ObjectAlreadySponsoredException(); } verifyNoDisallowedStatuses(existingContact, DISALLOWED_STATUSES); HistoryEntry historyEntry = historyBuilder .setType(HistoryEntry.Type.CONTACT_TRANSFER_REQUEST) .setModificationTime(now) .setParent(Key.create(existingContact)) .build(); DateTime transferExpirationTime = now.plus(automaticTransferLength); ContactTransferData serverApproveTransferData = new ContactTransferData.Builder() .setTransferRequestTime(now) .setTransferRequestTrid(trid) .setGainingClientId(gainingClientId) .setLosingClientId(losingClientId) .setPendingTransferExpirationTime(transferExpirationTime) .setTransferStatus(TransferStatus.SERVER_APPROVED) .build(); // If the transfer is server approved, this message will be sent to the losing registrar. */ PollMessage serverApproveLosingPollMessage = createLosingTransferPollMessage(targetId, serverApproveTransferData, historyEntry); // If the transfer is server approved, this message will be sent to the gaining registrar. */ PollMessage serverApproveGainingPollMessage = createGainingTransferPollMessage(targetId, serverApproveTransferData, historyEntry); ContactTransferData pendingTransferData = serverApproveTransferData .asBuilder() .setTransferStatus(TransferStatus.PENDING) .setServerApproveEntities( ImmutableSet.of( serverApproveGainingPollMessage.createVKey(), serverApproveLosingPollMessage.createVKey())) .build(); // When a transfer is requested, a poll message is created to notify the losing registrar. PollMessage requestPollMessage = createLosingTransferPollMessage(targetId, pendingTransferData, historyEntry).asBuilder() .setEventTime(now) // Unlike the serverApprove messages, this applies immediately. .build(); ContactResource newContact = existingContact.asBuilder() .setTransferData(pendingTransferData) .addStatusValue(StatusValue.PENDING_TRANSFER) .build(); ofy().save().<Object>entities( newContact, historyEntry, requestPollMessage, serverApproveGainingPollMessage, serverApproveLosingPollMessage); return responseBuilder .setResultFromCode(SUCCESS_WITH_ACTION_PENDING) .setResData(createTransferResponse(targetId, newContact.getTransferData())) .build(); }
Example 20
Source File: DateUtilTest.java From commcare-android with Apache License 2.0 | 3 votes |
@Test public void testDateCalculations() { //Test Identity Calculations Date now = new Date(); LocalDateTime ldnow = new LocalDateTime(now); DateTime dtnow = new DateTime(now); Assert.assertEquals("Dates are incompatible (Date -> LocalDate)", now.getTime(), ldnow.toDate().getTime()); Assert.assertEquals("Dates are incompatible (Date -> DateTime)", now.getTime(), dtnow.toLocalDateTime().toDate().getTime()); DateTime elevenPm = new DateTime(2020, 10, 10, 23, 00, 00); DateTime twoAmNd = elevenPm.plus(Hours.hours(4)); DateTime elevenThirtyPmNd = new DateTime(2020, 10, 11, 23, 30, 00); DateTime elevenPmPlusThree = elevenPm.plus(Hours.hours(72)); DateTime elevenPmPlusThreeDaysThirtyMinutes = elevenPm.plus(Hours.hours(72).plus(Minutes.minutes(30).toStandardHours())); DateTime elevenPmPlusThreeDaysOneHour = elevenPm.plus(Hours.hours(73)); Assert.assertEquals(1, SyncDetailCalculations.getDaysBetweenJavaDatetimes(elevenPm.toDate(), twoAmNd.toDate())); Assert.assertEquals(0, SyncDetailCalculations.getDaysBetweenJavaDatetimes(twoAmNd.toDate(), elevenThirtyPmNd.toDate())); Assert.assertEquals(3, SyncDetailCalculations.getDaysBetweenJavaDatetimes(elevenPm.toDate(), elevenPmPlusThree.toDate())); Assert.assertEquals(3, SyncDetailCalculations.getDaysBetweenJavaDatetimes(elevenPm.toDate(), elevenPmPlusThreeDaysThirtyMinutes.toDate())); Assert.assertEquals(4, SyncDetailCalculations.getDaysBetweenJavaDatetimes(elevenPm.toDate(), elevenPmPlusThreeDaysOneHour.toDate())); }