/*
   * (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;
  }
  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;
    }
  }
  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()));
  }
Beispiel #4
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 + "]");
      }
    }
  }
  /**
   * @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();
  }
  /** @param calendar the calendar to set */
  public final void setCalendar(final Calendar calendar) {
    this.calendar = calendar;

    try {
      Uid uidProp = Calendars.getUid(calendar);
      this.uid = uidProp.getValue();
      setName(uidProp.getValue());
    } catch (ConstraintViolationException e) {
      LOG.error("Invalid UID", e);
      setName("calendar");
    }

    file = new JcrFile();
    file.setName("data");
    file.setDataProvider(new JcrDataProviderImpl(calendar.toString().getBytes()));
    //        file.setMimeType(MediaType.ICALENDAR_2_0.getContentType());
    file.setMimeType(Calendars.getContentType(calendar, null));
    file.setLastModified(java.util.Calendar.getInstance());

    for (Object component : calendar.getComponents()) {

      // save first available summary..
      if (summary == null) {
        Summary summaryProp = (Summary) ((Component) component).getProperty(Property.SUMMARY);
        if (summaryProp != null) {
          this.summary = summaryProp.getValue();
        }
      }

      // save first available description..
      if (description == null) {
        Description descriptionProp =
            (Description) ((Component) component).getProperty(Property.DESCRIPTION);
        if (descriptionProp != null) {
          description = new JcrFile();
          description.setName("text");
          description.setMimeType("text/plain");
          description.setDataProvider(
              new JcrDataProviderImpl(descriptionProp.getValue().getBytes()));
          description.setLastModified(java.util.Calendar.getInstance());
        }
      }

      // save attachments..
      attachments.clear();
      PropertyList attachments = ((Component) component).getProperties(Property.ATTACH);
      for (Object attach : attachments) {
        try {
          JcrFile attachment = new JcrFile();
          attachment.setName("attachment");
          if (Value.BINARY.equals(((Property) attach).getParameter(Parameter.VALUE))) {
            attachment.setDataProvider(new JcrDataProviderImpl(((Attach) attach).getBinary()));
            FmtType contentType = (FmtType) ((Property) attach).getParameter(Parameter.FMTTYPE);
            if (contentType != null) {
              attachment.setMimeType(contentType.getValue());
            }
          } else {
            ByteArrayOutputStream aout = new ByteArrayOutputStream();
            IOUtils.copy(((Attach) attach).getUri().toURL().openStream(), aout);
            attachment.setDataProvider(new JcrDataProviderImpl(aout.toByteArray()));
          }
          attachment.setLastModified(java.util.Calendar.getInstance());
          this.attachments.add(attachment);
        } catch (Exception e) {
          LOG.error("Error saving attachment", e);
        }
      }
    }
  }
  /**
   * @param ownerId
   * @param highContrast
   * @param visitorUsername
   * @return
   * @throws NotAVisitorException
   * @throws CalendarUserNotFoundException
   */
  @RequestMapping(
      value = "/admin/schedule-debug/{ownerIdentifier}/view.html",
      method = RequestMethod.GET)
  public String displaySchedule(
      @PathVariable("ownerIdentifier") long ownerIdentifier,
      @RequestParam(value = "highContrast", required = false, defaultValue = "false")
          boolean highContrast,
      @RequestParam(value = "weekStart", required = false, defaultValue = "0") int weekStart,
      @RequestParam(value = "visitorUsername", required = true) String visitorUsername,
      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);
    model.addAttribute("visitor", visitor);
    IScheduleOwner selectedOwner = ownerDao.locateOwnerByAvailableId(ownerIdentifier);
    if (selectedOwner == null) {
      throw new CalendarAccountNotFoundException("no owner found for id " + ownerIdentifier);
    }
    VisibleScheduleRequestConstraints requestConstraints =
        VisibleScheduleRequestConstraints.newInstance(selectedOwner, weekStart);
    if (LOG.isDebugEnabled()) {
      LOG.debug(
          "displaySchedule request, visitor: "
              + visitor
              + "; weekStart: "
              + weekStart
              + "requestConstraints "
              + requestConstraints);
    }

    Calendar ownerCalendar =
        this.calendarDataDao.getCalendar(
            selectedOwner.getCalendarAccount(),
            requestConstraints.getTargetStartDate(),
            requestConstraints.getTargetEndDate());
    model.addAttribute("ownerCalendarData", ownerCalendar.toString());
    model.addAttribute("noteboard", selectedOwner.getPreference(Preferences.NOTEBOARD));
    model.addAttribute("owner", selectedOwner);
    model.addAttribute("highContrast", highContrast);

    VisibleSchedule schedule;

    if (selectedOwner.hasMeetingLimit()) {
      // we have to look at the whole visible schedule for attendings
      schedule = schedulingAssistantService.getVisibleSchedule(visitor, selectedOwner);
      if (selectedOwner.isExceedingMeetingLimit(schedule.getAttendingCount())) {
        // return attending only view
        List<AvailableBlock> attendingList = schedule.getAttendingList();
        model.addAttribute("attendingList", attendingList);
        return "admin/debug-already-attending";
      } else {
        // extract start->end from visibleSchedule
        schedule =
            schedule.subset(
                requestConstraints.getTargetStartDate(), requestConstraints.getTargetEndDate());
      }

    } else {
      // only pull start->end of schedule
      schedule =
          schedulingAssistantService.getVisibleSchedule(
              visitor,
              selectedOwner,
              requestConstraints.getTargetStartDate(),
              requestConstraints.getTargetEndDate());
    }

    model.addAttribute("visibleSchedule", schedule);
    model.addAttribute("scheduleStart", schedule.getScheduleStart());
    model.addAttribute("prevWeekStart", requestConstraints.getPrevWeekIndex());
    model.addAttribute("nextWeekStart", requestConstraints.getNextWeekIndex());
    model.addAttribute("weekStart", requestConstraints.getConstrainedWeekStart());
    model.addAttribute("ownerVisitorSamePerson", selectedOwner.isSamePerson(visitor));
    return "admin/debug-visible-schedule";
  }