private DtStart getStartDateProperty(Date startDate) {

    DateTime date = convertRaplaLocaleToUTC(startDate);
    TimeZoneRegistry registry = TimeZoneRegistryFactory.getInstance().createRegistry();
    net.fortuna.ical4j.model.TimeZone tz = registry.getTimeZone(timeZone.getID());
    date.setTimeZone(tz);
    return new DtStart(date);
  }
Example #2
0
 public void setDtEnd(long tsEnd, String tzID) {
   if (tzID == null) { // all-day
     dtEnd = new DtEnd(new Date(tsEnd));
   } else {
     DateTime end = new DateTime(tsEnd);
     end.setTimeZone(tzRegistry.getTimeZone(tzID));
     dtEnd = new DtEnd(end);
   }
 }
Example #3
0
 public void setDtStart(long tsStart, String tzID) {
   if (tzID == null) { // all-day
     dtStart = new DtStart(new Date(tsStart));
   } else {
     DateTime start = new DateTime(tsStart);
     start.setTimeZone(tzRegistry.getTimeZone(tzID));
     dtStart = new DtStart(start);
   }
 }
  private DateTime calculateOnset(String dateStr) throws ParseException {

    // Translate local onset into UTC time by parsing local time
    // as GMT and adjusting by TZOFFSETFROM if required
    long utcOnset;

    synchronized (UTC_FORMAT) {
      utcOnset = UTC_FORMAT.parse(dateStr).getTime();
    }

    // return a UTC
    DateTime onset = new DateTime(true);
    onset.setTime(utcOnset);
    return onset;
  }
