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

The following examples show how to use org.joda.time.DateTime#plusMinutes() . 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
@Override
protected byte[] getBytes() throws Exception {
    List<ThreadNum> threadNums = Lists.newArrayList();

    DateTime time = start;
    while (!time.isAfter(end)) {
        String timestamp = DateUtils.TIME_FORMATTER.print(time);
        int threadNum = getThreadNum(timestamp);
        if (threadNum > 0) {
            threadNums.add(new ThreadNum(timestamp, threadNum));
        }
        time = time.plusMinutes(1);
    }

    Map<String, Object> map = Maps.newHashMap();

    map.put("type", "threadNum");
    map.put("threadNums", threadNums);
    map.put("start", DateUtils.TIME_FORMATTER.print(start));
    map.put("end", DateUtils.TIME_FORMATTER.print(end));
    return JacksonSerializer.serializeToBytes(map);
}
 
Example 2
@Test
public void testAvailabilityCompress() throws Exception {
    long now = triggerTime;

    DateTime start = DateTimeService.getTimeSlice(new DateTime(now, DateTimeZone.UTC).minusHours(2),
            Duration.standardHours(2)).plusMinutes(30);
    DateTime end = start.plusMinutes(20);
    String tenantId = nextTenantId() + now;

    MetricId<AvailabilityType> mId = new MetricId<>(tenantId, AVAILABILITY, "m3");

    doAction(() -> metricsService.createTenant(new Tenant(tenantId), false));

    Metric<AvailabilityType> m1 = new Metric<>(mId, asList(
            new DataPoint<>(start.getMillis(), AvailabilityType.UP),
            new DataPoint<>(start.plusMinutes(2).getMillis(), AvailabilityType.DOWN),
            new DataPoint<>(start.plusMinutes(4).getMillis(), AvailabilityType.DOWN),
            new DataPoint<>(end.getMillis(), AvailabilityType.UP)));

    testCompressResults(AVAILABILITY, m1, start);
}
 
Example 3
@Override
protected void respond() {
	Request r = getCalendar().getRequest();

	String sid = r.getRequestParameters().getParameterValue(SOURCE_ID).toString();
	DateTime start = new DateTime(r.getRequestParameters().getParameterValue("start").toLong());
	DateTime end = new DateTime(r.getRequestParameters().getParameterValue("end").toLong());

	if (getCalendar().getConfig().isIgnoreTimezone()) {
		// Convert to same DateTime in local time zone.
		int remoteOffset = -r.getRequestParameters().getParameterValue("timezoneOffset").toInt();
		int localOffset = DateTimeZone.getDefault().getOffset(null) / 60000;
		int minutesAdjustment = remoteOffset - localOffset;
		start = start.plusMinutes(minutesAdjustment);
		end = end.plusMinutes(minutesAdjustment);
	}
	EventSource source = getCalendar().getEventManager().getEventSource(sid);
	EventProvider provider = source.getEventProvider();
	String response = getCalendar().toJson(provider.getEvents(start, end));

	getCalendar().getRequestCycle().scheduleRequestHandlerAfterCurrent(
		new TextRequestHandler("application/json", "UTF-8", response));

}
 
Example 4
Source Project: bateman   File: QuoteCollectionTest.java    License: MIT License 6 votes vote down vote up
public void testConvertQuoteToTimeSeries() throws Exception {
    DateTime open = new DateTime();
    DateTime later = open.plusMinutes(1);
    List<Quote> quotes = Arrays.asList(new Quote(open, 60, new BigDecimal(1.0), new BigDecimal(1.2), new BigDecimal(0.9), new BigDecimal(1.1), 42),
            new Quote(later, 60, new BigDecimal(1.3), new BigDecimal(1.8), new BigDecimal(0.7), new BigDecimal(1.5), 43));

    QuoteCollection collection = new QuoteCollection();
    TreeMap<DateTime, BigDecimal> prices = new TreeMap<DateTime, BigDecimal>();
    prices.put(open, BigDecimal.ONE);
    prices.put(later, new BigDecimal(1.3));

    TimeSeries expResult = new TimeSeries(prices);
    TimeSeries result = collection.convertQuoteToTimeSeries(quotes);

    assertEquals(expResult.getPrices().get(open), result.getPrices().get(open));
    assertEquals(expResult.getPrices().get(later), result.getPrices().get(later));
}
 
