// the following function is used when one wants to use the term structure as of now to calculate
  // market values for future periods (i.e. forward values)
  public double getMarketValue(
      DateTime startDate, DateTime forwardDate, ITermStructure termStructure) {

    int i = 0;
    double marketValue = 0;
    DateTime tempDate = forwardDate.plus(installmentPeriod);
    Duration tempDuration = new Duration(startDate, tempDate);

    while (!isExpired(tempDate)) {
      marketValue +=
          coupon
              / Math.pow(
                  1
                      + termStructure.getRiskFreeRate(
                          convertDurationToPercentageOfAYear(tempDuration)),
                  i);
      i++;
      tempDate = tempDate.plus(installmentPeriod);
      tempDuration = tempDuration.plus(installmentPeriod);
    }
    return quantity
        * (marketValue
            + (coupon + getFaceValue())
                / Math.pow(
                    1
                        + termStructure.getRiskFreeRate(
                            convertDurationToPercentageOfAYear(tempDuration)),
                    i));
  }
  public double getMarketValue(
      DateTime date,
      ITermStructure termStructure) { // todo (cne) add the spread (due to the rating)

    double marketValue = 0;
    int i = 0;
    DateTime tempDate =
        date.plus(installmentPeriod); // todo (cne) check if the coupon occurs immediately of not
    Duration tempDuration = new Duration(date, tempDate);

    while (!isExpired(tempDate)) {
      marketValue +=
          coupon
              / Math.pow(
                  1
                      + termStructure.getRiskFreeRate(
                          convertDurationToPercentageOfAYear(tempDuration)),
                  i);
      i++;
      tempDate = tempDate.plus(installmentPeriod);
      tempDuration = tempDuration.plus(installmentPeriod);
      // int iterationCounter = i;
    }
    // i = iterationCounter;
    return quantity
        * (marketValue
            + (coupon + getFaceValue())
                / Math.pow(
                    1
                        + termStructure.getRiskFreeRate(
                            convertDurationToPercentageOfAYear(tempDuration)),
                    i));
  }
  @Test
  public void testGetTicketPrice() {
    User testUser = createUser();
    Event testHighRatedEvent = createEvent();
    Event testEvent = createEvent();
    Auditorium testAuditorium = createAuditorium();

    eventService.assignAuditoriumToEvent(testHighRatedEvent, TESTED_DATE_2, testAuditorium);

    Assert.assertEquals(
        bookingService.getTicketPrice(testHighRatedEvent, TESTED_DATE_2, 10, testUser),
        HIGH_RATED_EVENT_PRICE,
        0);
    Assert.assertEquals(
        bookingService.getTicketPrice(testHighRatedEvent, TESTED_DATE_2, 1, testUser),
        HIGH_RATEDEVENT_PRICE_VIP_SEAT,
        0);

    testEvent.setRating(EventRating.MID);
    eventService.assignAuditoriumToEvent(testEvent, TESTED_DATE_2.plus(1), testAuditorium);

    Assert.assertEquals(
        bookingService.getTicketPrice(testEvent, TESTED_DATE_2.plus(1), 10, testUser),
        EVENT_BASE_PRICE,
        0);
    Assert.assertEquals(
        bookingService.getTicketPrice(testEvent, TESTED_DATE_2.plus(1), 1, testUser),
        EVENT_PRICE_VIP_SEAT,
        0);
  }
 /**
  * @deprecated use adjustedIncrementalFactor(double elapsedMonths)
  * @param occurrenceDate
  * @param updateDate
  * @param elapsedMonths
  * @return
  */
 @Deprecated
 public double adjustedIncrementalFactor(
     DateTime occurrenceDate, DateTime updateDate, int elapsedMonths) {
   double originalIncrementalFactor = incrementFactor(nextPayoutIndex(elapsedMonths));
   Integer nextPayoutIndex = nextPayoutIndex(elapsedMonths);
   DateTime patternDateNext = occurrenceDate.plus(cumulativeLapseTime(nextPayoutIndex));
   DateTime patternDateBefore = occurrenceDate.plus(cumulativeLapseTime(nextPayoutIndex - 1));
   double timeFraction =
       Months.monthsBetween(updateDate, patternDateNext).getMonths()
           / (double) Months.monthsBetween(patternDateBefore, patternDateNext).getMonths();
   return originalIncrementalFactor * timeFraction;
 }
  public double BondPriceDiscrete(DateTime date, double r) {
    double bondPrice = 0;
    int i = 0;
    DateTime tempDate = date.plus(installmentPeriod);
    while (!isExpired(tempDate)) {

      bondPrice += coupon / Math.pow(1 + r, i);
      i++;
      tempDate = tempDate.plus(installmentPeriod);
    }
    return quantity * (bondPrice + (coupon + getFaceValue()) / Math.pow(1 + r, i));
  }