Example #5
0
  /**
   * Build iCalendar-compliant recurrence rule
   *
   * @param recurrence
   * @param recurrenceEnd
   * @return rrule
   */
  public static String getRecurrenceRule(final String recurrence, final Date recurrenceEnd) {
    final TimeZone tz =
        TimeZoneRegistryFactory.getInstance()
            .createRegistry()
            .getTimeZone(java.util.Calendar.getInstance().getTimeZone().getID());

    if (recurrence != null) { // recurrence available
      // create recurrence rule
      final StringBuilder sb = new StringBuilder();
      sb.append("FREQ=");
      if (recurrence.equals(CalendarEntry.WORKDAILY)) {
        // build rule for monday to friday
        sb.append(CalendarEntry.DAILY);
        sb.append(";");
        sb.append("BYDAY=MO,TU,WE,TH,FR");
      } else if (recurrence.equals(CalendarEntry.BIWEEKLY)) {
        // build rule for biweekly
        sb.append(CalendarEntry.WEEKLY);
        sb.append(";");
        sb.append("INTERVAL=2");
      } else {
        // normal supported recurrence
        sb.append(recurrence);
      }
      if (recurrenceEnd != null) {
        final DateTime recurEndDT = new DateTime(recurrenceEnd.getTime());
        recurEndDT.setTimeZone(tz);
        sb.append(";");
        sb.append(CalendarEntry.UNTIL);
        sb.append("=");
        sb.append(recurEndDT.toString());
      }
      try {
        final Recur recur = new Recur(sb.toString());
        final RRule rrule = new RRule(recur);
        return rrule.getValue();
      } catch (final ParseException e) {
        log.error("cannot create recurrence rule: " + recurrence.toString(), e);
      }
    }

    return null;
  }
  /**
   * Tests limit recurrence set.
   *
   * @throws Exception - if something is wrong this exception is thrown.
   */
  @Test
  public void testLimitRecurrenceSet() throws Exception {
    CalendarBuilder cb = new CalendarBuilder();
    FileInputStream fis = new FileInputStream(baseDir + "limit_recurr_test.ics");
    Calendar calendar = cb.build(fis);

    Assert.assertEquals(5, calendar.getComponents().getComponents("VEVENT").size());

    VTimeZone vtz = (VTimeZone) calendar.getComponents().getComponent("VTIMEZONE");
    TimeZone tz = new TimeZone(vtz);
    OutputFilter filter = new OutputFilter("test");
    DateTime start = new DateTime("20060104T010000", tz);
    DateTime end = new DateTime("20060106T010000", tz);
    start.setUtc(true);
    end.setUtc(true);

    Period period = new Period(start, end);
    filter.setLimit(period);
    filter.setAllSubComponents();
    filter.setAllProperties();

    StringBuffer buffer = new StringBuffer();
    filter.filter(calendar, buffer);
    StringReader sr = new StringReader(buffer.toString());

    Calendar filterCal = cb.build(sr);

    ComponentList comps = filterCal.getComponents();
    Assert.assertEquals(3, comps.getComponents("VEVENT").size());
    Assert.assertEquals(1, comps.getComponents("VTIMEZONE").size());

    // Make sure 3rd and 4th override are dropped
    @SuppressWarnings("unchecked")
    Iterator<Component> it = comps.getComponents("VEVENT").iterator();
    while (it.hasNext()) {
      Component c = it.next();
      Assert.assertNotSame(
          "event 6 changed 3", c.getProperties().getProperty("SUMMARY").getValue());
      Assert.assertNotSame(
          "event 6 changed 4", c.getProperties().getProperty("SUMMARY").getValue());
    }
  }
  /**
   * Tests the set of limit recurrence.
   *
   * @throws Exception - if something is wrong this exception is thrown.
   */
  @Test
  public void testLimitRecurrenceSetThisAndFuture() throws Exception {
    CalendarBuilder cb = new CalendarBuilder();
    FileInputStream fis = new FileInputStream(baseDir + "limit_recurr_taf_test.ics");
    Calendar calendar = cb.build(fis);

    Assert.assertEquals(4, calendar.getComponents().getComponents("VEVENT").size());

    VTimeZone vtz = (VTimeZone) calendar.getComponents().getComponent("VTIMEZONE");
    TimeZone tz = new TimeZone(vtz);
    OutputFilter filter = new OutputFilter("test");
    DateTime start = new DateTime("20060108T170000", tz);
    DateTime end = new DateTime("20060109T170000", tz);
    start.setUtc(true);
    end.setUtc(true);

    Period period = new Period(start, end);
    filter.setLimit(period);
    filter.setAllSubComponents();
    filter.setAllProperties();

    StringBuffer buffer = new StringBuffer();
    filter.filter(calendar, buffer);
    StringReader sr = new StringReader(buffer.toString());

    Calendar filterCal = cb.build(sr);

    Assert.assertEquals(2, filterCal.getComponents().getComponents("VEVENT").size());
    // Make sure 2nd and 3rd override are dropped
    ComponentList vevents = filterCal.getComponents().getComponents(VEvent.VEVENT);
    Iterator<VEvent> it = vevents.iterator();
    while (it.hasNext()) {
      Component c = it.next();
      Assert.assertNotSame("event 6 changed", c.getProperties().getProperty("SUMMARY").getValue());
      Assert.assertNotSame(
          "event 6 changed 2", c.getProperties().getProperty("SUMMARY").getValue());
    }
  }
  /**
   * F&uuml;gt die Wiederholungen des &uuml;bergebenen Appointment-Objekts dem &uuml;bergebenen
   * Event-Objekt hinzu.
   *
   * @param appointment Ein Rapla Appointment.
   */
  private void addRepeatings(Appointment appointment, PropertyList properties) {
    Repeating repeating = appointment.getRepeating();

    if (repeating == null) {
      return;
    }

    // This returns the strings DAYLY, WEEKLY, MONTHLY, YEARLY
    String type = repeating.getType().toString().toUpperCase();

    Recur recur;

    // here is evaluated, if a COUNT is set in Rapla, or an enddate is
    // specified
    if (repeating.getNumber() == -1) {
      recur = new Recur(type, -1);
    } else if (repeating.isFixedNumber()) {
      recur = new Recur(type, repeating.getNumber());
    } else {
      net.fortuna.ical4j.model.Date endDate = new net.fortuna.ical4j.model.Date(repeating.getEnd());
      // TODO do we need to translate the enddate in utc?
      recur = new Recur(type, endDate);
    }

    if (repeating.isDaily()) {
      // DAYLY -> settings : intervall
      recur.setInterval(repeating.getInterval());

    } else if (repeating.isWeekly()) {
      // WEEKLY -> settings : every nTh Weekday
      recur.setInterval(repeating.getInterval());

      calendar.setTime(appointment.getStart());
      recur.getDayList().add(WeekDay.getWeekDay(calendar));
    } else if (repeating.isMonthly()) {
      // MONTHLY -> settings : every nTh Weekday
      recur.setInterval(repeating.getInterval());
      calendar.setTime(appointment.getStart());
      int weekofmonth =
          Math.round(calendar.get(java.util.Calendar.DAY_OF_MONTH) / DateTools.DAYS_PER_WEEK) + 1;
      recur.getDayList().add(new WeekDay(WeekDay.getWeekDay(calendar), weekofmonth));
    } else if (repeating.isYearly()) {
      // YEARLY -> settings : every nTh day mTh Monthname
      calendar.setTime(appointment.getStart());
      calendar.get(java.util.Calendar.DAY_OF_YEAR);
    } else {
      getLogger().warn("Invalid data in recurrency rule!");
    }

    properties.add(new RRule(recur));

    // bugfix - if rapla has no exceptions, an empty EXDATE: element is
    // produced. This may bother some iCal tools
    if (repeating.getExceptions().length == 0) {
      return;
    }

    // Add exception dates
    // DateList dl = new DateList(Value.DATE);

    ExDate exDate = new ExDate();
    TimeZoneRegistry registry = TimeZoneRegistryFactory.getInstance().createRegistry();
    net.fortuna.ical4j.model.TimeZone tz = registry.getTimeZone(timeZone.getID());

    // rku: use seperate EXDATE for each exception
    for (Iterator<Date> itExceptions = Arrays.asList(repeating.getExceptions()).iterator();
        itExceptions.hasNext(); ) {
      // DateList dl = new DateList(Value.DATE);
      Date date = itExceptions.next();
      // dl.add(new net.fortuna.ical4j.model.Date( date));
      java.util.Calendar cal = raplaLocale.createCalendar();
      cal.setTime(date);
      int year = cal.get(java.util.Calendar.YEAR);
      int day_of_year = cal.get(java.util.Calendar.DAY_OF_YEAR);
      cal.setTime(appointment.getStart());
      cal.set(java.util.Calendar.YEAR, year);
      cal.set(java.util.Calendar.DAY_OF_YEAR, day_of_year);
      int offset =
          (int) (tz.getOffset(DateTools.cutDate(date).getTime()) / DateTools.MILLISECONDS_PER_HOUR);
      cal.add(java.util.Calendar.HOUR, -offset);
      Date dateToSave = cal.getTime();
      net.fortuna.ical4j.model.DateTime dateTime = new net.fortuna.ical4j.model.DateTime();
      dateTime.setTime(dateToSave.getTime());
      exDate.getDates().add(dateTime);
    }
    exDate.setTimeZone(tz);

    properties.add(exDate);
    // properties.add(new ExDate(dl));
  }
 private DateTime applyOffsetFrom(DateTime orig) {
   DateTime withOffset = new DateTime(true);
   withOffset.setTime(orig.getTime() - getOffsetFrom().getOffset().getOffset());
   return withOffset;
 }
  /**
   * Returns the latest applicable onset of this observance for the specified date.
   *
   * @param date the latest date that an observance onset may occur
   * @return the latest applicable observance date or null if there is no applicable observance
   *     onset for the specified date
   */
  public final Date getLatestOnset(final Date date) {

    if (initialOnset == null) {
      try {
        initialOnset =
            applyOffsetFrom(calculateOnset(((DtStart) getProperty(Property.DTSTART)).getDate()));
      } catch (ParseException e) {
        Log log = LogFactory.getLog(Observance.class);
        log.error("Unexpected error calculating initial onset", e);
        // XXX: is this correct?
        return null;
      }
    }

    // observance not applicable if date is before the effective date of this observance..
    if (date.before(initialOnset)) {
      return null;
    }

    if ((onsetsMillisec != null) && (onsetLimit == null || date.before(onsetLimit))) {
      return getCachedOnset(date);
    }

    Date onset = initialOnset;
    Date initialOnsetUTC;
    // get first onset without adding TZFROM as this may lead to a day boundary
    // change which would be incompatible with BYDAY RRULES
    // we will have to add the offset to all cacheable onsets
    try {
      initialOnsetUTC = calculateOnset(((DtStart) getProperty(Property.DTSTART)).getDate());
    } catch (ParseException e) {
      Log log = LogFactory.getLog(Observance.class);
      log.error("Unexpected error calculating initial onset", e);
      // XXX: is this correct?
      return null;
    }
    // collect all onsets for the purposes of caching..
    final DateList cacheableOnsets = new DateList();
    cacheableOnsets.setUtc(true);
    cacheableOnsets.add(initialOnset);

    // check rdates for latest applicable onset..
    final PropertyList rdates = getProperties(Property.RDATE);
    for (final Iterator i = rdates.iterator(); i.hasNext(); ) {
      final RDate rdate = (RDate) i.next();
      for (final Iterator j = rdate.getDates().iterator(); j.hasNext(); ) {
        try {
          final DateTime rdateOnset = applyOffsetFrom(calculateOnset((Date) j.next()));
          if (!rdateOnset.after(date) && rdateOnset.after(onset)) {
            onset = rdateOnset;
          }
          /*
           * else if (rdateOnset.after(date) && rdateOnset.after(onset) && (nextOnset == null ||
           * rdateOnset.before(nextOnset))) { nextOnset = rdateOnset; }
           */
          cacheableOnsets.add(rdateOnset);
        } catch (ParseException e) {
          Log log = LogFactory.getLog(Observance.class);
          log.error("Unexpected error calculating onset", e);
        }
      }
    }

    // check recurrence rules for latest applicable onset..
    final PropertyList rrules = getProperties(Property.RRULE);
    for (final Iterator i = rrules.iterator(); i.hasNext(); ) {
      final RRule rrule = (RRule) i.next();
      // include future onsets to determine onset period..
      final Calendar cal = Dates.getCalendarInstance(date);
      cal.setTime(date);
      cal.add(Calendar.YEAR, 10);
      onsetLimit = Dates.getInstance(cal.getTime(), Value.DATE_TIME);
      final DateList recurrenceDates =
          rrule.getRecur().getDates(initialOnsetUTC, onsetLimit, Value.DATE_TIME);
      for (final Iterator j = recurrenceDates.iterator(); j.hasNext(); ) {
        final DateTime rruleOnset = applyOffsetFrom((DateTime) j.next());
        if (!rruleOnset.after(date) && rruleOnset.after(onset)) {
          onset = rruleOnset;
        }
        /*
         * else if (rruleOnset.after(date) && rruleOnset.after(onset) && (nextOnset == null ||
         * rruleOnset.before(nextOnset))) { nextOnset = rruleOnset; }
         */
        cacheableOnsets.add(rruleOnset);
      }
    }

    // cache onsets..
    Collections.sort(cacheableOnsets);
    DateTime cacheableOnset = null;
    this.onsetsMillisec = new long[cacheableOnsets.size()];
    this.onsetsDates = new DateTime[onsetsMillisec.length];

    for (int i = 0; i < onsetsMillisec.length; i++) {
      cacheableOnset = (DateTime) cacheableOnsets.get(i);
      onsetsMillisec[i] = cacheableOnset.getTime();
      onsetsDates[i] = cacheableOnset;
    }

    return onset;
  }