Java Code Examples for org.joda.time.DateTime#minusMinutes()

The following examples show how to use org.joda.time.DateTime#minusMinutes() . These examples are extracted from open source projects. 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 Project: frostmourne   File: ElasticsearchNumericMetric.java    License: MIT License 6 votes vote down vote up
public Map<String, Object> pullMetric(MetricContract metricContract, Map<String, String> settings) {
    ElasticsearchInfo elasticsearchInfo = new ElasticsearchInfo(metricContract.getDataSourceContract());
    EsRestClientContainer esRestClientContainer = elasticsearchSourceManager.findEsRestClientContainer(elasticsearchInfo);
    DateTime end = DateTime.now();
    DateTime start = end.minusMinutes(findTimeWindowInMinutes(settings));
    Map<String, Object> result = new HashMap<>();
    try {
        ElasticsearchMetric elasticsearchMetric = elasticsearchDataQuery.queryElasticsearchMetricValue(start, end, metricContract);
        result.put("NUMBER", elasticsearchMetric.getMetricValue());
        if (elasticsearchMetric.getLatestDocument() != null) {
            result.putAll(elasticsearchMetric.getLatestDocument());
        }
    } catch (IOException ex) {
        throw new RuntimeException("error when queryElasticsearchMetricValue", ex);
    }
    Map<String, String> dataNameProperties = metricContract.getDataNameContract().getSettings();
    String indexPrefix = dataNameProperties.get("indexPrefix");
    String datePattern = dataNameProperties.get("timePattern");
    String[] indices = esRestClientContainer.buildIndices(start, end, indexPrefix, datePattern);
    result.put("startTime", start.toDateTimeISO().toString());
    result.put("endTime", end.toDateTimeISO().toString());
    result.put("indices", indices);

    return result;
}
 
Example 2
private OmObservation createObservation() {
    final InterpolationType type = TimeseriesMLConstants.InterpolationType.InstantTotal;
    DateTime now = new DateTime(DateTimeZone.UTC);
    TimeInstant resultTime = new TimeInstant(now);
    TimePeriod validTime = new TimePeriod(now.minusMinutes(5), now.plusMinutes(5));
    OmObservation observation = new OmObservation();
    OmObservationConstellation observationConstellation = new OmObservationConstellation();
    observationConstellation.setFeatureOfInterest(new SamplingFeature(new CodeWithAuthority("feature", CODE_SPACE)));
    observationConstellation.setObservableProperty(new OmObservableProperty("omobservableProperty"));
    observationConstellation.setDefaultPointMetadata(new DefaultPointMetadata()
            .setDefaultTVPMeasurementMetadata(new DefaultTVPMeasurementMetadata().setInterpolationtype(type)));
    observationConstellation.setObservationType(OmConstants.OBS_TYPE_OBSERVATION);
    observationConstellation.addOffering(OFFERING);
    AbstractFeature procedure = new SosProcedureDescriptionUnknownType(PROCEDURE);
    observationConstellation.setProcedure(procedure);
    observation.setObservationConstellation(observationConstellation);
    observation.setParameter(null);
    observation.setResultTime(resultTime);
    observation.setTokenSeparator(TOKEN_SEPERATOR);
    observation.setTupleSeparator(TUPLE_SEPERATOR);
    observation.setValidTime(validTime);
    observation.setValue(mv);
    return observation;
}
 
Example 3
Source Project: nomulus   File: RdeUploadActionTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testRunWithLock_sftpCooldownNotPassed_throws204() {
  RdeUploadAction action = createAction(URI.create("sftp://user:[email protected]:32323/"));
  action.sftpCooldown = standardHours(2);
  DateTime stagingCursor = DateTime.parse("2010-10-18TZ");
  DateTime uploadCursor = DateTime.parse("2010-10-17TZ");
  DateTime sftpCursor = uploadCursor.minusMinutes(97); // Within the 2 hour cooldown period.
  persistResource(Cursor.create(RDE_STAGING, stagingCursor, Registry.get("tld")));
  persistResource(Cursor.create(RDE_UPLOAD_SFTP, sftpCursor, Registry.get("tld")));
  NoContentException thrown =
      assertThrows(NoContentException.class, () -> action.runWithLock(uploadCursor));
  assertThat(thrown)
      .hasMessageThat()
      .isEqualTo(
          "Waiting on 120 minute SFTP cooldown for TLD tld to send 2010-10-17T00:00:00.000Z "
              + "upload; last upload attempt was at 2010-10-16T22:23:00.000Z (97 minutes ago)");
}
 