Пример #6
0
 private static BinaryOperator<List<Prediction>> linearInterpolation() {
   return (interpolated, input) -> {
     if (input.size() != 1) {
       throw new IllegalArgumentException("expected one element, but got " + input);
     }
     if (interpolated.isEmpty()) {
       interpolated.addAll(input);
       return interpolated;
     }
     Prediction previous = interpolated.get(interpolated.size() - 1);
     Prediction next = input.get(0);
     for (DateTime timestamp = previous.timestamp.plus(PREDICTION_RESOLUTION);
         timestamp.isBefore(next.timestamp);
         timestamp = timestamp.plus(PREDICTION_RESOLUTION)) {
       double totalDuration = new Duration(previous.timestamp, next.timestamp).getMillis();
       double currentDuration = new Duration(previous.timestamp, timestamp).getMillis();
       double proportion = currentDuration / totalDuration;
       int totalChange = next.spacesAvailable - previous.spacesAvailable;
       int currentChange = (int) Math.round(totalChange * proportion);
       int spacesAvailable = previous.spacesAvailable + currentChange;
       interpolated.add(new Prediction(timestamp, spacesAvailable));
     }
     interpolated.add(next);
     return interpolated;
   };
 }
  private void testStartProcess(RuntimeEngine runtime) throws Exception {

    synchronized (
        (SingleSessionCommandService)
            ((CommandBasedStatefulKnowledgeSession) runtime.getKieSession()).getRunner()) {
      UserTransaction ut =
          (UserTransaction) new InitialContext().lookup("java:comp/UserTransaction");
      try {
        ut.begin();
        logger.debug("Starting process on ksession {}", runtime.getKieSession().getIdentifier());
        Map<String, Object> params = new HashMap<String, Object>();
        DateTime now = new DateTime();
        now.plus(1000);

        params.put("x", "R2/" + wait + "/PT1S");
        ProcessInstance processInstance =
            runtime.getKieSession().startProcess("IntermediateCatchEvent", params);
        logger.debug(
            "Started process instance {} on ksession {}",
            processInstance.getId(),
            runtime.getKieSession().getIdentifier());
        ut.commit();
      } catch (Exception ex) {
        ut.rollback();
        throw ex;
      }
    }
  }
  /**
   * Handles the Time.now macro
   *
   * @param tokens list of tokens
   * @param iter iterator used to iterate over the list of tokens
   * @return string containing the interpolated time token
   */
  private static String handleTime(List<String> tokens, Iterator<String> iter) {
    DateTime dt = new DateTime();

    // Add some amount
    if (iter.hasNext()) {
      String operationToken = iter.next();
      if (operationToken.equals("+") || operationToken.equals("-")) {
        if (iter.hasNext()) {
          String quantityToken = iter.next(); // Get the magnitude to
          // add or subtract

          ReadablePeriod period = getTimePeriod(quantityToken);

          if (operationToken.equals("-")) {
            dt = dt.minus(period);
          } else {
            dt = dt.plus(period);
          }
        } else {
          logger.warn("Token '{}' not followed by a quantity", operationToken);
        }
      } else {
        logger.warn("Invalid token '{}', must be operator '+' or '-'", operationToken);
      }
    }

    return DATE_UTIL.formatDateTime(dt);
  }
Пример #9
0
  @Test
  public void test_aggregationBySecond() throws Exception {
    DateTimeZone utc = DateTimeZone.UTC;
    DateTime startDate = new DateTime(2014, 1, 1, 0, 0, 0, 0, utc);
    DateTime endDate = new DateTime(2014, 1, 1, 0, 0, 2, 200, utc);
    ListDataPointGroup group = new ListDataPointGroup("aggregationByDay");

    for (DateTime milliSecond = startDate;
        milliSecond.isBefore(endDate);
        milliSecond = milliSecond.plus(100)) {
      group.addDataPoint(new LongDataPoint(milliSecond.getMillis(), 1L));
    }

    SumAggregator aggregator = new SumAggregator(new DoubleDataPointFactoryImpl());
    aggregator.setSampling(new Sampling(1, TimeUnit.SECONDS));
    aggregator.setAlignSampling(false);

    DataPointGroup dayCount = aggregator.aggregate(group);

    assertThat(dayCount.hasNext(), is(true));
    assertThat(dayCount.next().getLongValue(), is(10L));

    assertThat(dayCount.hasNext(), is(true));
    assertThat(dayCount.next().getLongValue(), is(10L));

    assertThat(dayCount.hasNext(), is(true));
    assertThat(dayCount.next().getLongValue(), is(2L));
    assertThat(dayCount.hasNext(), is(false));
  }
Пример #10
0
  @Test
  public void testTimerStartDateISO() throws Exception {

    byte[] content =
        IoUtils.readBytesFromInputStream(
            this.getClass().getResourceAsStream("/BPMN2-TimerStartDate.bpmn2"));
    String processContent = new String(content, "UTF-8");

    DateTime now = new DateTime(System.currentTimeMillis());
    now = now.plus(2000);

    processContent = processContent.replaceFirst("#\\{date\\}", now.toString());
    Resource resource = ResourceFactory.newReaderResource(new StringReader(processContent));
    resource.setSourcePath("/BPMN2-TimerStartDate.bpmn2");
    resource.setTargetPath("/BPMN2-TimerStartDate.bpmn2");
    KieBase kbase = createKnowledgeBaseFromResources(resource);

    ksession = createKnowledgeSession(kbase);
    final List<Long> list = new ArrayList<Long>();
    ksession.addEventListener(
        new DefaultProcessEventListener() {
          public void afterProcessStarted(ProcessStartedEvent event) {
            list.add(event.getProcessInstance().getId());
          }
        });
    assertEquals(0, list.size());
    Thread.sleep(3000);
    assertEquals(1, list.size());
  }
Пример #11
0
 public T get() {
   if (_lastUpdated == null || _lastUpdated.plus(_keepForPeriod).isAfter(DateTime.now())) {
     _storedItem = null;
     return null;
   } else {
     return _storedItem;
   }
 }
Пример #12
0
 public DateTime getShiftedTime() {
   DateTime r = new DateTime();
   if (timeShift == null) {
     return r;
   } else {
     return r.plus(timeShift);
   }
 }