Example 5
/**
 * Gets the interval date time.
 *
 * @param curr the curr
 * @param type the type
 * @param interval the interval
 * @return the interval date time
 */
protected static DateTime plusDateTime(DateTime curr, DateType type, int interval) {
    DateTime result = curr;
    if (DateType.YEAR.equals(type)) {
        result = curr.plusYears(interval);
    } else if (DateType.MONTH.equals(type)) {
        result = curr.plusMonths(interval);
    } else if (DateType.WEEK.equals(type)) {
        result = curr.plusWeeks(interval);
    } else if (DateType.DAY.equals(type)) {
        result = curr.plusDays(interval);
    } else if (DateType.HOUR.equals(type)) {
        result = curr.plusHours(interval);
    } else if (DateType.MINUTE.equals(type)) {
        result = curr.plusMinutes(interval);
    } else if (DateType.SECOND.equals(type)) {
        result = curr.plusSeconds(interval);
    }
    return result;
}
 
Example 6
@Override
protected void respond(final AjaxRequestTarget target) {
  final Request r = getCalendar().getRequest();

  DateTime start = new DateTime(r.getRequestParameters().getParameterValue("startDate").toLong());
  DateTime end = new DateTime(r.getRequestParameters().getParameterValue("endDate").toLong());

  if (ignoreTimezone) {
    // Convert to same DateTime in local time zone.
    final int remoteOffset = -r.getRequestParameters().getParameterValue("timezoneOffset").toInt();
    final int localOffset = DateTimeZone.getDefault().getOffset(null) / 60000;
    final int minutesAdjustment = remoteOffset - localOffset;
    start = start.plusMinutes(minutesAdjustment);
    end = end.plusMinutes(minutesAdjustment);
  }
  final boolean allDay = r.getRequestParameters().getParameterValue("allDay").toBoolean();
  onSelect(new SelectedRange(start, end, allDay), new CalendarResponse(getCalendar(), target));

}
 
Example 7
@Test
public void testCounterCompress() throws Exception {
    long now = triggerTime;

    DateTime start = DateTimeService.getTimeSlice(new DateTime(now, DateTimeZone.UTC).minusHours(2),
            Duration.standardHours(2)).plusMinutes(30);
    DateTime end = start.plusMinutes(20);
    String tenantId = nextTenantId() + now;

    MetricId<Long> mId = new MetricId<>(tenantId, COUNTER, "m2");

    doAction(() -> metricsService.createTenant(new Tenant(tenantId), false));

    Metric<Long> m1 = new Metric<>(mId, asList(
            new DataPoint<>(start.getMillis(), 1L),
            new DataPoint<>(start.plusMinutes(2).getMillis(), 2L),
            new DataPoint<>(start.plusMinutes(4).getMillis(), 3L),
            new DataPoint<>(end.getMillis(), 4L)));

    testCompressResults(COUNTER, m1, start);
}
 
Example 8
Source Project: blueflood   File: DateTimeParser.java    License: Apache License 2.0 5 votes vote down vote up
private DateTime updateDateTimeWithOffset(DateTime baseDateTime) {
    if (offset.equals(""))
        return baseDateTime;
    Pattern p = Pattern.compile("(-?\\d*)([a-z]*)");
    Matcher m = p.matcher(offset);
    if (!m.matches())
        return baseDateTime;

    int count = Integer.parseInt(m.group(1));
    String unit = m.group(2);

    DateTime dateTimeWithOffset = baseDateTime;
    if (unit.startsWith("s"))
        dateTimeWithOffset = baseDateTime.plusSeconds(count);
    else if (unit.startsWith("min"))
        dateTimeWithOffset = baseDateTime.plusMinutes(count);
    else if (unit.startsWith("h"))
        dateTimeWithOffset = baseDateTime.plusHours(count);
    else if (unit.startsWith("d"))
        dateTimeWithOffset = baseDateTime.plusDays(count);
    else if (unit.startsWith("mon"))
        dateTimeWithOffset = baseDateTime.plusMonths(count);
    else if (unit.startsWith("y"))
        dateTimeWithOffset = baseDateTime.plusYears(count);

    return dateTimeWithOffset;
}
 