Example 4
Source Project: frostmourne   File: AbstractSameTimeMetric.java    License: MIT License 5 votes vote down vote up
/**
 * 根据结束时间和比较间隔类型获取开始时间
 *
 * @param end        结束时间
 * @param periodUnit 间隔类型
 * @return start time
 */
protected DateTime findStart(DateTime end, String periodUnit) {
    DateTime start;
    if (periodUnit.equalsIgnoreCase("HOUR")) {
        start = end.minusMinutes(60);
    } else if (periodUnit.equalsIgnoreCase("DAY")) {
        start = end.minusDays(1);
    } else {
        throw new IllegalArgumentException("unknown period unit: " + periodUnit);
    }
    return start;
}
 
Example 5
private static DateTime getTheClosestTenRound(DateTime dt) {
    int minuteOfMinutesOfHour = dt.getMinuteOfHour() % 10;
    int diffToTen = 10 - minuteOfMinutesOfHour;
    return minuteOfMinutesOfHour >= diffToTen
            ? dt.plusMinutes(diffToTen)
            : dt.minusMinutes(minuteOfMinutesOfHour);
}
 
Example 6
Source Project: celos   File: UIServlet.java    License: Apache License 2.0 5 votes vote down vote up
static ScheduledTime getFirstTileTime(ScheduledTime now, int zoomLevelMinutes) {
    DateTime dt = now.getDateTime();
    DateTime nextDay = toFullDay(dt.plusDays(1));
    DateTime t = nextDay;
    while(t.isAfter(dt)) {
        t = t.minusMinutes(zoomLevelMinutes);
    }
    return new ScheduledTime(t);
}
 
Example 7
private String buildStreamDetailsURL(URI baseUri, AlertCondition.CheckResult checkResult, Stream stream) {
    // Return an informational message if the web interface URL hasn't been set
    if (baseUri == null || isNullOrEmpty(baseUri.getHost())) {
        return "Please configure 'transport_email_web_interface_url' in your Graylog configuration file.";
    }

    int time = 5;
    if (checkResult.getTriggeredCondition().getParameters().get("time") != null) {
        time = (int) checkResult.getTriggeredCondition().getParameters().get("time");
    }

    DateTime dateAlertEnd = checkResult.getTriggeredAt();
    DateTime dateAlertStart = dateAlertEnd.minusMinutes(time);
    String alertStart = Tools.getISO8601String(dateAlertStart);
    String alertEnd = Tools.getISO8601String(dateAlertEnd);

    AggregatesAlertCondition condition = (AggregatesAlertCondition) checkResult.getTriggeredCondition();

    String query = condition.getQuery();
    if (query != null && !"".equals(query)){
        try {
            query= "&q=" + URLEncoder.encode(query,"UTF-8");
        } catch (UnsupportedEncodingException e) {
            LOG.error("Failed to encode query [{}]", query );
        }
    } else {
        query = "";
    }

    return baseUri + "/streams/" + stream.getId() + "/messages?rangetype=absolute&from=" + alertStart + "&to=" + alertEnd + query;
}
 
Example 8
@Test
public void fromTweetsMapAgeMinutes() {
    DateTime now = DateTime.now();
    DateTime sixMinutesAgo = now.minusMinutes(6);
    List<Tweet> tweets = new ArrayList<>();
    tweets.add(createTweet(dtf.print(sixMinutesAgo), null, null, null, null));

    List<TimelineItem> results = TimelineConverter.fromTweets(tweets, now);

    assertThat(results.get(0).getCreatedAt(), is(equalTo("6m")));
}
 
Example 9
Source Project: hawkular-metrics   File: StringITest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void findDistinctStrings() throws Exception {
    DateTime end = now();
    DateTime start = end.minusMinutes(20);
    String tenantId = "Distinct Strings";
    MetricId<String> metricId = new MetricId<>(tenantId, STRING, "S1");

    Metric<String> metric = new Metric<>(metricId, asList(
            new DataPoint<>(start.getMillis(), "up"),
            new DataPoint<>(start.plusMinutes(1).getMillis(), "down"),
            new DataPoint<>(start.plusMinutes(2).getMillis(), "down"),
            new DataPoint<>(start.plusMinutes(3).getMillis(), "up"),
            new DataPoint<>(start.plusMinutes(4).getMillis(), "down"),
            new DataPoint<>(start.plusMinutes(5).getMillis(), "up"),
            new DataPoint<>(start.plusMinutes(6).getMillis(), "up"),
            new DataPoint<>(start.plusMinutes(7).getMillis(), "unknown"),
            new DataPoint<>(start.plusMinutes(8).getMillis(), "unknown"),
            new DataPoint<>(start.plusMinutes(9).getMillis(), "down"),
            new DataPoint<>(start.plusMinutes(10).getMillis(), "up")));

    doAction(() -> metricsService.addDataPoints(STRING, Observable.just(metric)));

    List<DataPoint<String>> actual = getOnNextEvents(() -> metricsService.findStringData(metricId,
            start.getMillis(), end.getMillis(), true, 0, Order.ASC));
    List<DataPoint<String>> expected = asList(
            metric.getDataPoints().get(0),
            metric.getDataPoints().get(1),
            metric.getDataPoints().get(3),
            metric.getDataPoints().get(4),
            metric.getDataPoints().get(5),
            metric.getDataPoints().get(7),
            metric.getDataPoints().get(9),
            metric.getDataPoints().get(10));

    assertEquals(actual, expected, "The string data does not match the expected values");
}
 
Example 10
Source Project: breakerbox   File: JdbiStoreTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void retrieveLatest() {
    final DateTime now = DateTime.now();
    final DependencyModel earlyDependencyModel = dependencyModel(now);
    final DependencyModel laterDependencyModel = new DependencyModel(
            earlyDependencyModel.getDependencyId(),
            now.plusMinutes(1),
            earlyDependencyModel.getTenacityConfiguration(),
            earlyDependencyModel.getUser(),
            earlyDependencyModel.getServiceId());
    final DependencyModel superEarlyModel = new DependencyModel(
            earlyDependencyModel.getDependencyId(),
            now.minusMinutes(1),
            earlyDependencyModel.getTenacityConfiguration(),
            earlyDependencyModel.getUser(),
            earlyDependencyModel.getServiceId());
    assertThat(jdbiStore.retrieveLatest(earlyDependencyModel.getDependencyId(), earlyDependencyModel.getServiceId()))
            .isEqualTo(Optional.empty());
    assertTrue(jdbiStore.store(earlyDependencyModel));
    assertThat(jdbiStore.retrieveLatest(earlyDependencyModel.getDependencyId(), earlyDependencyModel.getServiceId()))
            .isEqualTo(Optional.of(earlyDependencyModel));
    assertTrue(jdbiStore.store(laterDependencyModel));
    assertThat(jdbiStore.retrieveLatest(earlyDependencyModel.getDependencyId(), earlyDependencyModel.getServiceId()))
            .isEqualTo(Optional.of(laterDependencyModel));
    assertTrue(jdbiStore.store(superEarlyModel));
    assertThat(jdbiStore.retrieveLatest(earlyDependencyModel.getDependencyId(), earlyDependencyModel.getServiceId()))
            .isEqualTo(Optional.of(laterDependencyModel));
}
 