Пример #13
0
 @Override
 public Optional<DateTime> createEndTime(OptaSportType sport, DateTime start) {
   Optional<Duration> duration = Optional.fromNullable(DURATION_MAPPING.get(sport));
   if (!duration.isPresent()) {
     return Optional.absent();
   }
   return Optional.of(start.plus(duration.get()));
 }
  public double getDurationDiscrete(DateTime date, ITermStructure termStructure) {

    double numerator = 0;
    double denominator = 0;
    // int numberOfCashFlows = (int) installmentPeriod * numberOfPeriods(installmentPeriod, date,
    // maturityDate);
    int i = 0;
    DateTime tempDate = date.plus(installmentPeriod);
    Duration tempDuration = new Duration(date, tempDate);
    while (!isExpired(tempDate)) {

      numerator +=
          i
              * coupon
              / Math.pow(
                  1
                      + termStructure.getRiskFreeRate(
                          convertDurationToPercentageOfAYear(tempDuration)),
                  i);
      denominator +=
          coupon
              / Math.pow(
                  1
                      + termStructure.getRiskFreeRate(
                          convertDurationToPercentageOfAYear(tempDuration)),
                  i);
      i++;
      tempDate = tempDate.plus(installmentPeriod);
      tempDuration = tempDuration.plus(installmentPeriod);
    }
    return (numerator
            + i
                * (coupon + getFaceValue())
                / Math.pow(
                    1
                        + termStructure.getRiskFreeRate(
                            convertDurationToPercentageOfAYear(tempDuration)),
                    i))
        / (denominator
            + (coupon + getFaceValue())
                / Math.pow(
                    1
                        + termStructure.getRiskFreeRate(
                            convertDurationToPercentageOfAYear(tempDuration)),
                    i));
  }
  @Override
  public AuthorizationRequest createAuthorizationRequest(Map<String, String> parameters) {

    String clientId = parameters.get("client_id");
    if (clientId == null) {
      throw new InvalidClientException("A client id must be provided");
    }
    ClientDetails client = clientDetailsService.loadClientByClientId(clientId);

    String requestNonce = parameters.get("nonce");

    // Only process if the user is authenticated. If the user is not authenticated yet, this
    // code will be called a second time once the user is redirected from the login page back
    // to the auth endpoint.
    Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();

    if (requestNonce != null && principal != null && principal instanceof User) {

      // Check request nonce for reuse
      Collection<Nonce> clientNonces = nonceService.getByClientId(client.getClientId());
      for (Nonce nonce : clientNonces) {
        String nonceVal = nonce.getValue();
        if (nonceVal.equals(requestNonce)) {
          throw new NonceReuseException(client.getClientId(), nonce);
        }
      }

      // Store nonce
      Nonce nonce = new Nonce();
      nonce.setClientId(client.getClientId());
      nonce.setValue(requestNonce);
      DateTime now = new DateTime(new Date());
      nonce.setUseDate(now.toDate());
      DateTime expDate = now.plus(nonceStorageDuration);
      Date expirationJdkDate = expDate.toDate();
      nonce.setExpireDate(expirationJdkDate);

      nonceService.save(nonce);
    }

    Set<String> scopes = OAuth2Utils.parseParameterList(parameters.get("scope"));
    if ((scopes == null || scopes.isEmpty())) {
      // TODO: do we want to allow default scoping at all?
      // If no scopes are specified in the incoming data, it is possible to default to the client's
      // registered scopes, but minus the "openid" scope. OpenID Connect requests MUST have the
      // "openid" scope.
      Set<String> clientScopes = client.getScope();
      if (clientScopes.contains("openid")) {
        clientScopes.remove("openid");
      }
      scopes = clientScopes;
    }
    DefaultAuthorizationRequest request =
        new DefaultAuthorizationRequest(
            parameters, Collections.<String, String>emptyMap(), clientId, scopes);
    request.addClientDetails(client);
    return request;
  }
 @Override
 public TimeInstant createScenario(Session session) throws OwsExceptionReport {
   Transaction transaction = null;
   try {
     DateTime ref = new DateTime(DateTimeZone.UTC).minusDays(1);
     transaction = session.beginTransaction();
     HibernateObservationBuilder b = getBuilder(session);
     b.createObservation(PI_BEGUN_BY_ID, ref, ref.plus(1));
     b.createObservation(PI_ENDED_BY_ID, ref.minus(1), ref);
     b.createObservation(PI_AFTER_ID, ref.plus(1), ref.plus(2));
     b.createObservation(PI_BEFORE_ID, ref.minus(2), ref.minus(1));
     b.createObservation(PI_CONTAINS_ID, ref.minus(1), ref.plus(1));
     session.flush();
     transaction.commit();
     return new TimeInstant(ref);
   } catch (HibernateException he) {
     if (transaction != null) {
       transaction.rollback();
     }
     throw he;
   }
 }