Example 9
@Test
public void addMetadataToGaugeRawData() throws Exception {
    DateTime start = now();
    DateTime end = start.plusMinutes(16);
    String tenantId = "tenant-1";

    Metric<Double> metric = new Metric<>(new MetricId<>(tenantId, GAUGE, "metric-1"), asList(
            new DataPoint<>(start.getMillis(), 1.23),
            new DataPoint<>(start.plusMinutes(2).getMillis(), 1.234),
            new DataPoint<>(start.plusMinutes(4).getMillis(), 1.234),
            new DataPoint<>(end.getMillis(), 1.234)
    ));

    doAction(() -> dataAccess.insertData(Observable.just(metric)).doOnError(Throwable::printStackTrace));

    Observable<Row> observable = dataAccess.findTempData(new MetricId<>("tenant-1", GAUGE, "metric-1"),
            start.getMillis(), end.getMillis(), 0, Order.DESC, DEFAULT_PAGE_SIZE);
    List<DataPoint<Double>> actual = ImmutableList.copyOf(observable
            .map(Functions::getTempGaugeDataPoint)
            .toBlocking()
            .toIterable());

    List<DataPoint<Double>> expected = asList(
        new DataPoint<>(start.plusMinutes(4).getMillis(), 1.234),
        new DataPoint<>(start.plusMinutes(2).getMillis(), 1.234),
        new DataPoint<>(start.getMillis(), 1.23)
    );

    assertEquals(actual, expected, "The data does not match the expected values");
}
 
Example 10
Source Project: liteflow   File: TimeExpressionUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
     * 按某个时间单位添加时间
     * @param dateTime
     * @param n
     * @param timeUnit
     * @return
     */
    public static DateTime calculateTime(DateTime dateTime, int n, TimeUnit timeUnit) {

        DateTime addedDateTime = null;
        switch (timeUnit){
//            case SECOND:
//                addedDateTime = dateTime.plusSeconds(n);
//                break;
            case MINUTE:
                addedDateTime = dateTime.plusMinutes(n);
                break;
            case HOUR:
                addedDateTime = dateTime.plusHours(n);
                break;
            case DAY:
                addedDateTime = dateTime.plusDays(n);
                break;
            case WEEK:
                addedDateTime = dateTime.plusWeeks(n);
                break;
            case MONTH:
                addedDateTime = dateTime.plusMonths(n);
                break;
            case YEAR:
                addedDateTime = dateTime.plusYears(n);
                break;
        }

        return addedDateTime;
    }
 
Example 11
Source Project: sdk-rest   File: RestApiSession.java    License: MIT License 5 votes vote down vote up
private void updateDateTimeBhRestTokenWillExpire() {
	// set the DateTime the session will expire, subtracting one minute to be on the safe side.
	DateTime timeToExpire = getNow();
	int sessionMinutesToLive = Integer.valueOf(restCredentials.getRestSessionMinutesToLive());
	if (sessionMinutesToLive > MAX_TTL) {
		sessionMinutesToLive = MAX_TTL;
	}
	timeToExpire = timeToExpire.plusMinutes(sessionMinutesToLive - 1);
	this.dateTimeBhRestTokenWillExpire = timeToExpire;
}
 