Example 11
Source Project: breakerbox   File: DependencyDBTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void retrieveLatest() {
    final DateTime now = DateTime.now();
    final DependencyModel earlyDependencyModel = dependencyModel(now);
    final DependencyModel laterDependencyModel = new DependencyModel(
            earlyDependencyModel.getDependencyId(),
            now.plusMinutes(1),
            earlyDependencyModel.getTenacityConfiguration(),
            earlyDependencyModel.getUser(),
            earlyDependencyModel.getServiceId());
    final DependencyModel superEarlyModel = new DependencyModel(
            earlyDependencyModel.getDependencyId(),
            now.minusMinutes(1),
            earlyDependencyModel.getTenacityConfiguration(),
            earlyDependencyModel.getUser(),
            earlyDependencyModel.getServiceId());
    assertThat(dependencyDB.findLatest(earlyDependencyModel.getDependencyId(), earlyDependencyModel.getServiceId()))
            .isNull();
    assertThat(dependencyDB.insert(earlyDependencyModel)).isEqualTo(1);
    assertThat(dependencyDB.findLatest(earlyDependencyModel.getDependencyId(), earlyDependencyModel.getServiceId()))
            .isEqualTo(earlyDependencyModel);
    assertThat(dependencyDB.insert(laterDependencyModel)).isEqualTo(1);
    assertThat(dependencyDB.findLatest(earlyDependencyModel.getDependencyId(), earlyDependencyModel.getServiceId()))
            .isEqualTo(laterDependencyModel);
    assertThat(dependencyDB.insert(superEarlyModel)).isEqualTo(1);
    assertThat(dependencyDB.findLatest(earlyDependencyModel.getDependencyId(), earlyDependencyModel.getServiceId()))
            .isEqualTo(laterDependencyModel);
}
 
Example 12
private TimedCacheValue(OAuthResponse value, DateTime expiresAt) {
    this.value = value;
    //Setting a buffer of 5 minutes for refresh
    this.expiresAt = expiresAt.minusMinutes(5);
}
 
Example 13
@Override
public DateTime getNextAlarmDate(DateTime executionDate) {
    return executionDate.minusMinutes(ItemsBuilderData.getOneSleepCycleDurationInMinutes());
}
 