Пример #17
0
  @Test
  public void test_aggregationByMilliSecond() throws Exception {
    DateTimeZone utc = DateTimeZone.UTC;
    DateTime startDate = new DateTime(2014, 1, 1, 0, 0, 0, 0, utc);
    DateTime endDate = new DateTime(2014, 1, 1, 0, 0, 0, 3, utc);
    ListDataPointGroup group = new ListDataPointGroup("aggregationByDay");

    for (DateTime milliSecond = startDate;
        milliSecond.isBefore(endDate);
        milliSecond = milliSecond.plus(1)) {
      group.addDataPoint(new LongDataPoint(milliSecond.getMillis(), 1L));
      group.addDataPoint(new LongDataPoint(milliSecond.getMillis(), 1L));
    }

    SumAggregator aggregator = new SumAggregator(new DoubleDataPointFactoryImpl());
    aggregator.setSampling(new Sampling(1, TimeUnit.MILLISECONDS));
    aggregator.setAlignSampling(false);
    aggregator.setStartTime(startDate.getMillis());

    DataPointGroup dayCount = aggregator.aggregate(group);

    assertThat(dayCount.hasNext(), is(true));
    DataPoint firstMillis = dayCount.next();
    assertThat(new DateTime(firstMillis.getTimestamp(), utc), equalTo(startDate));
    assertThat(firstMillis.getLongValue(), is(2L));

    assertThat(dayCount.hasNext(), is(true));
    DataPoint secondMillis = dayCount.next();
    assertThat(new DateTime(secondMillis.getTimestamp(), utc), equalTo(startDate.plus(1)));
    assertThat(secondMillis.getLongValue(), is(2L));

    assertThat(dayCount.hasNext(), is(true));
    DataPoint thirdMillis = dayCount.next();
    assertThat(new DateTime(thirdMillis.getTimestamp(), utc), equalTo(startDate.plus(2)));
    assertThat(thirdMillis.getLongValue(), is(2L));

    assertThat(dayCount.hasNext(), is(false));
  }
  @Override
  public AggregateCount getCounts(String name, Interval interval, DateTimeField resolution) {

    DateTime end = interval.getEnd();
    Chronology c = interval.getChronology();
    DurationField resolutionDuration = resolution.getDurationField();

    long[] counts;

    if (resolutionDuration.getUnitMillis() == DateTimeConstants.MILLIS_PER_MINUTE) {
      // Iterate through each hour in the interval and load the minutes for it
      MutableDateTime dt = new MutableDateTime(interval.getStart());
      dt.setRounding(c.hourOfDay());
      Duration step = Duration.standardHours(1);
      List<long[]> hours = new ArrayList<long[]>();
      while (dt.isBefore(end)) {
        hours.add(getMinCountsForHour(name, dt));
        dt.add(step);
      }
      counts =
          MetricUtils.concatArrays(
              hours,
              interval.getStart().getMinuteOfHour(),
              interval.toPeriod().toStandardMinutes().getMinutes() + 1,
              60);

    } else if (resolutionDuration.getUnitMillis() == DateTimeConstants.MILLIS_PER_HOUR) {
      DateTime cursor = new DateTime(c.dayOfMonth().roundFloor(interval.getStart().getMillis()));
      List<long[]> days = new ArrayList<long[]>();
      Duration step = Duration.standardHours(24);
      while (cursor.isBefore(end)) {
        days.add(getHourCountsForDay(name, cursor));
        cursor = cursor.plus(step);
      }

      counts =
          MetricUtils.concatArrays(
              days,
              interval.getStart().getHourOfDay(),
              interval.toPeriod().toStandardHours().getHours() + 1,
              24);

    } else {
      throw new IllegalArgumentException("Only minute or hour resolution is currently supported");
    }
    return new AggregateCount(name, interval, counts, resolution);
  }
Пример #19
0
  public void apply(Document doc, List<Object> values, Span span, DateTime ref) {
    Map params = getParameters();
    String value = (String) params.get("value");
    String diff = (String) params.get("diff");
    String dir = (String) params.get("dir");
    DateTime val = ref;
    if (value != null) {
      value = assignValues(value, values);
      val = new DateTime(value);
    } else if (diff != null) {
      diff = assignValues(diff, values);
      Period period = new Period(diff);

      if (dir == null || dir.equals("plus")) {
        val = ref.plus(period);
      } else if (dir.equals("minus")) {
        val = ref.minus(period);
      }
    } else {
      val = ref;
      // use set_xxx
      for (Map.Entry entry : (Set<Map.Entry>) params.entrySet()) {
        Matcher m = Pattern.compile("set_(.*)").matcher((String) entry.getKey());
        if (m.matches()) {
          String field = assignValues((String) entry.getValue(), values);
          String fieldName = m.group(1);

          if (fieldName.equals("month")) {
            int month = Integer.parseInt(field);
            val = getTimeAnnotator().normalizeMonth(val, month);
          } else if (fieldName.equals("day")) {
            int day = Integer.parseInt(field);
            val = val.withField(DateTimeFieldType.dayOfMonth(), day);
          } else {
            throw new InternalError();
          }
        }
      }
    }

    String formattedDate = formatter.print(val);
    FeatureSet attrs = new FeatureSet();
    attrs.put("VAL", formattedDate);

    doc.annotate("TIMEX2", span, attrs);
  }
Пример #20
0
 protected void actionAdjustment() {
   String result =
       (String) JOptionPane.showInputDialog(this, "Enter an adjustment", "0 00:00:00.000");
   if (result != null && !result.isEmpty()) {
     try {
       Period adjustment = format_short.parsePeriod(result);
       DateTime start = new DateTime();
       DateTime end = start.plus(adjustment);
       TimeSpan ts = new TimeSpan(start, end);
       times.add(ts);
       period = period.plus(adjustment);
       updateTimes();
     } catch (IllegalArgumentException ex) {
       JOptionPane.showMessageDialog(this, ex.toString(), "Error", JOptionPane.ERROR_MESSAGE);
     }
   }
 }
Пример #21
0
  @Test
  public void test1() throws Exception {
    ObjectViews views = this.unmarshal("com/axelor/meta/WSTest.xml", ObjectViews.class);
    List<Action> actions = views.getActions();

    Assert.assertNotNull(actions);
    Assert.assertEquals(4, actions.size());

    MetaStore.resister(views);

    Action action = MetaStore.getAction("data.import.1");
    Map<String, Object> context = Maps.newHashMap();

    DateTime dt = new DateTime();
    dt = dt.plus(Period.days(20));

    context.put("dt", dt);

    ActionHandler handler = createHandler("data.import.1", context);
    action.evaluate(handler);
  }
Пример #22
0
  /**
   * This makes test makes the RangeAggregator do time calculations larger than an int.
   *
   * @throws Exception
   */
  @Test
  public void test_aggregationByMilliSecondOverLongRange() throws Exception {
    DateTimeZone utc = DateTimeZone.UTC;
    DateTime startDate = new DateTime(2014, 1, 1, 0, 0, 0, 0, utc);
    DateTime endDate = new DateTime(2014, 3, 1, 0, 0, 0, 0, utc);
    ListDataPointGroup group = new ListDataPointGroup("aggregationByDay");

    for (DateTime milliSecond = startDate;
        milliSecond.isBefore(endDate);
        milliSecond = milliSecond.plus(10000)) {
      group.addDataPoint(new LongDataPoint(milliSecond.getMillis(), 1L));
      group.addDataPoint(new LongDataPoint(milliSecond.getMillis(), 1L));
    }

    SumAggregator aggregator = new SumAggregator(new DoubleDataPointFactoryImpl());
    aggregator.setSampling(new Sampling(1, TimeUnit.MILLISECONDS));
    aggregator.setAlignSampling(false);
    aggregator.setStartTime(startDate.getMillis());

    DataPointGroup dpg = aggregator.aggregate(group);

    while (dpg.hasNext()) dpg.next();
  }
Пример #23
0
  @Test
  public void periodLimitsAdd() {
    DateTime test = asDate(2011, 4, 12);
    ITimePeriod period1 = new TimeRange(asDate(2011, 4, 20), asDate(2011, 4, 25));
    ITimePeriod period2 = new TimeRange(asDate(2011, 4, 30), (DateTime) null); // 4월 30일 이후

    CalendarDateAdd dateAdd = new CalendarDateAdd();

    // 예외기간을 설정합니다. 4월 20일 ~ 4월25일, 4월 30일 이후
    dateAdd.getExcludePeriods().add(period1);
    dateAdd.getExcludePeriods().add(period2);

    assertThat(dateAdd.add(test, Durations.Day)).isEqualTo(test.plus(Durations.Day));

    // 4월 12일에 8일을 더하면 4월 20일이지만, 20~25일까지 제외되므로, 4월 25일이 된다.
    assertThat(dateAdd.add(test, Durations.days(8))).isEqualTo(period1.getEnd());

    // 4월 12에 20일을 더하면 4월 20~25일을 제외한 후 계산하면 4월 30 이후가 된다. (5월 3일).
    // 하지만 4월 30 이후는 모두 제외되므로 결과값은 null이다.
    assertThat(dateAdd.add(test, Durations.days(20))).isNull();

    assertThat(dateAdd.subtract(test, Durations.days(3))).isEqualTo(test.minus(Durations.days(3)));
  }
Пример #24
0
 private static List<Prediction> normalizeToPredictionWindow(
     DateTime start, List<Prediction> predictions) {
   DateTime end = start.plus(PREDICTION_WINDOW).minus(PREDICTION_RESOLUTION);
   return predictions
       .stream()
       // remove too fine-grained predictions
       .collect(groupByRoundedTimeKeepingNewest()) // -> Map<DateTime, Prediction>
       .values()
       .stream()
       // normalize resolution
       .map(roundTimestampsToPredictionResolution())
       // interpolate too coarse-grained predictions
       .sorted(Comparator.comparing(p -> p.timestamp))
       .map(Collections::singletonList) // 1. wrap values in immutable singleton lists
       .reduce(new ArrayList<>(), linearInterpolation())
       .stream() // 2. mutable ArrayList as accumulator
       // normalize range
       .filter(
           isWithin(
               start,
               end)) // after interpolation because of
                     // PredictionDaoTest.does_linear_interpolation_also_between_values_outside_the_prediction_window
       .collect(toList());
 }
