Exemple #1
0
 protected void generateUID() {
   UidGenerator generator =
       new UidGenerator(
           new SimpleHostInfo(DavSyncAdapter.getAndroidID()),
           String.valueOf(android.os.Process.myPid()));
   uid = generator.generateUid().getValue();
 }
  @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);
    }
  }
Exemple #3
0
  /** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    String[] courseids = request.getParameterValues("courses");
    // Saving the course ids as a session attribute (not necessary, might be better for saving)

    HttpSession session = request.getSession(true);
    session.setAttribute("courses", courseids);

    // Get course and time info for each id
    if (courseids == null) {

    } else {
      try {
        for (String id : courseids) {
          Integer courseid = Integer.parseInt(id);
          PreparedStatement getCourse =
              con.prepareStatement(
                  "SELECT title, department, number, section " + "FROM courses WHERE id=?;");
          getCourse.setInt(1, courseid);
          PreparedStatement getTime =
              con.prepareStatement(
                  "SELECT day, starttime, endtime FROM times " + "WHERE course_id=?;");
          getTime.setInt(1, courseid);
          ResultSet courseResult = getCourse.executeQuery();
          ResultSet timesResult = getTime.executeQuery();
          while (courseResult.next()) {
            // Generating the course from the DB, lets us utilize timeblocks
            Course course = new Course();
            course.setTitle(courseResult.getString("title"));
            course.setDepartment(courseResult.getString("department"));
            course.setNumber(courseResult.getString("number"));
            course.setSection(courseResult.getString("section"));
            String courseTitle =
                course.getDepartment()
                    + course.getNumber()
                    + "-"
                    + course.getSection()
                    + ": "
                    + course.getTitle();
            while (timesResult.next()) {
              course.addTime(
                  timesResult.getString("day").charAt(0),
                  timesResult.getInt("starttime"),
                  timesResult.getInt("endtime"));
            }

            // Now parse the timeshttp://ical4j.sourceforge.net/introduction.html for the timeblocks
            Map<String, Set<Character>> timeblocks = course.getTimeBlocks();
            for (String startend : timeblocks.keySet()) {
              String[] StartEnd = startend.split("-");
              Integer startInt = Integer.parseInt(StartEnd[0]);
              Integer endInt = Integer.parseInt(StartEnd[1]);
              java.util.Calendar startDate = this.getTimeCalendar(startInt);
              java.util.Calendar endDate = this.getTimeCalendar(endInt);
              DateTime startTime = new DateTime(startDate.getTime());
              DateTime endTime = new DateTime(endDate.getTime());

              VEvent courseEvent = new VEvent(startTime, endTime, courseTitle);
              Recur recur = new Recur(Recur.WEEKLY, null);
              // add the proper days to the recurrence
              for (char day : timeblocks.get(startend)) {
                recur.getDayList().add(dayMap.get(day));
              }
              courseEvent.getProperties().add(new RRule(recur));
              // Get unique identifier
              UidGenerator ug = new UidGenerator("uidGen");
              Uid uid = ug.generateUid();
              courseEvent.getProperties().add(uid);
              // Finally, add the time block to the calendar
              this.ical.getComponents().add(courseEvent);
            }
          }
        }
      } catch (SQLException e) {
        e.printStackTrace();
      }
    }
    // Time to handle file download
    try {
      // making the file and outputting the calendar info
      File file = new File("mycalendar.ics");
      int length = 0;
      FileOutputStream fout = new FileOutputStream(file);
      CalendarOutputter outputter = new CalendarOutputter();
      outputter.output(ical, fout);
      ServletOutputStream outStream = response.getOutputStream();
      response.setContentType("text/calendar");
      response.setContentLength((int) file.length());
      // sets HTTP header
      response.setHeader("Content-Disposition", "attachment; filename=calendar.ics");
      byte[] byteBuffer = new byte[BUFSIZE];
      DataInputStream in = new DataInputStream(new FileInputStream(file));

      // reads the file's bytes and writes them to the response stream
      while ((in != null) && ((length = in.read(byteBuffer)) != -1)) {
        outStream.write(byteBuffer, 0, length);
      }

      in.close();
      outStream.close();
    } catch (ValidationException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }