/**
   * This method returns a list of events
   *
   * @return
   */
  public ArrayList<Event> getList() {
    String time = "";
    String summary = "";
    String description = "";

    try {
      FileInputStream fin = new FileInputStream("composite.ics");
      CalendarBuilder builder = new CalendarBuilder();

      Calendar calendar = builder.build(fin);
      for (Component c : calendar.getComponents()) {
        for (Property property : c.getProperties()) {

          switch (property.getName()) {
            case "DTSTART":
              time = property.getValue();
              break;
            case "SUMMARY":
              summary = property.getValue();
              break;
            case "DESCRIPTION":
              description = property.getValue();
              break;
          }
        }
        list.add(new AthleticsEvent(summary, description, time));
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    return list;
  }
Пример #2
0
  public void testContentDaoCreateAvailability() throws Exception {
    User user = getUser(userDao, "testuser");
    CollectionItem root = (CollectionItem) contentDao.getRootItem(user);

    AvailabilityItem newItem = new HibAvailabilityItem();
    newItem.setOwner(user);
    newItem.setName("test");
    newItem.setIcalUid("icaluid");

    CalendarBuilder cb = new CalendarBuilder();
    net.fortuna.ical4j.model.Calendar calendar =
        cb.build(helper.getInputStream("vavailability.ics"));

    newItem.setAvailabilityCalendar(calendar);

    newItem = (AvailabilityItem) contentDao.createContent(root, newItem);

    Assert.assertTrue(getHibItem(newItem).getId() > -1);
    Assert.assertTrue(newItem.getUid() != null);

    clearSession();

    ContentItem queryItem = contentDao.findContentByUid(newItem.getUid());

    helper.verifyItem(newItem, queryItem);
  }
Пример #3
0
 /**
  * Parse icalendar data from Reader into Calendar object.
  *
  * @param reader icalendar data reader
  * @return Calendar object
  * @throws ParserException - if something is wrong this exception is thrown.
  * @throws IOException - if something is wrong this exception is thrown.
  */
 public static Calendar parseCalendar(Reader reader) throws ParserException, IOException {
   if (reader == null) {
     return null;
   }
   CalendarBuilder builder = CalendarBuilderDispenser.getCalendarBuilder();
   clearTZRegistry(builder);
   return builder.build(reader);
 }
Пример #4
0
 /**
  * @return the calendar
  * @throws ParserException where calendar parsing fails
  * @throws IOException where a communication error occurs
  */
 public final Calendar getCalendar() throws IOException, ParserException {
   if (calendar == null) {
     CalendarBuilder builder = new CalendarBuilder();
     //            calendar = builder.build(new
     // ByteArrayInputStream(file.getDataProvider().getBytes()));
     calendar = builder.build(file.getDataProvider().getInputStream());
   }
   return calendar;
 }
Пример #5
0
  /**
   * Parse icalendar string into Calendar object.
   *
   * @param calendar icalendar string
   * @return Calendar object
   * @throws ParserException - if something is wrong this exception is thrown.
   * @throws IOException - if something is wrong this exception is thrown.
   */
  public static Calendar parseCalendar(String calendar) throws ParserException, IOException {
    if (calendar == null) {
      return null;
    }
    CalendarBuilder builder = CalendarBuilderDispenser.getCalendarBuilder();
    clearTZRegistry(builder);

    StringReader sr = new StringReader(calendar);
    return builder.build(sr);
  }
Пример #6
0
 public static String TimezoneDefToTzId(String timezoneDef) {
   try {
     CalendarBuilder builder = new CalendarBuilder();
     net.fortuna.ical4j.model.Calendar cal = builder.build(new StringReader(timezoneDef));
     VTimeZone timezone = (VTimeZone) cal.getComponent(VTimeZone.VTIMEZONE);
     return timezone.getTimeZoneId().getValue();
   } catch (Exception ex) {
     Log.w(TAG, "Can't understand time zone definition", ex);
   }
   return null;
 }
Пример #7
0
  /**
   * Parse icalendar string into calendar component
   *
   * @param calendar icalendar string
   * @return Component object
   * @throws ParserException - if something is wrong this exception is thrown.
   * @throws IOException - if something is wrong this exception is thrown.
   */
  public static Component parseComponent(String component) throws ParserException, IOException {
    if (component == null) {
      return null;
    }
    // Don't use dispenser as this method may be called from within
    // a build() as in the case of the custom timezone registry
    // parsing a timezone
    CalendarBuilder builder = new CalendarBuilder();
    StringReader sr = new StringReader("BEGIN:VCALENDAR\n" + component + "END:VCALENDAR");

    return (Component) builder.build(sr).getComponents().get(0);
  }
Пример #8
0
  public Calendar buildICal(String ical) {

    Calendar calendar = null;
    StringReader sin = new StringReader(ical);
    CalendarBuilder builder = new CalendarBuilder();

    try {
      calendar = builder.build(sin);
    } catch (IOException e) {
      e.printStackTrace();
    } catch (ParserException e) {
      e.printStackTrace();
    }
    return calendar;
  }
Пример #9
0
  public final void testGetConsumedTime2() throws Exception {
    String filename = "etc/samples/valid/derryn.ics";

    FileInputStream fin = new FileInputStream(filename);

    CalendarBuilder builder = new CalendarBuilder();

    net.fortuna.ical4j.model.Calendar calendar = null;

    try {
      calendar = builder.build(fin, "utf-8");
    } catch (IOException e) {
      log.warn("File: " + filename, e);
    } catch (ParserException e) {
      log.warn("File: " + filename, e);
    }

    assertNotNull(calendar);

    try {
      calendar.validate();
    } catch (ValidationException e) {
      assertTrue("Calendar file " + filename + " isn't valid:\n" + e.getMessage(), false);
    }

    log.info("File: " + filename);

    if (log.isDebugEnabled()) {
      log.debug("Calendar:\n=========\n" + calendar.toString());
    }

    Date start = new Date();
    Calendar endCal = getCalendarInstance();
    endCal.setTime(start);
    endCal.add(Calendar.WEEK_OF_YEAR, 4);
    //        Date end = new Date(start.getTime() + (1000 * 60 * 60 * 24 * 7 * 4));
    for (Iterator i = calendar.getComponents().iterator(); i.hasNext(); ) {
      Component c = (Component) i.next();

      if (c instanceof VEvent) {
        PeriodList consumed =
            ((VEvent) c).getConsumedTime(start, new Date(endCal.getTime().getTime()));

        log.debug("Event [" + c + "]");
        log.debug("Consumed time [" + consumed + "]");
      }
    }
  }
Пример #10
0
 private static void clearTZRegistry(CalendarBuilder cb) {
   // clear timezone registry if present
   TimeZoneRegistry tzr = cb.getRegistry();
   if (tzr != null) {
     tzr.clear();
   }
 }
Пример #11
0
  /**
   * 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());
    }
  }
Пример #12
0
  /**
   * 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());
    }
  }
  /* Fetch the iCalendar for the subscription. If it fails set the status and
   * return null. Unchanged data will return null with no status change.
   */
  private void getIcal() throws SynchException {
    try {
      if (fetchedIcal != null) {
        return;
      }

      getClient();

      Header[] hdrs = null;

      if ((uidMap != null) && (info.getChangeToken() != null) && (fetchedIcal != null)) {
        hdrs = new Header[] {new BasicHeader("If-None-Match", info.getChangeToken())};
      }

      int rc = client.sendRequest("GET", info.getUri(), hdrs);
      info.setLastRefreshStatus(String.valueOf(rc));

      if (rc == HttpServletResponse.SC_NOT_MODIFIED) {
        // Data unchanged.
        if (debug) {
          trace("data unchanged");
        }
        return;
      }

      if (rc != HttpServletResponse.SC_OK) {
        info.setLastRefreshStatus(String.valueOf(rc));
        if (debug) {
          trace("Unsuccessful response from server was " + rc);
        }
        info.setChangeToken(null); // Force refresh next time
        return;
      }

      CalendarBuilder builder = new CalendarBuilder();

      InputStream is = client.getResponse().getContentStream();

      Calendar ical = builder.build(is);

      /* Convert each entity to XML */

      fetchedIcal = IcalToXcal.fromIcal(ical, null);

      uidMap = new HashMap<String, MapEntry>();

      prodid = null;

      for (VcalendarType vcal : fetchedIcal.getVcalendar()) {
        /* Extract the prodid from the converted calendar - we use it when we
         * generate a new icalendar for each entity.
         */
        if ((prodid == null) && (vcal.getProperties() != null)) {
          for (JAXBElement<? extends BasePropertyType> pel :
              vcal.getProperties().getBasePropertyOrTzid()) {
            if (pel.getValue() instanceof ProdidPropType) {
              prodid = ((ProdidPropType) pel.getValue()).getText();
              break;
            }
          }
        }

        for (JAXBElement<? extends BaseComponentType> comp :
            vcal.getComponents().getBaseComponent()) {
          UidPropType uidProp = (UidPropType) XcalUtil.findProperty(comp.getValue(), XcalTags.uid);

          if (uidProp == null) {
            // Should flag as an error
            continue;
          }

          String uid = uidProp.getText();

          MapEntry me = uidMap.get(uid);

          if (me == null) {
            me = new MapEntry();
            me.uid = uid;
            uidMap.put(uidProp.getText(), me);
          }

          LastModifiedPropType lm =
              (LastModifiedPropType) XcalUtil.findProperty(comp.getValue(), XcalTags.lastModified);

          String lastmod = null;
          if (lm != null) {
            lastmod = lm.getUtcDateTime().toXMLFormat();
          }

          if (Util.cmpObjval(me.lastMod, lastmod) < 0) {
            me.lastMod = lastmod;
          }

          me.comps.add(comp);
        }
      }

      /* Looks like we translated ok. Save any etag and delete everything in the
       * calendar.
       */

      String etag = client.getResponse().getResponseHeaderValue("Etag");
      if (etag != null) {
        info.setChangeToken(etag);
      }
    } catch (SynchException se) {
      throw se;
    } catch (Throwable t) {
      throw new SynchException(t);
    } finally {
      try {
        client.release();
      } catch (Throwable t) {
      }
    }
  }
Пример #14
0
  @Override
  @SuppressWarnings("unchecked")
  public void parseEntity(@NonNull InputStream entity)
      throws IOException, InvalidResourceException {
    net.fortuna.ical4j.model.Calendar ical;
    try {
      CalendarBuilder builder = new CalendarBuilder();
      ical = builder.build(entity);

      if (ical == null) throw new InvalidResourceException("No iCalendar found");
    } catch (ParserException e) {
      throw new InvalidResourceException(e);
    }

    // event
    ComponentList events = ical.getComponents(Component.VEVENT);
    if (events == null || events.isEmpty()) throw new InvalidResourceException("No VEVENT found");
    VEvent event = (VEvent) events.get(0);

    if (event.getUid() != null) uid = event.getUid().getValue();
    else {
      Log.w(TAG, "Received VEVENT without UID, generating new one");
      generateUID();
    }

    if ((dtStart = event.getStartDate()) == null || (dtEnd = event.getEndDate()) == null)
      throw new InvalidResourceException("Invalid start time/end time/duration");

    if (hasTime(dtStart)) {
      validateTimeZone(dtStart);
      validateTimeZone(dtEnd);
    }

    // all-day events and "events on that day":
    // * related UNIX times must be in UTC
    // * must have a duration (set to one day if missing)
    if (!hasTime(dtStart) && !dtEnd.getDate().after(dtStart.getDate())) {
      Log.i(TAG, "Repairing iCal: DTEND := DTSTART+1");
      Calendar c = Calendar.getInstance(TimeZone.getTimeZone(Time.TIMEZONE_UTC));
      c.setTime(dtStart.getDate());
      c.add(Calendar.DATE, 1);
      dtEnd.setDate(new Date(c.getTimeInMillis()));
    }

    rrule = (RRule) event.getProperty(Property.RRULE);
    rdate = (RDate) event.getProperty(Property.RDATE);
    exrule = (ExRule) event.getProperty(Property.EXRULE);
    exdate = (ExDate) event.getProperty(Property.EXDATE);

    if (event.getSummary() != null) summary = event.getSummary().getValue();
    if (event.getLocation() != null) location = event.getLocation().getValue();
    if (event.getDescription() != null) description = event.getDescription().getValue();

    status = event.getStatus();

    opaque = true;
    if (event.getTransparency() == Transp.TRANSPARENT) opaque = false;

    organizer = event.getOrganizer();
    for (Object o : event.getProperties(Property.ATTENDEE)) attendees.add((Attendee) o);

    Clazz classification = event.getClassification();
    if (classification != null) {
      if (classification == Clazz.PUBLIC) forPublic = true;
      else if (classification == Clazz.CONFIDENTIAL || classification == Clazz.PRIVATE)
        forPublic = false;
    }

    this.alarms = event.getAlarms();
  }
Пример #15
0
 /**
  * Parse icalendar data from InputStream
  *
  * @param is icalendar data inputstream
  * @return Calendar object
  * @throws ParserException - if something is wrong this exception is thrown.
  * @throws IOException - if something is wrong this exception is thrown.
  */
 public static Calendar parseCalendar(InputStream is) throws ParserException, IOException {
   CalendarBuilder builder = CalendarBuilderDispenser.getCalendarBuilder();
   clearTZRegistry(builder);
   return builder.build(is);
 }
Пример #16
0
 /**
  * Parse icalendar data from byte[] into Calendar object.
  *
  * @param content icalendar data
  * @return Calendar object
  * @throws ParserException - if something is wrong this exception is thrown.
  * @throws IOException - if something is wrong this exception is thrown.
  */
 public static Calendar parseCalendar(byte[] content) throws ParserException, IOException {
   CalendarBuilder builder = CalendarBuilderDispenser.getCalendarBuilder();
   clearTZRegistry(builder);
   return builder.build(new ByteArrayInputStream(content));
 }