コード例 #1
1
ファイル: ExportServlet.java プロジェクト: Bacaa14/Coursola
  @Override
  public void init() throws ServletException {
    // TODO Auto-generated method stub
    super.init();
    filePath = getServletContext().getRealPath("") + File.separator + "schedule.ics";
    try {
      ical.getProperties().add(new ProdId("-//Ben Fortuna//iCal4j 1.0//EN"));
      ical.getProperties().add(Version.VERSION_2_0);
      ical.getProperties().add(CalScale.GREGORIAN);
    } catch (Exception e) {
      System.out.println("iCalendar failed to import");
    }
    registry = TimeZoneRegistryFactory.getInstance().createRegistry();
    timezone = registry.getTimeZone("America/New_York");
    tz = timezone.getVTimeZone();

    try {
      // Register the driver.
      Class.forName("org.postgresql.Driver").newInstance();
    } catch (Exception e) {
      e.printStackTrace();
    }
    String url = "jdbc:postgresql://hopper.cs.wlu.edu/corsola";
    try {
      con = DriverManager.getConnection(url, "web", "");
    } catch (SQLException e) {
      e.printStackTrace();
    }
  }
コード例 #2
1
  /**
   * 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;
  }
コード例 #3
1
ファイル: IcalToXcal.java プロジェクト: yehecan/bw-util
  /**
   * @param cal
   * @param pattern
   * @param doTimezones
   * @return Internal XML representation of iCalendar object
   * @throws Throwable
   */
  @SuppressWarnings("unchecked")
  public static IcalendarType fromIcal(
      final Calendar cal,
      final BaseComponentType pattern,
      final boolean doTimezones,
      final boolean wrapXprops)
      throws Throwable {
    final IcalendarType ical = new IcalendarType();
    final VcalendarType vcal = new VcalendarType();

    ical.getVcalendar().add(vcal);

    processProperties(cal.getProperties(), vcal, pattern, wrapXprops);

    final ComponentList icComps = cal.getComponents();

    if (icComps == null) {
      return ical;
    }

    final ArrayOfComponents aoc = new ArrayOfComponents();
    vcal.setComponents(aoc);

    for (final Object o : icComps) {
      if (!doTimezones && (o instanceof VTimeZone)) {
        // Skip these
        continue;
      }
      aoc.getBaseComponent().add(toComponent((CalendarComponent) o, pattern, wrapXprops));
    }

    return ical;
  }
コード例 #4
1
  /**
   * uses getCalendar(fixture.getHttpClient(), query)
   *
   * @throws Exception
   */
  @Test
  public void testGetEventResources() throws Exception {
    Date beginDate = ICalendarUtils.createDateTime(2006, 0, 1, null, true);
    Date endDate = ICalendarUtils.createDateTime(2006, 11, 9, null, true);
    List<Calendar> l = collection.getEventResources(fixture.getHttpClient(), beginDate, endDate);

    for (Calendar calendar : l) {
      ComponentList vevents = calendar.getComponents().getComponents(Component.VEVENT);
      VEvent ve = (VEvent) vevents.get(0);
      String uid = ICalendarUtils.getUIDValue(ve);
      int correctNumberOfEvents = -1;
      if (ICS_DAILY_NY_5PM_UID.equals(uid)) {
        // one for each day
        correctNumberOfEvents = 1;
      } else if (ICS_ALL_DAY_JAN1_UID.equals(uid)) {
        correctNumberOfEvents = 1;
      } else if (ICS_NORMAL_PACIFIC_1PM_UID.equals(uid)) {
        correctNumberOfEvents = 1;
      } else if (ICS_FLOATING_JAN2_7PM_UID.equals(uid)) {
        correctNumberOfEvents = 0;
      } else {
        fail(uid + " is not the uid of any event that should have been returned");
      }

      assertEquals(correctNumberOfEvents, vevents.size());
    }

    // 3 calendars - one for each resource (not including expanded
    // recurrences)
    assertEquals(3, l.size());
  }