Example 12
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 13
Source Project: hawkular-metrics   File: TagsITest.java    License: Apache License 2.0 4 votes vote down vote up
@Test
public void addTaggedGaugeDataPoints() throws Exception {
    DateTime start = now().minusMinutes(30);
    DateTime end = start.plusMinutes(20);
    String tenantId = "tagged-data-points";

    Metric<Double> metric = new Metric<>(new MetricId<>(tenantId, GAUGE, "G1"), asList(
            new DataPoint<>(start.plusMinutes(4).getMillis(), 1.1, ImmutableMap.of("x", "1")),
            new DataPoint<>(start.plusMinutes(2).getMillis(), 2.2, ImmutableMap.of("x", "2", "y", "5")),
            new DataPoint<>(start.getMillis(), 3.4)));

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

    Observable<DataPoint<Double>> data = metricsService.findDataPoints(new MetricId<>(tenantId, GAUGE, "G1"),
            start.getMillis(), end.getMillis(), 0, Order.ASC);
    List<DataPoint<Double>> actual = toList(data);
    List<DataPoint<Double>> expected = asList(
            new DataPoint<>(start.getMillis(), 3.4),
            new DataPoint<>(start.plusMinutes(2).getMillis(), 2.2, ImmutableMap.of("x", "2", "y", "5")),
            new DataPoint<>(start.plusMinutes(4).getMillis(), 1.1, ImmutableMap.of("x", "1")));

    assertEquals(actual, expected, "The tagged data does not match the expected values");
    assertMetricIndexMatches(tenantId, GAUGE, singletonList(new Metric<>(metric.getMetricId(),
            metric.getDataPoints(), 7)));

    data = metricsService.findDataPoints(new MetricId<>(tenantId, GAUGE, "G1"), start.getMillis(),
            end.getMillis(), 1, Order.ASC);
    actual = toList(data);
    expected = singletonList(new DataPoint<>(start.getMillis(), 3.4));

    assertEquals(actual, expected, "The tagged data does not match when limiting the number of data points");

    data = metricsService.findDataPoints(new MetricId<>(tenantId, GAUGE, "G1"), start.getMillis(),
            end.getMillis(), 0, Order.DESC);
    actual = toList(data);
    expected = asList(
            new DataPoint<>(start.plusMinutes(4).getMillis(), 1.1, ImmutableMap.of("x", "1")),
            new DataPoint<>(start.plusMinutes(2).getMillis(), 2.2, ImmutableMap.of("x", "2", "y", "5")),
            new DataPoint<>(start.getMillis(), 3.4));

    assertEquals(actual, expected, "The tagg data does not match when the order is DESC");

    data = metricsService.findDataPoints(new MetricId<>(tenantId, GAUGE, "G1"), start.getMillis(),
            end.getMillis(), 1, Order.DESC);
    actual = toList(data);
    expected = singletonList(new DataPoint<>(start.plusMinutes(4).getMillis(), 1.1, ImmutableMap.of("x", "1")));

    assertEquals(actual, expected, "The tagged data does not match when the order is DESC and there is a limit");
}
 
Example 14
private static DateTime getHalfOfTenRound(DateTime dt) {
    return dt.plusMinutes(getDifferenceBetweenMinuteAndHalfOfTen(dt.getMinuteOfHour()));
}
 
Example 15
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 16
Source Project: spork   File: AugmentBaseDataVisitor.java    License: Apache License 2.0 4 votes vote down vote up
Object GetLargerValue(Object v) {
    byte type = DataType.findType(v);

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

    switch (type) {
    case DataType.CHARARRAY:
        return (String) v + "0";
    case DataType.BYTEARRAY:
        String str = ((DataByteArray) v).toString();
        str = str + "0";
        return new DataByteArray(str);
    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).add(BigInteger.ONE);
    case DataType.BIGDECIMAL:
        return ((BigDecimal)v).add(BigDecimal.ONE);
    case DataType.DATETIME:
        DateTime dt = (DateTime) v;
        if (dt.getMillisOfSecond() != 0) {
            return dt.plusMillis(1);
        } else if (dt.getSecondOfMinute() != 0) {
            return dt.plusSeconds(1);
        } else if (dt.getMinuteOfHour() != 0) {
            return dt.plusMinutes(1);
        } else if (dt.getHourOfDay() != 0) {
            return dt.plusHours(1);
        } else {
            return dt.plusDays(1);
        }
    default:
        return null;
    }
}
 