Example 14
Source Project: arctic-sea   File: OmEncoderv20Test.java    License: Apache License 2.0 4 votes vote down vote up
protected OmObservation createComplexObservation() {
        DateTime now = new DateTime(DateTimeZone.UTC);
        TimeInstant resultTime = new TimeInstant(now);
        TimeInstant phenomenonTime = new TimeInstant(now);
        TimePeriod validTime = new TimePeriod(now.minusMinutes(5), now.plusMinutes(5));
        OmObservation observation = new OmObservation();
        OmObservationConstellation observationConstellation = new OmObservationConstellation();
        observationConstellation.setFeatureOfInterest(new SamplingFeature(new CodeWithAuthority("feature", CODE_SPACE)));
        OmCompositePhenomenon observableProperty = new OmCompositePhenomenon(PARENT_OBSERVABLE_PROPERTY);
        observableProperty.addPhenomenonComponent(new OmObservableProperty(CHILD_OBSERVABLE_PROPERTY_1));
        observableProperty.addPhenomenonComponent(new OmObservableProperty(CHILD_OBSERVABLE_PROPERTY_2));
        observableProperty.addPhenomenonComponent(new OmObservableProperty(CHILD_OBSERVABLE_PROPERTY_3));
        observableProperty.addPhenomenonComponent(new OmObservableProperty(CHILD_OBSERVABLE_PROPERTY_4));
        observationConstellation.setObservableProperty(observableProperty);
        observationConstellation.setObservationType(OmConstants.OBS_TYPE_COMPLEX_OBSERVATION);
        observationConstellation.addOffering(OFFERING);
        AbstractFeature procedure = new SosProcedureDescriptionUnknownType(PROCEDURE);
//        procedure.setIdentifier(new CodeWithAuthority(PROCEDURE, CODE_SPACE));
        observationConstellation.setProcedure(procedure);
        observation.setObservationConstellation(observationConstellation);
        observation.setParameter(null);
        observation.setResultTime(resultTime);
        observation.setTokenSeparator(TOKEN_SEPERATOR);
        observation.setTupleSeparator(TUPLE_SEPERATOR);
        observation.setValidTime(validTime);
        ComplexValue complexValue = new ComplexValue();
        SweDataRecord sweDataRecord = new SweDataRecord();
        SweQuantity sweQuantity = new SweQuantity();
        sweQuantity.setDefinition(CHILD_OBSERVABLE_PROPERTY_1);
        sweQuantity.setUom("unit");
        sweQuantity.setValue(42.0);
        sweDataRecord.addField(new SweField(CHILD_OBSERVABLE_PROPERTY_1_NAME, sweQuantity));
        SweBoolean sweBoolean = new SweBoolean();
        sweBoolean.setValue(Boolean.TRUE);
        sweBoolean.setDefinition(CHILD_OBSERVABLE_PROPERTY_2);
        sweDataRecord.addField(new SweField(CHILD_OBSERVABLE_PROPERTY_2_NAME, sweBoolean));
        SweCount sweCount = new SweCount();
        sweCount.setDefinition(CHILD_OBSERVABLE_PROPERTY_3);
        sweCount.setValue(42);
        sweDataRecord.addField(new SweField(CHILD_OBSERVABLE_PROPERTY_3_NAME, sweCount));
        SweText sweText = new SweText();
        sweText.setDefinition(CHILD_OBSERVABLE_PROPERTY_4);
        sweText.setValue("42");
        sweDataRecord.addField(new SweField(CHILD_OBSERVABLE_PROPERTY_4_NAME, sweText));
        SweCategory sweCategory = new SweCategory();
        sweCategory.setDefinition(CHILD_OBSERVABLE_PROPERTY_5);
        sweCategory.setCodeSpace(CODE_SPACE);
        sweCategory.setValue("52");
        sweDataRecord.addField(new SweField(CHILD_OBSERVABLE_PROPERTY_5_NAME, sweCategory));
        complexValue.setValue(sweDataRecord);
        observation.setValue(new SingleObservationValue<>(phenomenonTime, complexValue));
        return observation;
    }
 