コード例 #5
1
  /** {@inheritDoc} */
  public Calendar createCalendar(List<VEvent> events, String method) {

    if (!isIcsEnabled()) {
      log.debug(
          "ExternalCalendaringService is disabled. Enable via calendar.ics.generation.enabled=true in sakai.properties");
      return null;
    }

    // setup calendar
    Calendar calendar = setupCalendar(method);

    // null check
    if (CollectionUtils.isEmpty(events)) {
      log.error("List of VEvents was null or empty, no calendar will be created.");
      return null;
    }

    // add vevents to calendar
    calendar.getComponents().addAll(events);

    // validate
    try {
      calendar.validate(true);
    } catch (ValidationException e) {
      e.printStackTrace();
      return null;
    }

    if (log.isDebugEnabled()) {
      log.debug("Calendar:" + calendar);
    }

    return calendar;
  }
コード例 #6
1
ファイル: Util.java プロジェクト: ptrvif/openhab
  public static Calendar createCalendar(CalDavEvent calDavEvent, DateTimeZone timeZone) {
    TimeZoneRegistry registry = TimeZoneRegistryFactory.getInstance().createRegistry();
    TimeZone timezone = registry.getTimeZone(timeZone.getID());

    Calendar calendar = new Calendar();
    calendar.getProperties().add(Version.VERSION_2_0);
    calendar.getProperties().add(new ProdId("openHAB"));
    VEvent vEvent = new VEvent();
    vEvent.getProperties().add(new Summary(calDavEvent.getName()));
    vEvent.getProperties().add(new Description(calDavEvent.getContent()));
    final DtStart dtStart =
        new DtStart(new net.fortuna.ical4j.model.DateTime(calDavEvent.getStart().toDate()));
    dtStart.setTimeZone(timezone);
    vEvent.getProperties().add(dtStart);
    final DtEnd dtEnd =
        new DtEnd(new net.fortuna.ical4j.model.DateTime(calDavEvent.getEnd().toDate()));
    dtEnd.setTimeZone(timezone);
    vEvent.getProperties().add(dtEnd);
    vEvent.getProperties().add(new Uid(calDavEvent.getId()));
    vEvent.getProperties().add(Clazz.PUBLIC);
    vEvent
        .getProperties()
        .add(
            new LastModified(
                new net.fortuna.ical4j.model.DateTime(calDavEvent.getLastChanged().toDate())));
    calendar.getComponents().add(vEvent);

    return calendar;
  }
コード例 #7
0
  public Calendar createiCalender(Collection<Appointment> appointments, Preferences preferences) {

    boolean doExportAsMeeting =
        preferences == null
            ? global_export_attendees
            : preferences.getEntryAsBoolean(
                Export2iCalPlugin.EXPORT_ATTENDEES_PREFERENCE, global_export_attendees);

    String exportAttendeesParticipationStatus =
        preferences == null
            ? global_export_attendees_participation_status
            : preferences.getEntryAsString(
                Export2iCalPlugin.EXPORT_ATTENDEES_PARTICIPATION_STATUS_PREFERENCE,
                global_export_attendees_participation_status);

    // ensure the stored value is not empty string, if so, do not export attendees
    doExportAsMeeting =
        doExportAsMeeting
            && (exportAttendeesAttribute != null && exportAttendeesAttribute.trim().length() > 0);

    Calendar calendar = initiCalendar();
    addICalMethod(calendar, Method.PUBLISH);
    addVTimeZone(calendar);
    ComponentList components = calendar.getComponents();
    for (Appointment app : appointments) {
      VEvent event = createVEvent(app, doExportAsMeeting, exportAttendeesParticipationStatus);
      components.add(event);
    }
    return calendar;
  }