Пример #25
0
 public boolean windowElapsed(WindowName windowName, DateTime milestoneStartDateTime) {
   Period endOffset = getWindowEnd(windowName);
   return !now().isBefore(milestoneStartDateTime.plus(endOffset));
 }
  /* (non-Javadoc)
   * @see com.vmware.identity.samlservice.SamlValidator#validate(java.lang.Object)
   */
  @Override
  public ValidationResult validate(AuthnRequestState t) {
    log.debug("Validating request {}", t);

    ValidationResult vr = null;

    try {
      Validate.notNull(t);

      HttpServletRequest httpRequest = t.getRequest();
      Validate.notNull(httpRequest);

      AuthnRequest request = t.getAuthnRequest();
      Validate.notNull(request);
      Validate.notNull(request.getIssuer());

      IdmAccessor accessor = t.getIdmAccessor();
      Validate.notNull(accessor);
      Validate.notNull(accessor.getTenant());

      // Validate assertion consumer service first, if that is valid, we can send SAML replies
      try {
        boolean validateACSWithMetadata = !this.isRequestSigned(t);
        String acsUrl =
            accessor.getAcsForRelyingParty(
                request.getIssuer().getValue(),
                request.getAssertionConsumerServiceIndex(),
                request.getAssertionConsumerServiceURL(),
                request.getProtocolBinding(),
                validateACSWithMetadata);

        t.setAcsUrl(acsUrl);
      } catch (IllegalStateException e) {
        // set validation result to 400
        log.debug("Caught illegal state exception while Validating {} returning 400", e.toString());
        vr = new ValidationResult(HttpServletResponse.SC_BAD_REQUEST, e.getMessage(), null);
      }

      // Validate ID
      if (vr == null && request.getID() == null) {
        vr = new ValidationResult(OasisNames.REQUESTER);
        log.debug("Validation FAILED - Request ID is missing");
      }

      // Validate version
      if (vr == null) {
        SAMLVersion version = request.getVersion();
        if ((version.getMajorVersion() > Shared.REQUIRED_SAML_VERSION.getMajorVersion())
            || version.getMajorVersion() == Shared.REQUIRED_SAML_VERSION.getMajorVersion()
                && version.getMinorVersion() > Shared.REQUIRED_SAML_VERSION.getMinorVersion()) {
          // version too high
          vr =
              new ValidationResult(
                  OasisNames.VERSION_MISMATCH, OasisNames.REQUEST_VERSION_TOO_HIGH);
          log.debug("Validation FAILED - Version is too high");
        } else if ((version.getMajorVersion() < Shared.REQUIRED_SAML_VERSION.getMajorVersion())
            || version.getMajorVersion() == Shared.REQUIRED_SAML_VERSION.getMajorVersion()
                && version.getMinorVersion() < Shared.REQUIRED_SAML_VERSION.getMinorVersion()) {
          // version too low
          vr =
              new ValidationResult(OasisNames.VERSION_MISMATCH, OasisNames.REQUEST_VERSION_TOO_LOW);
          log.debug("Validation FAILED - Version is too low");
        }
      }

      // Validate IssueInstant only if this is a new request (i.e. it had not pass been validated)
      if (vr == null && !t.isExistingRequest()) {
        DateTime dtPlus = request.getIssueInstant();
        DateTime dtMinus = request.getIssueInstant();
        DateTime instant = new DateTime();
        long clockTolerance = accessor.getClockTolerance();
        if (dtPlus == null) {
          vr = new ValidationResult(OasisNames.REQUESTER);
          log.debug("Validation FAILED - Issue Instant is missing");
        } else {
          dtPlus = dtPlus.plus(clockTolerance);
          dtMinus = dtMinus.minus(clockTolerance);
          // dtPlus must be after now and dtMinus must be before now
          //	in order to satisfy clock tolerance
          if (dtPlus.isBefore(instant) || dtMinus.isAfter(instant)) {
            vr = new ValidationResult(OasisNames.REQUESTER);
            log.debug("Validation FAILED - Issue Instant outside of clock tolerance");
            log.debug("clockTolerance {}", clockTolerance);
            log.debug("now {}", instant);
            log.debug("dtPlus {}", dtPlus.toString());
            log.debug("dtMinus {}", dtMinus.toString());
          }
        }
      }

      // Destination URL skipped, this is already done by OpenSAML when parsing

      // validate scoping if presenet
      if (vr == null) {
        vr = validateScoping(t);
      }

      // signature must NOT be included
      if (vr == null) {
        if (request.getSignature() != null) {
          log.debug("Validation FAILED - Signature MUST NOT be present");
          vr = new ValidationResult(OasisNames.REQUESTER, OasisNames.REQUEST_UNSUPPORTED);
        }
      }

      // ensure that we don't accept unsigned requests if configuration requires signing
      if (vr == null) {

        try {
          boolean mustBeSigned =
              accessor.getAuthnRequestsSignedForRelyingParty(request.getIssuer().getValue());
          this.validateSigning(mustBeSigned, t);
        } catch (IllegalStateException e) {
          // set validation result to request denied
          log.error("Validation FAILED - unsigned request detected, signing required");
          vr = new ValidationResult(OasisNames.RESPONDER, OasisNames.REQUEST_DENIED);
        }
      }

      // validate NameIDPolicy if present
      if (vr == null) {
        NameIDPolicy policy = request.getNameIDPolicy();
        if (policy != null) {
          String format = policy.getFormat();
          if (format != null
              && !format.equals(OasisNames.PERSISTENT)
              && !format.equals(OasisNames.EMAIL_ADDRESS)
              && !format.equals(SAMLNames.IDFORMAT_VAL_UPN.toString())) {
            log.error("Validation FAILED - unknown NameIDPolicy Format");
            vr = new ValidationResult(OasisNames.REQUESTER, OasisNames.INVALID_NAMEID_POLICY);
          }
        }
      }

      // validate conditions
      if (vr == null) {
        Conditions conditions = request.getConditions();
        if (conditions != null) {
          // notBefore processing
          DateTime notBefore = conditions.getNotBefore();
          if (notBefore != null) {
            // no additional validation, we'll use whatever client wants
            t.setStartTime(notBefore.toDate());
          }
          // delegable and renewable conditions
          for (Condition c : conditions.getConditions()) {
            if (c == null) {
              continue;
            }
            if (c instanceof RenewableType) {
              t.setRenewable(true);
            }
            if (c instanceof DelegableType) {
              t.setDelegable(true);
            }
          }
        }
      }
      if (vr == null) {
        computeSupportedAuthnTypes(t, request);
      }

      // validation done
      if (vr == null) {
        log.info("Authentication request validation succeeded");
        vr = new ValidationResult(); // success

        // check if we need to convert a principal into emailAddress
        if (request.getNameIDPolicy() != null
            && request.getNameIDPolicy().getFormat() != null
            && request.getNameIDPolicy().getFormat().equals(OasisNames.EMAIL_ADDRESS)) {
          t.setIdentityFormat(OasisNames.IDENTITY_FORMAT_EMAIL_ADDRESS);
        } else {
          t.setIdentityFormat(OasisNames.IDENTITY_FORMAT_UPN);
        }
      }

    } catch (Exception e) {
      vr = new ValidationResult(HttpServletResponse.SC_BAD_REQUEST, "BadRequest", null);
      log.debug("Caught exception while Validating " + e.toString() + ", returning 400");
    }
    return vr;
  }