Example 15
private static Assertion buildSAML2Assertion(
        String baseUrl,
        String subjectNameId,
        String subjectNameIdFormat,
        String subjectNameIdQualifier,
        String idpId,
        String clientKey,
        boolean includeClientKeyAttribute)
{
    // Bootstrap the OpenSAML library
    try {
        DefaultBootstrap.bootstrap();
    } catch (ConfigurationException e) {
    }

    DateTime issueInstant = new DateTime();
    DateTime notOnOrAfter = issueInstant.plusMinutes(10);
    DateTime notBefore = issueInstant.minusMinutes(10);
    
    NameID nameID = (new NameIDBuilder().buildObject());
    if (subjectNameIdFormat.equals("email")) {
        nameID.setFormat(NameIDType.EMAIL);
    } else if (subjectNameIdFormat.equals("unspecified")) {
        nameID.setFormat(NameIDType.UNSPECIFIED);
    } else {
        throw new IllegalArgumentException("subjectNameIdFormat must be 'email' or 'unspecified'.");
    }
    if (subjectNameIdQualifier != null) {
        nameID.setNameQualifier(subjectNameIdQualifier);
    }
    nameID.setValue(subjectNameId);
    
    SubjectConfirmationData subjectConfirmationData = (new SubjectConfirmationDataBuilder().buildObject());
    subjectConfirmationData.setRecipient(baseUrl + ACCESS_TOKEN_URL_PATH);
    subjectConfirmationData.setNotOnOrAfter(notOnOrAfter);
    
    SubjectConfirmation subjectConfirmation = (new SubjectConfirmationBuilder().buildObject());
    subjectConfirmation.setMethod(SubjectConfirmation.METHOD_BEARER);
    subjectConfirmation.setSubjectConfirmationData(subjectConfirmationData);

    Subject subject = (new SubjectBuilder().buildObject());
    subject.setNameID(nameID);
    subject.getSubjectConfirmations().add(subjectConfirmation);
    
    Issuer issuer = (new IssuerBuilder().buildObject());
    issuer.setValue(idpId);
    
    Audience audience = (new AudienceBuilder().buildObject());
    audience.setAudienceURI(SP_ID_JAM);
    
    AudienceRestriction audienceRestriction = (new AudienceRestrictionBuilder().buildObject());
    audienceRestriction.getAudiences().add(audience);
    
    Conditions conditions = (new ConditionsBuilder().buildObject());
    conditions.setNotBefore(notBefore);
    conditions.setNotOnOrAfter(notOnOrAfter);
    conditions.getAudienceRestrictions().add(audienceRestriction);
   
    Assertion assertion = (new AssertionBuilder().buildObject());
    assertion.setID(UUID.randomUUID().toString());
    assertion.setVersion(SAMLVersion.VERSION_20);
    assertion.setIssueInstant(issueInstant);
    assertion.setIssuer(issuer);
    assertion.setSubject(subject);
    assertion.setConditions(conditions);
    
    if (includeClientKeyAttribute) {
        XSString attributeValue = (XSString)Configuration.getBuilderFactory().getBuilder(XSString.TYPE_NAME).buildObject(AttributeValue.DEFAULT_ELEMENT_NAME, XSString.TYPE_NAME);
        attributeValue.setValue(clientKey);

        Attribute attribute = (new AttributeBuilder().buildObject());
        attribute.setName("client_id");
        attribute.getAttributeValues().add(attributeValue);

        AttributeStatement attributeStatement = (new AttributeStatementBuilder().buildObject());
        attributeStatement.getAttributes().add(attribute);
        assertion.getAttributeStatements().add(attributeStatement);
    }

    return assertion;
}
 
Example 16
public static String buildSignedSAML2Assertion(
    final String idpId,
    final String destinationUri,
    
    final String subjectNameId,
    final String subjectNameIdFormat,
    final String subjectNameIdQualifier,

    final PrivateKey idpPrivateKey,
    final X509Certificate idpCertificate,
    final String spJamId,
    final Map<String, List<Object>> attributes) throws Exception {
            
    // Bootstrap the OpenSAML library
    try {
        DefaultBootstrap.bootstrap();
    } catch (ConfigurationException e) {
        
    }

    DateTime issueInstant = new DateTime();
    DateTime notOnOrAfter = issueInstant.plusMinutes(10);
    DateTime notBefore = issueInstant.minusMinutes(10);
    
    NameID nameID = makeEmailFormatName(subjectNameId, subjectNameIdFormat, subjectNameIdQualifier);
    
    SubjectConfirmationData subjectConfirmationData = (new SubjectConfirmationDataBuilder().buildObject());
    subjectConfirmationData.setRecipient(destinationUri);
    subjectConfirmationData.setNotOnOrAfter(notOnOrAfter);
    
    SubjectConfirmation subjectConfirmation = (new SubjectConfirmationBuilder().buildObject());
    subjectConfirmation.setMethod(SubjectConfirmation.METHOD_BEARER);
    subjectConfirmation.setSubjectConfirmationData(subjectConfirmationData);

    Subject subject = (new SubjectBuilder().buildObject());
    subject.setNameID(nameID);
    subject.getSubjectConfirmations().add(subjectConfirmation);
    
    Issuer issuer = (new IssuerBuilder().buildObject());
    issuer.setValue(idpId);
    
    Audience audience = (new AudienceBuilder().buildObject());
    audience.setAudienceURI(spJamId);
    
    AudienceRestriction audienceRestriction = (new AudienceRestrictionBuilder().buildObject());
    audienceRestriction.getAudiences().add(audience);
    
    Conditions conditions = (new ConditionsBuilder().buildObject());
    conditions.setNotBefore(notBefore);
    conditions.setNotOnOrAfter(notOnOrAfter);
    conditions.getAudienceRestrictions().add(audienceRestriction);
   
    Assertion assertion = (new AssertionBuilder().buildObject());
    assertion.setID(UUID.randomUUID().toString());
    assertion.setVersion(SAMLVersion.VERSION_20);
    assertion.setIssueInstant(issueInstant);
    assertion.setIssuer(issuer);
    assertion.setSubject(subject);
    assertion.setConditions(conditions);

    return signAssertion(assertion, idpPrivateKey);
}
 
