Ejemplo n.º 1
0
 /**
  * Convert Calendar object to String
  *
  * @param calendar
  * @return string representation of calendar
  * @throws ValidationException - if something is wrong this exception is thrown.
  * @throws IOException - if something is wrong this exception is thrown.
  */
 public static String outputCalendar(Calendar calendar) throws ValidationException, IOException {
   if (calendar == null) {
     return null;
   }
   CalendarOutputter outputter = new CalendarOutputter();
   StringWriter sw = new StringWriter();
   outputter.output(calendar, sw);
   return sw.toString();
 }
Ejemplo n.º 2
0
  @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;
  }
Ejemplo n.º 3
0
 public static void storeToDisk(String calendarId, String filename, Calendar calendar) {
   try {
     FileOutputStream fout = new FileOutputStream(getCacheFile(calendarId, filename));
     CalendarOutputter outputter = new CalendarOutputter();
     outputter.setValidating(false);
     outputter.output(calendar, fout);
     fout.flush();
     fout.close();
   } catch (IOException e) {
     log.error("cannot store event '{}' to disk", filename);
   } catch (ValidationException e) {
     log.error("cannot store event '{}' to disk", filename);
   }
 }
Ejemplo n.º 4
0
 public static String createICSCalendarRepresentation(final Calendar icsCalendar) {
   try {
     final CalendarOutputter output = new CalendarOutputter();
     output.setValidating(false);
     StringWriter icsCalendarWritter = new StringWriter();
     output.output(icsCalendar, icsCalendarWritter);
     icsCalendarWritter.close();
     return icsCalendarWritter.toString();
   } catch (IOException e) {
     throw new StudyCalendarSystemException("Error while creating ics calendar", e);
   } catch (ValidationException ve) {
     throw new StudyCalendarSystemException("Error while creating ics calendar", ve);
   }
 }
Ejemplo n.º 5
0
  /*
   * (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);
    }
  }
Ejemplo n.º 6
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);
    }
  }
Ejemplo n.º 7
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();
    }
  }
  /** {@inheritDoc} */
  public String toFile(Calendar calendar) {

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

    // null check
    if (calendar == null) {
      log.error("Calendar is null, cannot generate ICS file.");
      return null;
    }

    String path = generateFilePath(UUID.randomUUID().toString());

    // test file
    File file = new File(path);
    try {
      if (!file.createNewFile()) {
        log.error("Couldn't write file to: " + path);
        return null;
      }
    } catch (IOException e) {
      log.error(
          "An error occurred trying to write file to: "
              + path
              + " : "
              + e.getClass()
              + " : "
              + e.getMessage());
      return null;
    }

    // if cleanup enabled, mark for deletion when the JVM exits.
    if (sakaiProxy.isCleanupEnabled()) {
      file.deleteOnExit();
    }

    FileOutputStream fout;
    try {
      fout = new FileOutputStream(file);

      CalendarOutputter outputter = new CalendarOutputter();
      outputter.output(calendar, fout);

      fout.flush();
      fout.close();
    } catch (FileNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (ValidationException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    return path;
  }