コード例 #8
0
  public boolean isValid(Object value) {

    Calendar calendar = null;
    try {
      calendar = (Calendar) value;

      // validate entire icalendar object
      calendar.validate(true);

      // additional check to prevent bad .ics
      CalendarUtils.parseCalendar(calendar.toString());

      // make sure we have a VEVENT with a recurrenceid
      ComponentList comps = calendar.getComponents();
      if (comps == null) {
        log.warn("error validating event exception: " + calendar.toString());
        return false;
      }

      comps = comps.getComponents(Component.VEVENT);
      if (comps == null || comps.size() == 0) {
        log.warn("error validating event exception: " + calendar.toString());
        return false;
      }

      VEvent event = (VEvent) comps.get(0);
      if (event == null) {
        log.warn("error validating event exception: " + calendar.toString());
        return false;
      }

      RecurrenceId recurrenceId = event.getRecurrenceId();

      if (recurrenceId == null
          || recurrenceId.getValue() == null
          || "".equals(recurrenceId.getValue())) {
        log.warn("error validating event exception: " + calendar.toString());
        return false;
      }

      return true;
    } catch (ValidationException ve) {
      log.warn("event validation error", ve);
      if (calendar != null) {
        log.warn("error validating event: " + calendar.toString());
      }
      return false;
    } catch (RuntimeException e) {
      return false;
    } catch (IOException e) {
      return false;
    } catch (ParserException e) {
      log.warn("parse error", e);
      if (calendar != null) {
        log.warn("error parsing event: " + calendar.toString());
      }
      return false;
    }
  }
コード例 #9
0
ファイル: Calendar.java プロジェクト: codirk/ical4j
 /** {@inheritDoc} */
 public final boolean equals(final Object arg0) {
   if (arg0 instanceof Calendar) {
     final Calendar calendar = (Calendar) arg0;
     return new EqualsBuilder()
         .append(getProperties(), calendar.getProperties())
         .append(getComponents(), calendar.getComponents())
         .isEquals();
   }
   return super.equals(arg0);
 }
コード例 #10
0
ファイル: Event.java プロジェクト: neonobjclash/davdroid
 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;
 }
コード例 #11
0
ファイル: Event.java プロジェクト: neonobjclash/davdroid
  @Override
  @SuppressWarnings("unchecked")
  public ByteArrayOutputStream toEntity() throws IOException {
    net.fortuna.ical4j.model.Calendar ical = new net.fortuna.ical4j.model.Calendar();
    ical.getProperties().add(Version.VERSION_2_0);
    ical.getProperties()
        .add(new ProdId("-//bitfire web engineering//DAVdroid " + Constants.APP_VERSION + "//EN"));

    VEvent event = new VEvent();
    PropertyList props = event.getProperties();

    if (uid != null) props.add(new Uid(uid));

    props.add(dtStart);
    if (dtEnd != null) props.add(dtEnd);
    if (duration != null) props.add(duration);

    if (rrule != null) props.add(rrule);
    if (rdate != null) props.add(rdate);
    if (exrule != null) props.add(exrule);
    if (exdate != null) props.add(exdate);

    if (summary != null && !summary.isEmpty()) props.add(new Summary(summary));
    if (location != null && !location.isEmpty()) props.add(new Location(location));
    if (description != null && !description.isEmpty()) props.add(new Description(description));

    if (status != null) props.add(status);
    if (!opaque) props.add(Transp.TRANSPARENT);

    if (organizer != null) props.add(organizer);
    props.addAll(attendees);

    if (forPublic != null) event.getProperties().add(forPublic ? Clazz.PUBLIC : Clazz.PRIVATE);

    event.getAlarms().addAll(alarms);

    props.add(new LastModified());
    ical.getComponents().add(event);

    // add VTIMEZONE components
    net.fortuna.ical4j.model.TimeZone tzStart = (dtStart == null ? null : dtStart.getTimeZone()),
        tzEnd = (dtEnd == null ? null : dtEnd.getTimeZone());
    if (tzStart != null) ical.getComponents().add(tzStart.getVTimeZone());
    if (tzEnd != null && tzEnd != tzStart) ical.getComponents().add(tzEnd.getVTimeZone());

    CalendarOutputter output = new CalendarOutputter(false);
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    try {
      output.output(ical, os);
    } catch (ValidationException e) {
      Log.e(TAG, "Generated invalid iCalendar");
    }
    return os;
  }