Example 17
@Override
public boolean doCommand(GuildMessageReceivedEvent message, BotContext context, String content) {
    try {
        DateTime date = null;
        String reminder = null;
        Matcher m = PATTERN.matcher(content);
        if (m.find()) {
            date = getFormatter(context).parseDateTime(String.format("%s %s", m.group(1), m.group(2)));
            reminder = m.group(3);
            if (DateTime.now().isAfter(date)) {
                messageService.onError(message.getChannel(), "discord.command.remind.error.future");
                return fail(message);
            }
        }

        String keyWord = messageService.getMessage("discord.command.remind.keyWord");
        m = Pattern.compile(String.format(RELATIVE_PATTERN_FORMAT, keyWord)).matcher(content);
        if (m.find()) {
            Long millis = TimeSequenceParser.parseFull(m.group(1));
            reminder = m.group(2);
            if (millis != null && StringUtils.isNotEmpty(reminder)) {
                date = DateTime.now().plus(millis);
            }
        }

        if (date != null && reminder != null) {
            createReminder(message.getChannel(), message.getMember(), reminder, date.toDate());
            return ok(message, "discord.command.remind.done");
        }
    } catch (IllegalArgumentException e) {
        // fall down
    }

    String prefix = context.getConfig() != null ? context.getConfig().getPrefix() : commonProperties.getDiscord().getDefaultPrefix();

    String remindCommand = messageService.getMessageByLocale("discord.command.remind.key",
            context.getCommandLocale());

    DateTime current = DateTime.now();
    current = current.plusMinutes(1);
    EmbedBuilder builder = messageService.getBaseEmbed();
    builder.setTitle(messageService.getMessage("discord.command.remind.help.title"));
    builder.addField(
            messageService.getMessage("discord.command.remind.help.field1.title",
                    CommonUtils.getUTCOffset(context.getTimeZone())),
            messageService.getMessage("discord.command.remind.help.field1.value", prefix, remindCommand,
                    getFormatter(context).print(current)), false);
    builder.addField(
            messageService.getMessage("discord.command.remind.help.field2.title"),
            messageService.getMessage("discord.command.remind.help.field2.value", prefix, remindCommand),
            false);
    messageService.sendMessageSilent(message.getChannel()::sendMessage, builder.build());
    return false;
}
 
Example 18
@Test
public void testJobFuture() throws Exception {
  final DateTime now = new DateTime().withMillisOfSecond(0)
    .withSecondOfMinute(0).withZone(DateTimeZone.UTC);

  DateTime t1 = now.plusHours(1);
  JobSpec job1 = getTestJob("should be first");
  job1.setCronString(String.format("%d %d * * *",
                                   t1.getMinuteOfHour(),
                                   t1.getHourOfDay()));
  job1.setId(1L);

  JobSpec job2 = getTestJob("should be second");
  DateTime t2 = t1.plusMinutes(59);
  job2.setCronString(String.format("%d %d * * *",
                                   t2.getMinuteOfHour(),
                                   t2.getHourOfDay()));
  job2.setId(2L);

  List<JobSpec> jobs = new ArrayList<>();
  jobs.add(job2);
  jobs.add(job1);

  when(jobDao.getJobs()).thenReturn(jobs);

  List<FutureRunInfo> expected = new ArrayList<>();
  FutureRunInfo fri1 =
    new FutureRunInfo(job1.getName(),
      ChronosController.calcNextRunTime(now, job1));
  FutureRunInfo fri2 =
    new FutureRunInfo(job2.getName(),
      ChronosController.calcNextRunTime(now, job2));
  expected.add(fri1);
  expected.add(fri2);

  FutureRunInfo fri3 =
    new FutureRunInfo(job1.getName(),
      ChronosController.calcNextRunTime(fri2.getTime(), job1));
  FutureRunInfo fri4 =
    new FutureRunInfo(job2.getName(),
      ChronosController.calcNextRunTime(fri2.getTime(), job2));
  expected.add(fri3);
  expected.add(fri4);

  int limit = 4;
  assertEquals(expected, controller.getJobFuture(null, limit));
  MockHttpServletRequestBuilder jobsFutureReq =
    get(String.format("/api/jobs/future?limit=%d", limit));
  mockMvc.perform(jobsFutureReq)
    .andExpect(content().string(OM.writeValueAsString(expected)))
    .andExpect(status().isOk());

  when(jobDao.getJob(job1.getId())).thenReturn(job1);
  List<FutureRunInfo> expectedId = new ArrayList<>();
  expectedId.add(fri1);
  expectedId.add(fri3);

  limit = 2;
  MockHttpServletRequestBuilder jobsFutureIdReq =
    get(String.format("/api/jobs/future?limit=%d&id=%d", limit, job1.getId()));
  mockMvc.perform(jobsFutureIdReq)
    .andExpect(content().string(OM.writeValueAsString(expectedId)))
    .andExpect(status().isOk());
}
 