Пример #27
0
  void drawTimeLine() {

    // draw the base timeline

    int minorTickHeight = (int) (20 * scaleFactorY);
    int majorTickHeight = (int) (40 * scaleFactorY);
    parent.strokeWeight(10);
    parent.stroke(0);
    parent.line(lineStart, lineY, lineStop, lineY);
    // draw days
    // int maxDays = Days.daysBetween(timelineStartDate,
    // timelineEndDate).getDays();
    int maxHours = Hours.hoursBetween(timelineStartDate, timelineEndDate).getHours();
    // println("Interval  is " + fullTimeInterval);
    // println("Period is " + Days.daysBetween(minDate, maxDate).getDays());
    // println("Max days is " + maxDays);

    DateTime tempdt = new DateTime(timelineStartDate);
    String previousMonth = timelineStartDate.monthOfYear().getAsText();
    int previousDay = -1; // =tempdt.dayOfYear().get();
    int monthStart = lineStart;
    parent.textAlign(PConstants.CENTER, PConstants.TOP);

    for (int a = 0; a < maxHours; a++) {
      // println(a);
      parent.textAlign(PConstants.CENTER, PConstants.TOP);
      // draw label
      parent.textFont(parent.font);
      parent.textSize(10 * fontScale);

      if (tempdt.dayOfYear().get() != previousDay) {
        int tx = (int) (PApplet.map(a, 0, maxHours, lineStart, lineStop));
        // draw tick
        parent.strokeWeight(1);
        parent.line(tx, lineY, tx, lineY + minorTickHeight);
        previousDay = tempdt.dayOfYear().get();
        parent.fill(0);
        if (tempdt.dayOfMonth().get() == 1) {
          // special case!
          parent.textSize(14 * fontScale);
          parent.text(
              tempdt.dayOfMonth().getAsString(),
              tx,
              lineY + majorTickHeight + parent.textDescent());
        } else {
          parent.text(
              tempdt.dayOfMonth().getAsString(),
              tx,
              lineY + minorTickHeight + parent.textDescent());
        }

        // check if need to draw monthName
        if (!previousMonth.equals(tempdt.monthOfYear().getAsText())) {
          // draw some visual markers!
          // line(monthStart, lineY, monthStart,
          // lineY+majorTickHeight);
          parent.line(tx, lineY, tx, lineY + majorTickHeight);
          // position halfway between monthStart and tx, draw
          // monthname
          parent.textSize(18 * fontScale);
          // check! do we overlap the next month? if so, change
          // alignment
          if (parent.textWidth(previousMonth) / 2 + monthStart > tx) {
            parent.textAlign(PConstants.RIGHT, PConstants.TOP);
          }
          parent.text(
              previousMonth,
              (tx + monthStart) / 2,
              lineY + minorTickHeight + 2 * (parent.textAscent() + parent.textDescent()));
          previousMonth = tempdt.monthOfYear().getAsText();
          monthStart = tx;
        }
      }
      tempdt = tempdt.plus(Period.hours(1));
    }
    // draw final day
    parent.line(lineStop, lineY, lineStop, lineY + minorTickHeight);
    if (tempdt.dayOfMonth().get() == 1) {
      // special case!
      parent.text(
          tempdt.dayOfMonth().getAsString(),
          lineStop,
          lineY + majorTickHeight + parent.textDescent());
    } else {
      parent.text(
          tempdt.dayOfMonth().getAsString(),
          lineStop,
          lineY + minorTickHeight + parent.textDescent());
    }
    // draw final month!
    parent.textSize(18 * fontScale);
    parent.text(
        tempdt.monthOfYear().getAsText(),
        (lineStop + monthStart) / 2,
        lineY + minorTickHeight + 2 * (parent.textAscent() + parent.textDescent()));
  }