コード例 #12
0
ファイル: ICalTools.java プロジェクト: NCIP/psc
  /**
   * Generates the calendar skeleton with basic calendar properties .
   *
   * @return the calendar
   */
  public static Calendar generateCalendarSkeleton() {
    final Calendar icsCalendar = new Calendar();
    icsCalendar.getProperties().add(new ProdId("-//Events Calendar//iCal4j 1.0//EN"));
    // THIS version need to removed otherwise Outlook will not import .ics files.
    // (http://calendarswamp.blogspot.com/2005/08/outlook-2003-for-ical-import-use.html)

    // icsCalendar.getProperties().add(Version.VERSION_2_0);
    icsCalendar.getProperties().add(CalScale.GREGORIAN);

    // this property is required for Outlook
    // (http://en.wikipedia.org/wiki/ICalendar#Microsoft_Outlook)
    icsCalendar.getProperties().add(Method.PUBLISH);
    return icsCalendar;
  }
コード例 #13
0
  //
  // private
  //
  private boolean hasEventWithUID(List<Calendar> cals, String uid) {
    for (Calendar cal : cals) {
      ComponentList vEvents = cal.getComponents().getComponents(Component.VEVENT);
      if (vEvents.size() == 0) {
        return false;
      }
      VEvent ve = (VEvent) vEvents.get(0);
      String curUid = ICalendarUtils.getUIDValue(ve);
      if (curUid != null && uid.equals(curUid)) {
        return true;
      }
    }

    return false;
  }
コード例 #14
0
  /*
   * (non-Javadoc) {@inheritDoc}
   */
  @Override
  public Navigation run() throws Exception {
    Validators v = new Validators(request);
    v.add("startWeek", v.required(), v.integerType(), v.longRange(START_WEEK_MIN, START_WEEK_MAX));
    v.add("keyword", v.maxlength(KEYWORD_MAX_LENGTH));
    if (!v.validate()) {
      response.setStatus(UNAUTHORIZED);
      Errors errors = v.getErrors();
      StringBuilder sb = new StringBuilder();
      for (int i = 0; i < errors.size(); i++) {
        sb.append(errors.get(i) + "\n");
      }
      response.setContentType("text/plain;charset=UTF-8");
      response.getWriter().write(new String(sb));
    } else {
      response.setContentType("text/calendar;charset=UTF-8");
      response.setHeader("Content-Disposition", "filename=\"" + ICALENDAR_FILE_NAME + "\"");

      Integer startWeekNum = Integer.parseInt(request.getParameter("startWeek"));
      StartWeek startWeek = StartWeek.parse(startWeekNum);
      String keyword = request.getParameter("keyword");
      String memcacheKey = "startWeek=" + startWeekNum;
      if (keyword != null) {
        memcacheKey += "&keyword=" + URLEncoder.encode(keyword, "UTF-8");
      }
      Object cache = Memcache.get(memcacheKey);
      if (cache == null) {
        CalendarCondition condition = new CalendarCondition();
        if (keyword != null) {
          // 半角スペースで区切られているキーワードは分割して配列にする。
          condition.setKeywords(Arrays.asList(keyword.split(" ")));
        }
        condition.setStartDate(startWeek.toDate());

        Calendar calendar = calendarService.getCalendar(condition);
        response.getWriter().write(calendar.toString());

        // MemcacheにiCalendarの内容をキャッシュする。
        Memcache.put(memcacheKey, calendar.toString());
      } else {
        // キャッシュがある場合はキャッシュの内容を返す。
        response.getWriter().write((String) cache);
      }
    }
    response.flushBuffer();

    return null;
  }
コード例 #15
0
ファイル: VEventTest.java プロジェクト: TaNhoSy/zimbra-mirror
  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 + "]");
      }
    }
  }