Example 17
Source Project: spork   File: AugmentBaseDataVisitor.java    License: Apache License 2.0 4 votes vote down vote up
Object GetSmallerValue(Object v) {
    byte type = DataType.findType(v);

    if (type == DataType.BAG || type == DataType.TUPLE
            || type == DataType.MAP)
        return null;

    switch (type) {
    case DataType.CHARARRAY:
        String str = (String) v;
        if (str.length() > 0)
            return str.substring(0, str.length() - 1);
        else
            return null;
    case DataType.BYTEARRAY:
        DataByteArray data = (DataByteArray) v;
        if (data.size() > 0)
            return new DataByteArray(data.get(), 0, data.size() - 1);
        else
            return null;
    case DataType.INTEGER:
        return Integer.valueOf((Integer) v - 1);
    case DataType.LONG:
        return Long.valueOf((Long) v - 1);
    case DataType.FLOAT:
        return Float.valueOf((Float) v - 1);
    case DataType.DOUBLE:
        return Double.valueOf((Double) v - 1);
    case DataType.BIGINTEGER:
        return ((BigInteger)v).subtract(BigInteger.ONE);
    case DataType.BIGDECIMAL:
        return ((BigDecimal)v).subtract(BigDecimal.ONE);
    case DataType.DATETIME:
        DateTime dt = (DateTime) v;
        if (dt.getMillisOfSecond() != 0) {
            return dt.minusMillis(1);
        } else if (dt.getSecondOfMinute() != 0) {
            return dt.minusSeconds(1);
        } else if (dt.getMinuteOfHour() != 0) {
            return dt.minusMinutes(1);
        } else if (dt.getHourOfDay() != 0) {
            return dt.minusHours(1);
        } else {
            return dt.minusDays(1);
        }
    default:
        return null;
    }

}
 
Example 18
private Calendar getClassCalendar(User user, DateTime validity, HttpServletRequest request) {

        List<EventBean> allEvents = getClasses(user);
        String url = CoreConfiguration.getConfiguration().applicationUrl() + "/login";
        EventBean event =
                new EventBean("Renovar a chave do calendario.", validity.minusMinutes(30), validity.plusMinutes(30), false, null,
                        url, "A sua chave de sincronização do calendario vai expirar. Diriga-se ao Fénix para gerar nova chave");

        allEvents.add(event);

        return CalendarFactory.createCalendar(allEvents);

    }
 
Example 19
@Test
public void subtract_minutes_from_date_in_java_with_joda () {
	
	DateTime newYearsDay = new DateTime(2013, 1, 1, 0, 0, 0, 0);
	DateTime newYearsEve = newYearsDay.minusMinutes(1);

	DateTimeFormatter fmt = DateTimeFormat.forPattern("MM/dd/yyyy HH:mm:ss z");
	
	logger.info(newYearsDay.toString(fmt));
	logger.info(newYearsEve.toString(fmt));

	assertTrue(newYearsEve.isBefore(newYearsDay));
}
 
Example 20
private Calendar getExamsCalendar(User user, DateTime validity, HttpServletRequest request) {

        List<EventBean> allEvents = getExams(user);

        String url = CoreConfiguration.getConfiguration().applicationUrl() + "/login";
        EventBean event =
                new EventBean("Renovar a chave do calendario.", validity.minusMinutes(30), validity.plusMinutes(30), false, null,
                        url, "A sua chave de sincronização do calendario vai expirar. Diriga-se ao Fénix para gerar nova chave");

        allEvents.add(event);

        return CalendarFactory.createCalendar(allEvents);

    }