List of usage examples for org.joda.time DateTime minusMillis
public DateTime minusMillis(int millis)
From source file:demo.sts.provider.token.Saml1TokenProvider.java
License:Apache License
private org.opensaml.saml1.core.Assertion createAuthnAssertionSAML1(org.opensaml.saml1.core.Subject subject) { org.opensaml.saml1.core.AuthenticationStatement authnStatement = (new org.opensaml.saml1.core.impl.AuthenticationStatementBuilder()) .buildObject();//from w w w .j a va 2s.c o m authnStatement.setSubject(subject); // authnStatement.setAuthenticationMethod(strAuthMethod); DateTime now = new DateTime(); authnStatement.setAuthenticationInstant(now); org.opensaml.saml1.core.Conditions conditions = (new org.opensaml.saml1.core.impl.ConditionsBuilder()) .buildObject(); conditions.setNotBefore(now.minusMillis(3600000)); conditions.setNotOnOrAfter(now.plusMillis(3600000)); String issuerURL = "http://www.sopera.de/SAML1"; org.opensaml.saml1.core.Assertion assertion = (new org.opensaml.saml1.core.impl.AssertionBuilder()) .buildObject(); try { SecureRandomIdentifierGenerator generator = new SecureRandomIdentifierGenerator(); assertion.setID(generator.generateIdentifier()); } catch (NoSuchAlgorithmException e) { LOG.log(Level.WARNING, e.getMessage(), e); } assertion.setIssuer(issuerURL); assertion.setIssueInstant(now); assertion.setVersion(SAMLVersion.VERSION_11); assertion.getAuthenticationStatements().add(authnStatement); // assertion.getAttributeStatements().add(attrStatement); assertion.setConditions(conditions); return assertion; }
From source file:demo.sts.provider.token.Saml2TokenProvider.java
License:Apache License
private Assertion createAssertion(Subject subject) { Assertion assertion = (new AssertionBuilder()).buildObject(); try {/*from ww w .j ava 2 s.com*/ SecureRandomIdentifierGenerator generator = new SecureRandomIdentifierGenerator(); assertion.setID(generator.generateIdentifier()); } catch (NoSuchAlgorithmException e) { LOG.log(Level.WARNING, e.getMessage(), e); } DateTime now = new DateTime(); assertion.setIssueInstant(now); String issuerURL = "http://www.sopera.de/SAML2"; if (issuerURL != null) { Issuer issuer = (new IssuerBuilder()).buildObject(); issuer.setValue(issuerURL); assertion.setIssuer(issuer); } assertion.setSubject(subject); Conditions conditions = (new ConditionsBuilder()).buildObject(); conditions.setNotBefore(now.minusMillis(3600000)); conditions.setNotOnOrAfter(now.plusMillis(3600000)); assertion.setConditions(conditions); return assertion; }
From source file:google.registry.model.domain.DomainResource.java
License:Open Source License
/** * The logic in this method, which handles implicit server approval of transfers, very closely * parallels the logic in {@code DomainTransferApproveFlow} which handles explicit client * approvals./*from www.j a va 2 s. c o m*/ */ @Override public DomainResource cloneProjectedAtTime(final DateTime now) { TransferData transferData = getTransferData(); DateTime transferExpirationTime = transferData.getPendingTransferExpirationTime(); // If there's a pending transfer that has expired, handle it. if (TransferStatus.PENDING.equals(transferData.getTransferStatus()) && isBeforeOrAt(transferExpirationTime, now)) { // Project until just before the transfer time. This will handle the case of an autorenew // before the transfer was even requested or during the request period. // If the transfer time is precisely the moment that the domain expires, there will not be an // autorenew billing event (since we end the recurrence at transfer time and recurrences are // exclusive of their ending), and we can just proceed with the transfer. DomainResource domainAtTransferTime = cloneProjectedAtTime(transferExpirationTime.minusMillis(1)); // If we are within an autorenew grace period, the transfer will subsume the autorenew. There // will already be a cancellation written in advance by the transfer request flow, so we don't // need to worry about billing, but we do need to reduce the number of years added to the // expiration time by one to account for the year added by the autorenew. int extraYears = transferData.getExtendedRegistrationYears(); if (domainAtTransferTime.getGracePeriodStatuses().contains(GracePeriodStatus.AUTO_RENEW)) { extraYears--; } // Set the expiration, autorenew events, and grace period for the transfer. (Transfer ends // all other graces). Builder builder = domainAtTransferTime.asBuilder() // Extend the registration by the correct number of years from the expiration time that // was current on the domain right before the transfer, capped at 10 years from the // moment of the transfer. .setRegistrationExpirationTime(extendRegistrationWithCap(transferExpirationTime, domainAtTransferTime.getRegistrationExpirationTime(), extraYears)) // Set the speculatively-written new autorenew events as the domain's autorenew events. .setAutorenewBillingEvent(transferData.getServerApproveAutorenewEvent()) .setAutorenewPollMessage(transferData.getServerApproveAutorenewPollMessage()) // Set the grace period using a key to the prescheduled transfer billing event. Not using // GracePeriod.forBillingEvent() here in order to avoid the actual datastore fetch. .setGracePeriods(ImmutableSet.of(GracePeriod.create(GracePeriodStatus.TRANSFER, transferExpirationTime.plus(Registry.get(getTld()).getTransferGracePeriodLength()), transferData.getGainingClientId(), transferData.getServerApproveBillingEvent()))); // Set all remaining transfer properties. setAutomaticTransferSuccessProperties(builder, transferData); // Finish projecting to now. return builder.build().cloneProjectedAtTime(now); } // There is no transfer. Do any necessary autorenews. Builder builder = asBuilder(); if (isBeforeOrAt(registrationExpirationTime, now)) { // Autorenew by the number of years between the old expiration time and now. DateTime lastAutorenewTime = leapSafeAddYears(registrationExpirationTime, new Interval(registrationExpirationTime, now).toPeriod().getYears()); DateTime newExpirationTime = lastAutorenewTime.plusYears(1); builder.setRegistrationExpirationTime(newExpirationTime) .addGracePeriod(GracePeriod.createForRecurring(GracePeriodStatus.AUTO_RENEW, lastAutorenewTime.plus(Registry.get(getTld()).getAutoRenewGracePeriodLength()), getCurrentSponsorClientId(), autorenewBillingEvent)); } // Remove any grace periods that have expired. DomainResource almostBuilt = builder.build(); builder = almostBuilt.asBuilder(); for (GracePeriod gracePeriod : almostBuilt.getGracePeriods()) { if (isBeforeOrAt(gracePeriod.getExpirationTime(), now)) { builder.removeGracePeriod(gracePeriod); } } // Handle common properties like setting or unsetting linked status. This also handles the // general case of pending transfers for other resource types, but since we've always handled // a pending transfer by this point that's a no-op for domains. projectResourceOntoBuilderAtTime(almostBuilt, builder, now); return builder.build(); }
From source file:influent.server.data.PropertyMatchBuilder.java
License:MIT License
private void _parseTerm(String termName, String termValue, FL_PropertyDescriptors descriptors) { if (termValue == null || termValue.isEmpty()) return;/*from w ww . jav a2 s.c o m*/ boolean isQuoted = false; boolean isRange = false; boolean isFuzzy = false; boolean isNegation = false; // Start a term builder FL_PropertyMatchDescriptor.Builder termBuilder = FL_PropertyMatchDescriptor.newBuilder(); boolean isFreeText = termName == null; if (!isFreeText) { // Negation if (termName.startsWith("-")) { termName = termName.substring(1); termBuilder.setInclude(false); isNegation = true; } } // Term Boosting Matcher boostMatch = boostPattern.matcher(termValue); if (boostMatch.find()) { String weightStr = boostMatch.group(1); try { Float weight = Float.valueOf(weightStr); termValue = termValue.substring(0, termValue.length() - weightStr.length() - 1); termBuilder.setWeight(weight); } catch (Exception e) { } } // Fuzzy matching Matcher similarityMatch = similarityPattern.matcher(termValue); if (similarityMatch.find()) { String similarityStr = similarityMatch.group(1); try { Float similarity = similarityStr == null ? 0.5f : Float.valueOf(similarityStr); termValue = similarityMatch.group(1); termBuilder.setSimilarity(similarity); isFuzzy = true; } catch (Exception e) { } } // Quotes and ranges Matcher quoteMatch = quotePattern.matcher(termValue); Matcher rangeMatch = rangePattern.matcher(termValue); String rangeStart = null; String rangeEnd = null; if (quoteMatch.find()) { termValue = quoteMatch.group(2); isQuoted = true; } if (rangeMatch.find()) { isRange = true; rangeStart = rangeMatch.group(1); rangeEnd = rangeMatch.group(2); } // Constraints if (!isFuzzy && (isQuoted || isFreeText || isRange || isNegation)) { if (_matchType == null || _matchType.equalsIgnoreCase("any")) { termBuilder.setConstraint(FL_Constraint.OPTIONAL_EQUALS); } else { termBuilder.setConstraint(FL_Constraint.REQUIRED_EQUALS); } } else { if (_matchType == null || _matchType.equalsIgnoreCase("any")) { termBuilder.setConstraint(FL_Constraint.FUZZY_PARTIAL_OPTIONAL); } else { termBuilder.setConstraint(FL_Constraint.FUZZY_REQUIRED); } } // Match properties to Search Descriptors for (FL_PropertyDescriptor pd : descriptors.getProperties()) { String propertyKey = pd.getKey(); if (propertyKey.equals(termName) || isFreeText) { for (FL_TypeMapping td : pd.getMemberOf()) { if (isFreeText && !FL_SearchableBy.FREE_TEXT.equals(pd.getSearchableBy())) { // If the term is freetext, but this isn't a freetext searchable property, continue; continue; } else if (_dataTypes != null && !_dataTypes.contains(td.getType())) { // If the term doesn't match the given datatypes, then continue; continue; } termBuilder.setKey(pd.getKey()); // Special handling for dates if (pd.getPropertyType() == FL_PropertyType.DATE) { // Dates become unfuzzied if (_matchType == null || _matchType.equalsIgnoreCase("any")) { termBuilder.setConstraint(FL_Constraint.OPTIONAL_EQUALS); } else { termBuilder.setConstraint(FL_Constraint.REQUIRED_EQUALS); } if (!isRange) { // Singleton dates become ranges across the whole 24h day DateTime date = new DateTime(termValue); rangeStart = dateFormatter.print(date.withTime(0, 0, 0, 0)); rangeEnd = dateFormatter.print(date.withTime(23, 59, 59, 59)); isRange = true; } else { if (!rangeStart.equals("*")) { DateTime startDate = new DateTime(rangeStart); rangeStart = dateFormatter.print(startDate.withTime(0, 0, 0, 0)); // From 0h on start date.. } if (!rangeEnd.equals("*")) { DateTime endDate = new DateTime(rangeEnd); rangeEnd = dateFormatter.print(endDate.minusMillis(3)); // .. to 23:59:59.997 exclusive of the end date (max SQL millisecond precision) } } } // Set the term value in the builder if (isRange) { termBuilder.setRange(FL_BoundedRange.newBuilder().setStart(rangeStart).setEnd(rangeEnd) .setInclusive(true).setType(pd.getPropertyType()).build()); } else { // freetext is comma/space delimited (as long as it's not quoted). Everything else is comma delimited. List<Object> values = new ArrayList<Object>(Arrays.asList( termValue.split(isFreeText && !isQuoted ? "(?<!\\\\)( |,)" : "(?<!\\\\),"))); if (pd.getKey().equals(FL_RequiredPropertyKey.FROM.name()) || pd.getKey().equals(FL_RequiredPropertyKey.TO.name()) || pd.getKey().equals(FL_RequiredPropertyKey.ENTITY.name()) || pd.getKey().equals(FL_RequiredPropertyKey.LINKED.name())) { values = processIds(values, td); } if (values.size() == 0) { // Stripped out all the values? Throw it out continue; } else if (values.size() == 1) { // Singletons termBuilder.setRange(FL_SingletonRange.newBuilder().setType(pd.getPropertyType()) .setValue(values.get(0)).build()); } else { // Lists termBuilder.setRange(FL_ListRange.newBuilder().setType(pd.getPropertyType()) .setValues(new ArrayList<Object>(values)).build()); } } if (isFreeText) { // Freetext, but not the correct type? if (!_typeCheckPropertyValue(pd, termBuilder.getRange())) { continue; } } termBuilder.setTypeMappings(Collections.singletonList(td)); List<FL_PropertyMatchDescriptor> termList = _descriptorMap.get(td.getType()); if (termList == null) { termList = new ArrayList<FL_PropertyMatchDescriptor>(); } termList.add(termBuilder.build()); _descriptorMap.put(td.getType(), termList); } } } }
From source file:jp.furplag.util.time.JodaPrettifier.java
License:Apache License
/** * Return the prettified String if the period includes specified moment. * * <pre>/* w ww. j a v a 2 s . c om*/ * prettify(DateTime.now().minusHours(1), null, null, null, null) = "one hour ago." prettify(DateTime.now(), DateTime.now().plusYears(1), null, null, null) = "one year ago." prettify(DateTime.now().minusHours(1), null, null, null, new Period().withDays(1)) = "one hour ago." prettify(DateTime.now().minusHours(1), null, null, null, new Period().withMinites(10)) = * DateTime.now().withZone(DateTimeZone.UTC).minusHours(1).toString(DateTimeFormat.forStyle("-M")) * * <pre> * * @param then the datetime object, null means current date-time. * @param reference the moment of a starting point ( {@link org.joda.time.ReadableInstant} and {@link Long} specifiable ). Use {@code DateTime.now()} as a start point if {@code reference} is null. * @param locale the language for Localization ( {@code String} and {@code Locale} specifiable ). Use ROOT if {@code locale} is null. * @param limit if the moment is in the specified period, return prettified String ( {@code Period} and {@code Interval} specifiable ). Prettify all, if null. * @return the prettified String if the period includes specified moment. In other situation, return stringified date-time. */ public static String prettify(final Object then, final Object reference, final Locale locale, final DateTimeZone zone, final Object limit) { DateTime temporary = DateTimeUtils.toDT(then, zone, true); if (temporary == null) return StringUtils.EMPTY; DateTime ref = DateTimeUtils.toDT(reference, temporary.getZone(), true); if (ref == null) return doPrettify(temporary, null, locale); if (ref.isEqual(temporary)) ref = ref.plusMillis(1); if (limit == null) return doPrettify(temporary, ref, locale); Interval limitter = null; if (Interval.class.equals(limit)) limitter = (Interval) limit; if (limit instanceof Period) { limitter = new Interval(ref.minus((Period) limit), ref.plusMillis(1).plus((Period) limit)); } if (limit instanceof BaseSingleFieldPeriod) { limitter = new Interval(ref.minus(new Period(limit)), ref.plusMillis(1).plus(new Period(limit))); } if (ObjectUtils.isAny(ClassUtils.primitiveToWrapper(limit.getClass()), Double.class, Float.class)) { limitter = new Interval(toDT(toAJD(ref) - NumberUtils.valueOf(limit, double.class), ref), toDT(toAJD(ref) + NumberUtils.valueOf(limit, double.class), ref)); } else if (BigDecimal.class.equals(limit.getClass())) { if (NumberUtils.compareTo((BigDecimal) limit, NumberUtils.down(limit)) == 0) { limitter = new Interval(ref.minusMillis(NumberUtils.valueOf(limit, int.class)), ref.plusMillis(NumberUtils.valueOf(limit, int.class) + 1)); } else { limitter = new Interval(toDT(toAJD(ref) - NumberUtils.valueOf(limit, double.class), ref), toDT(toAJD(ref) + NumberUtils.valueOf(limit, double.class), ref)); } } else if (Number.class.isAssignableFrom(ClassUtils.primitiveToWrapper(limit.getClass()))) { limitter = new Interval(ref.minusMillis(NumberUtils.valueOf(limit, int.class)), ref.plusMillis(NumberUtils.valueOf(limit, int.class) + 1)); } if (DateTime.class.equals(limit.getClass())) { limitter = new Interval(ref.minus(((DateTime) limit).getMillis()), ref.plus(((DateTime) limit).getMillis() + 1L)); } if (Boolean.class.equals(limit.getClass())) { limitter = new Interval(temporary.minusMillis(1), ((Boolean) limit) ? temporary.plusMillis(1) : temporary.minusMillis(1)); } if (limitter == null) return doPrettify(temporary, ref, locale); if (limitter.contains(temporary)) return doPrettify(temporary, ref, locale); return toDT(temporary, GJChronology.getInstance(temporary.getZone())) .toString(DateTimeFormat.forStyle(isToday(temporary, temporary.getZone()) ? "-M" : "MS") .withLocale(locale == null ? Locale.ROOT : locale)); }
From source file:li.klass.fhem.activities.graph.ChartData.java
License:Open Source License
private List<GraphEntry> handleShowDiscreteValues(List<GraphEntry> data) { if (!isDiscreteChart()) { return data; }//from ww w . j a va2s . c o m float previousValue = -1; List<GraphEntry> newData = newArrayList(); for (GraphEntry entry : data) { DateTime date = entry.getDate(); float value = entry.getValue(); if (previousValue == -1) { previousValue = value; } newData.add(new GraphEntry(date.minusMillis(1), previousValue)); newData.add(new GraphEntry(date, value)); newData.add(new GraphEntry(date.plusMillis(1), value)); previousValue = value; } return newData; }
From source file:li.klass.fhem.activities.graph.ChartingActivity.java
License:Open Source License
private void handleDiscreteValues(Map<GPlotSeries, List<GraphEntry>> graphData) { for (Map.Entry<GPlotSeries, List<GraphEntry>> entry : graphData.entrySet()) { if (!isDiscreteSeries(entry.getKey())) { continue; }//w w w .j a v a 2 s.c om float previousValue = -1; List<GraphEntry> newData = newArrayList(); List<GraphEntry> values = entry.getValue(); for (GraphEntry graphEntry : values) { DateTime date = graphEntry.getDate(); float value = graphEntry.getValue(); if (previousValue == -1) { previousValue = value; } newData.add(new GraphEntry(date.minusMillis(1), previousValue)); newData.add(new GraphEntry(date, value)); newData.add(new GraphEntry(date.plusMillis(1), value)); previousValue = value; } values.clear(); values.addAll(newData); } }
From source file:niche.newres.timedevents2owl.randomizer.TimedEvents2OWLRandomizer.java
public static DateTime minusRandomMilliSeconds(DateTime dateTime, int minRange, int maxRange) { int randomMilliSeconds = TimedEvents2OWLRandomizer.randInt(minRange, maxRange); return dateTime.minusMillis(randomMilliSeconds); }
From source file:org.apache.cxf.ws.security.sts.provider.token.Saml1TokenProvider.java
License:Apache License
private org.opensaml.saml1.core.Assertion createAuthnAssertionSAML1(org.opensaml.saml1.core.Subject subject) { org.opensaml.saml1.core.AuthenticationStatement authnStatement = (new org.opensaml.saml1.core.impl.AuthenticationStatementBuilder()) .buildObject();//from ww w .ja v a 2 s . com authnStatement.setSubject(subject); // authnStatement.setAuthenticationMethod(strAuthMethod); DateTime now = new DateTime(); authnStatement.setAuthenticationInstant(now); org.opensaml.saml1.core.Conditions conditions = (new org.opensaml.saml1.core.impl.ConditionsBuilder()) .buildObject(); conditions.setNotBefore(now.minusMillis(3600000)); conditions.setNotOnOrAfter(now.plusMillis(3600000)); String issuerURL = "http://www.sopera.de/SAML1"; org.opensaml.saml1.core.Assertion assertion = (new org.opensaml.saml1.core.impl.AssertionBuilder()) .buildObject(); try { SecureRandomIdentifierGenerator generator = new SecureRandomIdentifierGenerator(); assertion.setID(generator.generateIdentifier()); } catch (NoSuchAlgorithmException e) { LOG.error(e); } assertion.setIssuer(issuerURL); assertion.setIssueInstant(now); assertion.setVersion(SAMLVersion.VERSION_11); assertion.getAuthenticationStatements().add(authnStatement); // assertion.getAttributeStatements().add(attrStatement); assertion.setConditions(conditions); return assertion; }
From source file:org.apache.cxf.ws.security.sts.provider.token.Saml2TokenProvider.java
License:Apache License
private Assertion createAssertion(Subject subject) { Assertion assertion = (new AssertionBuilder()).buildObject(); try {//from w ww . j av a2 s .co m SecureRandomIdentifierGenerator generator = new SecureRandomIdentifierGenerator(); assertion.setID(generator.generateIdentifier()); } catch (NoSuchAlgorithmException e) { LOG.error(e); } DateTime now = new DateTime(); assertion.setIssueInstant(now); String issuerURL = "http://www.sopera.de/SAML2"; if (issuerURL != null) { Issuer issuer = (new IssuerBuilder()).buildObject(); issuer.setValue(issuerURL); assertion.setIssuer(issuer); } assertion.setSubject(subject); Conditions conditions = (new ConditionsBuilder()).buildObject(); conditions.setNotBefore(now.minusMillis(3600000)); conditions.setNotOnOrAfter(now.plusMillis(3600000)); assertion.setConditions(conditions); return assertion; }