コード例 #16
0
  /**
   * Helper method to setup the standard parts of the calendar
   *
   * @return
   */
  private Calendar setupCalendar(String method) {

    String serverName = sakaiProxy.getServerName();

    // setup calendar
    Calendar calendar = new Calendar();
    calendar
        .getProperties()
        .add(new ProdId("-//" + serverName + "//Sakai External Calendaring Service//EN"));
    calendar.getProperties().add(Version.VERSION_2_0);
    calendar.getProperties().add(CalScale.GREGORIAN);
    if (method != null) {
      calendar.getProperties().add(new Method(method));
    }
    return calendar;
  }
コード例 #17
0
  private void addVTimeZone(Calendar calendar) {

    if (timeZone != null) {
      VTimeZone tz = timeZone.getVTimeZone();
      calendar.getComponents().add(tz);
    }
  }
コード例 #18
0
ファイル: EventsServlet.java プロジェクト: Rutrus/kune
  /*
   * (non-Javadoc)
   *
   * @see
   * javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest,
   * javax.servlet.http.HttpServletResponse)
   */
  @SuppressWarnings("unchecked")
  @Override
  protected void doGet(final HttpServletRequest req, final HttpServletResponse resp)
      throws ServletException, IOException {

    final String userHash = req.getParameter(FileConstants.HASH);
    final StateToken token = new StateToken(req.getParameter(FileConstants.TOKEN));

    final Calendar calendar = new Calendar();
    calendar.getProperties().add(new ProdId("-//Ben Fortuna//iCal4j 1.0//EN"));
    calendar.getProperties().add(Version.VERSION_2_0);
    calendar.getProperties().add(CalScale.GREGORIAN);
    final List<VEvent> events = new ArrayList<VEvent>();

    try {
      final Container cnt = getContainer(userHash, token);
      if (cnt != null && cnt.getTypeId().equals(EventsToolConstants.TYPE_ROOT)) {
        final List<Map<String, String>> listOfProps =
            EventsServerConversionUtil.getAppointmentsUsingCache(cnt);
        for (final Map<String, String> props : listOfProps) {
          try {
            final VEvent vEvent = EventsServerConversionUtil.toVEvent(props);
            events.add(vEvent);
          } catch (final Exception e) {
            LOG.warn("Invalid appointments in " + token, e);
            for (final Entry<String, String> val : props.entrySet()) {
              LOG.warn(String.format("Prop: %s, value: %s", val.getKey(), val.getValue()));
            }
          }
        }
      } else {
        return404(resp);
        return;
      }
      calendar.getComponents().addAll(events);
      resp.setContentType("text/calendar; charset=UTF-8");
      final OutputStream out = resp.getOutputStream();
      final CalendarOutputter outputter = new CalendarOutputter();
      outputter.output(calendar, out);
    } catch (final ContentNotFoundException e) {
      return404(resp);
      return;
    } catch (final ValidationException e) {
      LOG.warn("Invalid calendar conversion in " + token, e);
    }
  }
コード例 #19
0
ファイル: CalendarUtils.java プロジェクト: CooSocial/cosmo
 public static boolean hasSupportedComponent(Calendar calendar) {
   for (Object component : calendar.getComponents()) {
     if (isSupportedComponent(((CalendarComponent) component).getName())) {
       return true;
     }
   }
   return false;
 }