Example 19
@Test
public void addAvailabilityForMultipleMetrics() throws Exception {
    DateTime start = now().minusMinutes(10);
    DateTime end = start.plusMinutes(8);
    String tenantId = "test-tenant";

    metricsService.createTenant(new Tenant(tenantId), false).toBlocking().lastOrDefault(null);

    Metric<AvailabilityType> m1 = new Metric<>(new MetricId<>(tenantId, AVAILABILITY, "m1"), asList(
            new DataPoint<>(start.plusSeconds(10).getMillis(), UP),
            new DataPoint<>(start.plusSeconds(20).getMillis(), DOWN)));
    Metric<AvailabilityType> m2 = new Metric<>(new MetricId<>(tenantId, AVAILABILITY, "m2"), asList(
            new DataPoint<>(start.plusSeconds(15).getMillis(), DOWN),
            new DataPoint<>(start.plusSeconds(30).getMillis(), UP)));
    Metric<AvailabilityType> m3 = new Metric<>(new MetricId<>(tenantId, AVAILABILITY, "m3"));

    doAction(() -> metricsService.addDataPoints(AVAILABILITY, Observable.just(m1, m2, m3)));

    List<DataPoint<AvailabilityType>> actual = metricsService.findDataPoints(m1.getMetricId(),
            start.getMillis(), end.getMillis(), 0, Order.ASC).toList().toBlocking().last();
    assertEquals(actual, m1.getDataPoints(), "The availability data does not match expected values");

    actual = metricsService.findDataPoints(m2.getMetricId(), start.getMillis(), end.getMillis(), 0, Order.ASC)
            .toList().toBlocking().last();
    assertEquals(actual, m2.getDataPoints(), "The availability data does not match expected values");

    actual = metricsService.findDataPoints(m3.getMetricId(), start.getMillis(), end.getMillis(), 0, Order.DESC)
            .toList().toBlocking().last();
    assertEquals(actual.size(), 0, "Did not expect to get back results since there is no data for " + m3);

    Metric<AvailabilityType> m4 = new Metric<>(new MetricId<>(tenantId, AVAILABILITY, "m4"), emptyMap(), 24,
            asList(
                    new DataPoint<>(start.plusMinutes(2).getMillis(), UP),
                    new DataPoint<>(end.plusMinutes(2).getMillis(), UP)));
    doAction(() -> metricsService.createMetric(m4, false));

    doAction(() -> metricsService.addDataPoints(AVAILABILITY, Observable.just(m4)));

    actual = metricsService.findDataPoints(m4.getMetricId(), start.getMillis(), end.getMillis(), 0, Order.DESC)
            .toList().toBlocking().last();
    Metric<AvailabilityType> expected = new Metric<>(m4.getMetricId(), emptyMap(), 24,
            singletonList(new DataPoint<>(start.plusMinutes(2).getMillis(), UP)));
    assertEquals(actual, expected.getDataPoints(), "The availability data does not match expected values");

    assertMetricIndexMatches(tenantId, AVAILABILITY, asList(
            new Metric<>(m1.getMetricId(), 7),
            new Metric<>(m2.getMetricId(), 7),
            new Metric<>(m4.getMetricId(), 24)));
}
 
Example 20
Source Project: arctic-sea   File: DateTimeHelper.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * Calculates the expire time for a time object
 *
 * @param start
 *            Time object
 * @return Expire time
 */
public static DateTime calculateExpiresDateTime(DateTime start) {
    return start.plusMinutes(lease);
}