Пример #28
0
 public static String computeTime(String dateString, String val, String timeUnit) {
   DateTime date = new DateTime();
   int value = 0;
   boolean isLong = false;
   if (!Strings.isEmpty(val) && !Strings.isEmpty(dateString) && !Strings.isEmpty(timeUnit)) {
     if (dateString.substring(dateString.indexOf("T") + 1, dateString.length()).length() == 0) {
       dateString = dateString + DEFAULT_TIME_FORMAT;
     }
     date = new DateTime(dateString);
     if (val.indexOf(".") > 0) {
       val = val.substring(0, val.indexOf("."));
     }
     Long l = new Long(val);
     if ((l.longValue() < 0 && -l.longValue() > 32768)
         || (l.longValue() > 0 && l.longValue() > 32768)) {
       isLong = true;
     }
     if (!isLong) {
       value = Integer.parseInt(val);
     }
     if (!Strings.isEmpty(timeUnit)) {
       if (timeUnit.equals("d")) {
         if (!isLong) {
           if (value > 0) {
             date = date.plusDays(value);
           } else {
             date = date.minusDays(-value);
           }
         } else {
           if (l.longValue() < 0) {
             date = date.minus(-l.longValue() * 24 * 60 * 60 * 1000);
           } else {
             date = date.plus(l.longValue() * 24 * 60 * 60 * 1000);
           }
         }
       } else if (timeUnit.equals(HOUR)) {
         if (!isLong) {
           if (value > 0) {
             date = date.plusHours(value);
           } else {
             date = date.minusHours(-value);
           }
         } else {
           if (l.longValue() < 0) {
             date = date.minus(-l.longValue() * 60 * 60 * 1000);
           } else {
             date = date.plus(l.longValue() * 60 * 60 * 1000);
           }
         }
       } else if (timeUnit.equals(MIN)) {
         if (!isLong) {
           if (value > 0) {
             date = date.plusMinutes(value);
           } else {
             date = date.minusMinutes(-value);
           }
         } else {
           if (l.longValue() < 0) {
             date = date.minus(-l.longValue() * 60 * 1000);
           } else {
             date = date.plus(l.longValue() * 60 * 1000);
           }
         }
       } else if (timeUnit.equals(SEC)) {
         if (!isLong) {
           if (value > 0) {
             date = date.plusSeconds(value);
           } else {
             date = date.minusSeconds(-value);
           }
         } else {
           if (l.longValue() < 0) {
             date = date.minus(-l.longValue() * 1000);
           } else {
             date = date.plus(l.longValue() * 1000);
           }
         }
       }
     }
   }
   return FormatUtils.formatDateTimeToISO(date.toDate());
 }
 @Override
 protected SessionEvent createEventDiff(DateTime dateTime) throws Exception {
   return new SessionEvent(new Interval(dateTime, dateTime.plus(2)));
 }
  @Override
  /** Sends an SMS */
  public void send(OutgoingSms sms) {

    // todo: cache that?
    Configs configs = new ConfigReader(settingsFacade).getConfigs();
    Config config;
    Template template;

    if (sms.hasConfig()) {
      config = configs.getConfig(sms.getConfig());
    } else {
      logger.debug("No config specified, using default config.");
      config = configs.getDefaultConfig();
    }
    template = templates.getTemplate(config.getTemplateName());

    // todo: die if things aren't right, right?
    // todo: SMS_SCHEDULE_FUTURE_SMS research if any sms provider provides that, for now assume not.

    Integer maxSize = template.getOutgoing().getMaxSmsSize();
    String header = config.getSplitHeader();
    String footer = config.getSplitFooter();
    Boolean excludeLastFooter = config.getExcludeLastFooter();
    // todo: maximum number of supported recipients : per template/provider and/or per http specs

    // todo - cr - move that to the Config object so calculated only once ?
    // todo - cr - investigate if that might be a problem on windows
    // -2 to account for the added \n after the header and before the footer
    if ((maxSize - header.length() - footer.length() - 2) <= 0) {
      throw new IllegalArgumentException(
          "The combined sizes of the header and footer templates are larger than the maximum SMS size!");
    }

    List<String> messageParts =
        splitMessage(sms.getMessage(), maxSize, header, footer, excludeLastFooter);
    List<List<String>> recipientsList =
        splitRecipientList(sms.getRecipients(), template.getOutgoing().getMaxRecipient());

    // todo: delivery_time on the sms provider's side if they support it?
    for (List<String> recipients : recipientsList) {
      if (sms.hasDeliveryTime()) {
        DateTime dt = sms.getDeliveryTime();
        for (String part : messageParts) {
          String motechId = generateMotechId();
          MotechEvent event =
              outboundEvent(
                  SmsEventSubjects.SCHEDULED,
                  config.getName(),
                  recipients,
                  part,
                  motechId,
                  null,
                  null,
                  null,
                  null);
          // MOTECH scheduler needs unique job ids, so adding motechId as job_id_key will do that
          event.getParameters().put(MotechSchedulerService.JOB_ID_KEY, motechId);
          event.getParameters().put(SmsEventParams.DELIVERY_TIME, dt);
          schedulerService.safeScheduleRunOnceJob(new RunOnceSchedulableJob(event, dt.toDate()));
          logger.info(
              String.format(
                  "Scheduling message [%s] to [%s] at %s.",
                  part.replace("\n", "\\n"), recipients, sms.getDeliveryTime()));
          // add one millisecond to the next sms part so they will be delivered in order
          // without that it seems Quartz doesn't fire events in the order they were scheduled
          dt = dt.plus(1);
          for (String recipient : recipients) {
            smsAuditService.log(
                new SmsRecord(
                    config.getName(),
                    OUTBOUND,
                    recipient,
                    part,
                    now(),
                    DeliveryStatus.SCHEDULED,
                    null,
                    motechId,
                    null,
                    null));
          }
        }
      } else {
        for (String part : messageParts) {
          String motechId = generateMotechId();
          eventRelay.sendEventMessage(
              outboundEvent(
                  SmsEventSubjects.PENDING,
                  config.getName(),
                  recipients,
                  part,
                  motechId,
                  null,
                  null,
                  null,
                  null));
          logger.info("Sending message [{}] to [{}].", part.replace("\n", "\\n"), recipients);
          for (String recipient : recipients) {
            smsAuditService.log(
                new SmsRecord(
                    config.getName(),
                    OUTBOUND,
                    recipient,
                    part,
                    now(),
                    DeliveryStatus.PENDING,
                    null,
                    motechId,
                    null,
                    null));
          }
        }
      }
    }
  }