コード例 #20
0
  /**
   * @param ownerIdentifier
   * @param weekStart
   * @param visitorUsername
   * @param model
   * @return
   * @throws NotAVisitorException
   * @throws CalendarUserNotFoundException
   */
  @RequestMapping(
      value = "/admin/schedule-debug/{ownerIdentifier}/visitor-conflicts.json",
      method = RequestMethod.GET)
  public View visitorConflicts(
      @PathVariable("ownerIdentifier") long ownerIdentifier,
      @RequestParam(value = "weekStart", required = false, defaultValue = "1") int weekStart,
      @RequestParam(value = "visitorUsername", required = true) String visitorUsername,
      final ModelMap model)
      throws NotAVisitorException, CalendarAccountNotFoundException {

    ICalendarAccount visitorAccount = this.calendarAccountDao.getCalendarAccount(visitorUsername);
    if (visitorAccount == null) {
      throw new NotAVisitorException(visitorUsername + " not found");
    }
    IScheduleVisitor visitor = this.visitorDao.toVisitor(visitorAccount);

    IScheduleOwner owner = ownerDao.locateOwnerByAvailableId(ownerIdentifier);
    if (owner == null) {
      throw new CalendarAccountNotFoundException("no owner found for id " + ownerIdentifier);
    }
    VisibleScheduleRequestConstraints requestConstraints =
        VisibleScheduleRequestConstraints.newInstance(owner, weekStart);

    List<AvailableBlock> visitorConflicts =
        this.schedulingAssistantService.calculateVisitorConflicts(
            visitor,
            owner,
            requestConstraints.getTargetStartDate(),
            requestConstraints.getTargetEndDate());
    List<String> conflictBlocks = new ArrayList<String>();
    SimpleDateFormat df = CommonDateOperations.getDateTimeFormat();
    for (AvailableBlock b : visitorConflicts) {
      conflictBlocks.add(df.format(b.getStartTime()));
    }
    model.addAttribute("conflicts", conflictBlocks);

    Calendar visitorCalendar =
        this.calendarDataDao.getCalendar(
            visitorAccount,
            requestConstraints.getTargetStartDate(),
            requestConstraints.getTargetEndDate());
    model.addAttribute("visitorCalendarData", visitorCalendar.toString());
    return new MappingJacksonJsonView();
  }
コード例 #21
0
ファイル: DavJournal.java プロジェクト: ashanan/cosmo
  /**
   * Imports a calendar object containing a VJOURNAL. Sets the following properties:
   *
   * <ul>
   *   <li>display name: the VJOURNAL's SUMMARY (or the item's name, if the SUMMARY is blank)
   *   <li>icalUid: the VJOURNAL's UID
   *   <li>body: the VJOURNAL's DESCRIPTION
   * </ul>
   */
  public void setCalendar(Calendar cal) throws DavException {
    NoteItem note = (NoteItem) getItem();

    ComponentList vjournals = cal.getComponents(Component.VJOURNAL);
    if (vjournals.isEmpty())
      throw new UnprocessableEntityException("VCALENDAR does not contain any VJOURNALS");

    EntityConverter converter = new EntityConverter(getEntityFactory());
    converter.convertJournalCalendar(note, cal);
  }
コード例 #22
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());
    }
  }
コード例 #23
0
ファイル: DavTask.java プロジェクト: CooSocial/cosmo
  /**
   * Imports a calendar object containing a VTODO. Sets the following properties:
   *
   * <ul>
   *   <li>display name: the VTODO's SUMMARY (or the item's name, if the SUMMARY is blank)
   *   <li>icalUid: the VTODO's UID
   *   <li>body: the VTODO's DESCRIPTION
   *   <li>reminderTime: if the VTODO has a DISPLAY VALARM the reminderTime will be set to the
   *       trigger time
   * </ul>
   *
   * @param cal The calendar imported.
   * @throws CosmoDavException - if something is wrong this exception is thrown.
   */
  public void setCalendar(Calendar cal) throws CosmoDavException {
    NoteItem note = (NoteItem) getItem();

    ComponentList vtodos = cal.getComponents(Component.VTODO);
    if (vtodos.isEmpty()) {
      throw new UnprocessableEntityException("VCALENDAR does not contain any VTODOS");
    }

    EntityConverter converter = new EntityConverter(getEntityFactory());
    converter.convertTaskCalendar(note, cal);
  }
コード例 #24
0
  // TODO: this is work in progress; see issue 48
  @Ignore
  @Test
  public void queryPartialCalendar() throws CalDAV4JException {
    Calendar calendar = null;
    GenerateQuery gq = new GenerateQuery();

    // query by UID in a given timerange
    calendar = null;
    gq.setFilter("VEVENT : UID==" + ICS_GOOGLE_DAILY_NY_5PM_UID);
    gq.setRecurrenceSet("20060101T170000Z", "20060103T230000Z", CalendarData.EXPAND);

    List<Calendar> calendars = collection.queryCalendars(fixture.getHttpClient(), gq.generate());
    assertNotNull(calendars);
    assertEquals("bad number of responses: ", 3, calendars.size());
    for (Calendar c : calendars) {
      assertEquals(ICalendarUtils.getUIDValue(calendar), ICS_GOOGLE_DAILY_NY_5PM_UID);
      assertNotNull(
          ICalendarUtils.getPropertyValue(
              c.getComponent(Component.VEVENT), Property.RECURRENCE_ID));
    }
    // check if is in cache

  }
コード例 #25
0
  /**
   * Tests limit floating recurrence set.
   *
   * @throws Exception - if something is wrong this exception is thrown.
   */
  @Test
  public void testLimitFloatingRecurrenceSet() throws Exception {
    CalendarBuilder cb = new CalendarBuilder();
    FileInputStream fis = new FileInputStream(baseDir + "limit_recurr_float_test.ics");
    Calendar calendar = cb.build(fis);

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

    OutputFilter filter = new OutputFilter("test");
    DateTime start = new DateTime("20060102T170000");
    DateTime end = new DateTime("20060104T170000");

    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 override is 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 2", c.getProperties().getProperty("SUMMARY").getValue());
    }
  }
コード例 #26
0
ファイル: ICalTools.java プロジェクト: NCIP/psc
 public static Calendar generateICSCalendarForActivities(
     Calendar icsCalendar,
     Date date,
     Collection<ScheduledActivity> scheduledActivities,
     String baseUrl,
     Boolean includeSubject) {
   for (final ScheduledActivity scheduleActivity : scheduledActivities) {
     VEvent vEvent =
         generateAllDayEventForScheduleActivity(date, scheduleActivity, baseUrl, includeSubject);
     if (vEvent != null) {
       icsCalendar.getComponents().add(vEvent);
     }
   }
   return icsCalendar;
 }
コード例 #27
0
ファイル: CalendarUtils.java プロジェクト: CooSocial/cosmo
 public static boolean hasMultipleComponentTypes(Calendar calendar) {
   String found = null;
   for (Object component : calendar.getComponents()) {
     if (component instanceof VTimeZone) {
       continue;
     }
     if (found == null) {
       found = ((CalendarComponent) component).getName();
       continue;
     }
     if (!found.equals(((CalendarComponent) component).getName())) {
       return true;
     }
   }
   return false;
 }
コード例 #28
0
ファイル: Ical.java プロジェクト: stefanaj/TvTor
  public Collection<?> getCollectionOfTodaysEvents(Calendar calendar, int days_ago) {
    java.util.Calendar today = java.util.Calendar.getInstance();
    today.set(java.util.Calendar.HOUR_OF_DAY, 0 - 24 * days_ago);
    today.clear(java.util.Calendar.MINUTE);
    today.clear(java.util.Calendar.SECOND);

    // create a period starting now with a duration of one (1) day..
    Period period = new Period(new DateTime(today.getTime()), new Dur(1, 0, 0, 0));
    Rule[] rules;
    rules = new Rule[1];
    rules[0] = new PeriodRule(period);

    Filter filter = new Filter(rules, Filter.MATCH_ALL);

    Collection<?> eventsToday = filter.filter(calendar.getComponents(Component.VEVENT));

    return eventsToday;
  }
コード例 #29
0
  public void testICalendarAttribute() throws Exception {
    User user = getUser(userDao, "testuser");
    CollectionItem root = (CollectionItem) contentDao.getRootItem(user);

    ContentItem item = generateTestContent();

    ICalendarAttribute icalAttr = new HibICalendarAttribute();
    icalAttr.setQName(new HibQName("icalattribute"));
    icalAttr.setValue(helper.getInputStream("vjournal.ics"));
    item.addAttribute(icalAttr);

    ContentItem newItem = contentDao.createContent(root, item);

    clearSession();

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

    Attribute attr = queryItem.getAttribute(new HibQName("icalattribute"));
    Assert.assertNotNull(attr);
    Assert.assertTrue(attr instanceof ICalendarAttribute);

    net.fortuna.ical4j.model.Calendar calendar =
        (net.fortuna.ical4j.model.Calendar) attr.getValue();
    Assert.assertNotNull(calendar);

    net.fortuna.ical4j.model.Calendar expected =
        CalendarUtils.parseCalendar(helper.getInputStream("vjournal.ics"));

    Assert.assertEquals(expected.toString(), calendar.toString());

    calendar.getProperties().add(new ProdId("blah"));

    contentDao.updateContent(queryItem);

    clearSession();

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

    ICalendarAttribute ica =
        (ICalendarAttribute) queryItem.getAttribute(new HibQName("icalattribute"));
    Assert.assertFalse(expected.toString().equals(ica.getValue().toString()));
  }
コード例 #30
0
  @Override
  @SuppressWarnings("unchecked")
  public String encode(List<CalendarEvent> events) {

    if (events == null || events.isEmpty()) {
      throw new IllegalArgumentException("The calendar events must be defined to encode them");
    }
    Calendar calendarIcs = new Calendar();
    calendarIcs.getProperties().add(new ProdId("-//Silverpeas//iCal4j 1.1//FR"));
    calendarIcs.getProperties().add(Version.VERSION_2_0);
    calendarIcs.getProperties().add(CalScale.GREGORIAN);
    List<VEvent> iCalEvents = new ArrayList<VEvent>();
    ByteArrayOutputStream output = new ByteArrayOutputStream(10240);
    for (CalendarEvent event : events) {
      Date startDate = anICal4JDateCodec().encode(event.getStartDate());
      Date endDate = anICal4JDateCodec().encode(event.getEndDate());
      VEvent iCalEvent;
      if (event.isOnAllDay() && startDate.equals(endDate)) {
        iCalEvent = new VEvent(startDate, event.getTitle());
      } else {
        iCalEvent = new VEvent(startDate, endDate, event.getTitle());
      }

      // Generate UID
      iCalEvent.getProperties().add(generator.generateUid());

      // Add recurring data if any
      if (event.isRecurring()) {
        CalendarEventRecurrence eventRecurrence = event.getRecurrence();
        Recur recur = anICal4JRecurrenceCodec().encode(eventRecurrence);
        iCalEvent.getProperties().add(new RRule(recur));
        iCalEvent.getProperties().add(exceptionDatesFrom(eventRecurrence));
      }
      // Add Description
      iCalEvent.getProperties().add(new Description(event.getDescription()));
      // Add Classification
      iCalEvent.getProperties().add(new Clazz(event.getAccessLevel()));
      // Add Priority
      iCalEvent.getProperties().add(new Priority(event.getPriority()));

      // Add location if any
      if (!event.getLocation().isEmpty()) {
        iCalEvent.getProperties().add(new Location(event.getLocation()));
      }

      // Add event URL if any
      if (event.getUrl() != null) {
        try {
          iCalEvent.getProperties().add(new Url(event.getUrl().toURI()));
        } catch (URISyntaxException ex) {
          throw new EncodingException(ex.getMessage(), ex);
        }
      }

      // Add Categories
      TextList categoryList = new TextList(event.getCategories().asArray());
      if (!categoryList.isEmpty()) {
        iCalEvent.getProperties().add(new Categories(categoryList));
      }
      // Add attendees
      for (String attendee : event.getAttendees().asList()) {
        try {
          iCalEvent.getProperties().add(new Attendee(attendee));
        } catch (URISyntaxException ex) {
          throw new EncodingException("Malformed attendee URI: " + attendee, ex);
        }
      }

      iCalEvents.add(iCalEvent);
    }
    calendarIcs.getComponents().addAll(iCalEvents);
    CalendarOutputter outputter = new CalendarOutputter();
    try {
      outputter.output(calendarIcs, output);
      return output.toString(CharEncoding.UTF_8);
    } catch (Exception ex) {
      throw new EncodingException(
          "The encoding of the events in iCal formatted text has failed!", ex);
    } finally {
      IOUtils.closeQuietly(output);
    }
  }