Java Code Examples for net.fortuna.ical4j.data.CalendarBuilder#build()

The following examples show how to use net.fortuna.ical4j.data.CalendarBuilder#build() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: IcsConverter.java    From ganttproject with GNU General Public License v3.0 7 votes vote down vote up
public static void main(String[] args) throws Exception {
  Args mainArgs = new Args();
  try {
    new JCommander(new Object[] { mainArgs }, args);
  } catch (Throwable e) {
    e.printStackTrace();
    return;
  }
  if (mainArgs.file.size() != 1) {
    System.err.println("Only 1 input file should be specified");
    return;
  }
  CalendarBuilder builder = new CalendarBuilder();
  Calendar c = builder.build(new UnfoldingReader(new FileReader(mainArgs.file.get(0))));
  for (Component comp : (List<Component>)c.getComponents()) {
    System.err.println(comp);
  }
}
 
Example 2
Source File: TeamCalImportPage.java    From projectforge-webapp with GNU General Public License v3.0 6 votes vote down vote up
protected void importEvents()
{
  checkAccess();
  final FileUpload fileUpload = form.fileUploadField.getFileUpload();
  if (fileUpload != null) {
    try {
      final InputStream is = fileUpload.getInputStream();
      actionLog.reset();
      final String clientFilename = fileUpload.getClientFileName();
      final CalendarBuilder builder = new CalendarBuilder();
      final Calendar calendar = builder.build(is);
      final ImportStorage<TeamEventDO> storage = teamCalImportDao.importEvents(calendar, clientFilename, actionLog);
      setStorage(storage);
    } catch (final Exception ex) {
      log.error(ex.getMessage(), ex);
      error("An error occurred (see log files for details): " + ex.getMessage());
      clear();
    } finally {
      fileUpload.closeStreams();
    }
  }
}
 
Example 3
Source File: EventCollectionResource.java    From XPagesExtensionLibrary with Apache License 2.0 6 votes vote down vote up
private String extractUid(String icalendar) throws IOException, ParserException {
    
    String uid = null;
    StringReader reader = new StringReader(icalendar);
    CalendarBuilder builder = new CalendarBuilder();
    Calendar calendar = builder.build(new UnfoldingReader(reader, true));
    if ( calendar != null && calendar.getComponents() != null ) {
        Iterator<Component> iterator = calendar.getComponents().iterator();
        while (iterator.hasNext()) {
            Component component = iterator.next();
            if ( component instanceof VEvent ) {
                uid = ((VEvent)component).getUid().getValue();
                break;
            }
        }
    }
    
    return uid;
}
 
Example 4
Source File: ICalendarService.java    From axelor-open-suite with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Load the calendar events from the given reader.
 *
 * @param calendar the target {@link ICalendar}
 * @param reader the input source reader
 * @throws IOException
 * @throws ParserException
 */
@Transactional(rollbackOn = {Exception.class})
public void load(ICalendar calendar, Reader reader) throws IOException, ParserException {
  Preconditions.checkNotNull(calendar, "calendar can't be null");
  Preconditions.checkNotNull(reader, "reader can't be null");

  final CalendarBuilder builder = new CalendarBuilder();
  final Calendar cal = builder.build(reader);

  if (calendar.getName() == null && cal.getProperty(X_WR_CALNAME) != null) {
    calendar.setName(cal.getProperty(X_WR_CALNAME).getValue());
  }

  for (Object item : cal.getComponents(Component.VEVENT)) {
    findOrCreateEvent((VEvent) item, calendar);
  }
}
 
Example 5
Source File: LimitRecurrenceSetTest.java    From cosmo with Apache License 2.0 5 votes vote down vote up
/**
 * 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();
    
    StringBuilder buffer = new StringBuilder();
    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<VEvent> vevents = filterCal.getComponents().getComponents(VEvent.VEVENT);        
    for(VEvent c : vevents) {            
        Assert.assertNotSame("event 6 changed 2",c.getProperties().getProperty("SUMMARY").getValue());
    }   
}
 
Example 6
Source File: LimitRecurrenceSetTest.java    From cosmo with Apache License 2.0 5 votes vote down vote up
/**
 * 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();
    
    StringBuilder buffer = new StringBuilder();
    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<VEvent> vevents = filterCal.getComponents().getComponents(VEvent.VEVENT);
    
    for(VEvent c : vevents) {            
        Assert.assertNotSame("event 6 changed",c.getProperties().getProperty("SUMMARY").getValue());
        Assert.assertNotSame("event 6 changed 2",c.getProperties().getProperty("SUMMARY").getValue());
    }   
}
 
Example 7
Source File: RecurrenceExpanderTest.java    From cosmo with Apache License 2.0 5 votes vote down vote up
/**
 * Gets calendar.
 * @param name The name.
 * @return The calendar.
 * @throws Exception - if something is wrong this exception is thrown.
 */
protected Calendar getCalendar(String name) throws Exception {
    CalendarBuilder cb = new CalendarBuilder();
    InputStream in = getClass().getClassLoader().getResourceAsStream("expander/" + name);
    if (in == null) {
        throw new IllegalStateException("resource " + name + " not found");
    }        
    Calendar calendar = cb.build(in);
    return calendar;
}
 
Example 8
Source File: InstanceListTest.java    From cosmo with Apache License 2.0 5 votes vote down vote up
/**
 * Gets calendar.
 *
 * @param name The name.
 * @return The calendar.
 * @throws Exception - if something is wrong this exception is thrown.
 */
protected Calendar getCalendar(String name) throws Exception {
    CalendarBuilder cb = new CalendarBuilder();
    InputStream in = getClass().getClassLoader().getResourceAsStream("instancelist/" + name);
    if (in == null) {
        throw new IllegalStateException("resource " + name + " not found");
    }
    Calendar calendar = cb.build(in);
    return calendar;
}
 
Example 9
Source File: HibernateContentDaoTest.java    From cosmo with Apache License 2.0 5 votes vote down vote up
/**
 * Tests content dao create freeBusy.
 * 
 * @throws Exception
 *             - if something is wrong this exception is thrown.
 */
@Test
public void testContentDaoCreateFreeBusy() throws Exception {
    User user = getUser(userDao, "testuser");
    CollectionItem root = (CollectionItem) contentDao.getRootItem(user);

    FreeBusyItem newItem = new HibFreeBusyItem();
    newItem.setOwner(user);
    newItem.setName("test");
    newItem.setIcalUid("icaluid");

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

    newItem.setFreeBusyCalendar(calendar);

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

    Assert.assertTrue(getHibItem(newItem).getId() > -1);
    Assert.assertNotNull(newItem.getUid());

    clearSession();

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

    helper.verifyItem(newItem, queryItem);
}
 
Example 10
Source File: HibernateContentDaoTest.java    From cosmo with Apache License 2.0 5 votes vote down vote up
/**
 * Tests content dao create availability.
 * 
 * @throws Exception
 *             - if something is wrong this exception is thrown.
 */
@Test
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.assertNotNull(newItem.getUid());

    clearSession();

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

    helper.verifyItem(newItem, queryItem);
}
 
Example 11
Source File: EventStampTest.java    From cosmo with Apache License 2.0 5 votes vote down vote up
/**
 * Gets calendar.
 * @param name The name.
 * @return The calendar.
 * @throws Exception - if something is wrong this exception is thrown.
 */
protected Calendar getCalendar(String name) throws Exception {
    CalendarBuilder cb = new CalendarBuilder();
    FileInputStream fis = new FileInputStream(baseDir + name);
    Calendar calendar = cb.build(fis);
    return calendar;
}
 
Example 12
Source File: EntityConverterTest.java    From cosmo with Apache License 2.0 5 votes vote down vote up
/**
 * Gets calendar.
 * @param name The name.
 * @return The calendar.
 * @throws Exception - if something is wrong this exception is thrown.
 */
protected Calendar getCalendar(String name) throws Exception {
    CalendarBuilder cb = new CalendarBuilder();
    FileInputStream fis = new FileInputStream(baseDir + name);
    Calendar calendar = cb.build(fis);
    return calendar;
}
 
Example 13
Source File: DropIcsPanel.java    From projectforge-webapp with GNU General Public License v3.0 5 votes vote down vote up
/**
 * @see org.projectforge.web.wicket.components.DropFileContainer#onStringImport(org.apache.wicket.ajax.AjaxRequestTarget,
 *      java.lang.String, java.lang.String)
 */
@Override
protected void onStringImport(final AjaxRequestTarget target, final String fileName, final String content)
{

  try {
    final CalendarBuilder builder = new CalendarBuilder();
    final Calendar calendar = builder.build(new StringReader(content));
    onIcsImport(target, calendar);
  } catch (final Exception ex) {
    // TODO ju: handle exception
    log.fatal("unable to import dropped calendar", ex);
  }
}
 
Example 14
Source File: StandardContentServiceTest.java    From cosmo with Apache License 2.0 5 votes vote down vote up
/**
 * Gets calendar.
 * @param filename The file name.
 * @return The calendar.
 * @throws Exception - if something is wrong this exception is thrown.
 */
private Calendar getCalendar(String filename) throws Exception {
    CalendarBuilder cb = new CalendarBuilder();
    FileInputStream fis = new FileInputStream(baseDir + filename);
    Calendar calendar = cb.build(fis);
    return calendar;
}
 
Example 15
Source File: LimitRecurrenceSetTest.java    From cosmo with Apache License 2.0 5 votes vote down vote up
/**
 * 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();
    
    StringBuilder buffer = new StringBuilder();
    filter.filter(calendar, buffer);
    StringReader sr = new StringReader(buffer.toString());
    
    Calendar filterCal = cb.build(sr);
    
    ComponentList<CalendarComponent> 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

    ComponentList<CalendarComponent> events = comps.getComponents("VEVENT");
    for(CalendarComponent c : events) {            
        Assert.assertNotSame("event 6 changed 3",c.getProperties().getProperty("SUMMARY").getValue());
        Assert.assertNotSame("event 6 changed 4",c.getProperties().getProperty("SUMMARY").getValue());
    }
}
 
Example 16
Source File: CalendarFilterEvaluaterTest.java    From cosmo with Apache License 2.0 5 votes vote down vote up
/**
 * Gets calendar.
 * @param name The name.
 * @return The calendar.
 * @throws Exception - if something is wrong this exception is thrown.
 */
protected Calendar getCalendar(String name) throws Exception {
    CalendarBuilder cb = new CalendarBuilder();
    InputStream in = getClass().getClassLoader().getResourceAsStream(name);
    if (in == null) {
        throw new IllegalStateException("resource " + name + " not found");
    }        
    Calendar calendar = cb.build(in);
    return calendar;
}
 
Example 17
Source File: ExpandRecurringEventsTest.java    From cosmo with Apache License 2.0 4 votes vote down vote up
/**
 * Tests expand event.
 * @throws Exception - if something is wrong this exception is thrown.
 */
@Test
public void testExpandEvent() throws Exception {
    CalendarBuilder cb = new CalendarBuilder();
    FileInputStream fis = new FileInputStream(baseDir + "expand_recurr_test1.ics");
    Calendar calendar = cb.build(fis);
    
    Assert.assertEquals(1, 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("20060102T140000", tz);
    DateTime end = new DateTime("20060105T140000", tz);
    start.setUtc(true);
    end.setUtc(true);
    
    Period period = new Period(start, end);
    filter.setExpand(period);
    filter.setAllSubComponents();
    filter.setAllProperties();
    
    StringBuilder buffer = new StringBuilder();
    filter.filter(calendar, buffer);
    StringReader sr = new StringReader(buffer.toString());
    
    Calendar filterCal = cb.build(sr);
    
    ComponentList<VEvent> comps = filterCal.getComponents().getComponents("VEVENT");
    
    // Should expand to 3 event components
    Assert.assertEquals(3, comps.size());
            
    Iterator<VEvent> it = comps.iterator();
    VEvent event = it.next();
    
    Assert.assertEquals("event 6", event.getProperties().getProperty(Property.SUMMARY).getValue());
    Assert.assertEquals("20060102T190000Z", event.getStartDate().getDate().toString());
    Assert.assertEquals("20060102T190000Z", event.getRecurrenceId().getDate().toString());
    
    event = it.next();
    Assert.assertEquals("event 6", event.getProperties().getProperty(Property.SUMMARY).getValue());
    Assert.assertEquals("20060103T190000Z", event.getStartDate().getDate().toString());
    Assert.assertEquals("20060103T190000Z", event.getRecurrenceId().getDate().toString());
    
    event = it.next();
    Assert.assertEquals("event 6", event.getProperties().getProperty(Property.SUMMARY).getValue());
    Assert.assertEquals("20060104T190000Z", event.getStartDate().getDate().toString());
    Assert.assertEquals("20060104T190000Z", event.getRecurrenceId().getDate().toString());
    
    verifyExpandedCalendar(filterCal);
}
 
Example 18
Source File: MainActivity.java    From ICSImport with GNU General Public License v3.0 4 votes vote down vote up
@Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);

       Intent intent = getIntent();

Uri data = intent.getData();

try {
	//use ical4j to parse the event
	CalendarBuilder cb = new CalendarBuilder();
	Calendar calendar = null;
	calendar = cb.build(getStreamFromOtherSource(data));

	if (calendar != null) {

		Iterator i = calendar.getComponents(Component.VEVENT).iterator();

		while (i.hasNext()) {
			VEvent event = (VEvent) i.next();

			Intent insertIntent = new Intent(Intent.ACTION_INSERT)
				.setType("vnd.android.cursor.item/event");

			if (event.getStartDate() != null)
				insertIntent.putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, event.getStartDate().getDate().getTime());

			if (event.getEndDate() != null)
				insertIntent.putExtra(CalendarContract.EXTRA_EVENT_END_TIME, event.getEndDate().getDate().getTime());

			if (event.getSummary() != null)
				insertIntent.putExtra(CalendarContract.Events.TITLE, event.getSummary().getValue());

			if (event.getDescription() != null)
				insertIntent.putExtra(CalendarContract.Events.DESCRIPTION, event.getDescription().getValue());

			if (event.getLocation() != null) 
				insertIntent.putExtra(CalendarContract.Events.EVENT_LOCATION, event.getLocation().getValue());

			insertIntent.putExtra(CalendarContract.Events.ACCESS_LEVEL, CalendarContract.Events.ACCESS_PRIVATE);
			startActivity(insertIntent);

		}
	}

} catch (Exception e) {
	e.printStackTrace();
	Toast.makeText(getBaseContext(), "Invalid ICS file", Toast.LENGTH_LONG).show();
}
finish();

   }
 
Example 19
Source File: ExpandRecurringEventsTest.java    From cosmo with Apache License 2.0 4 votes vote down vote up
/**
 * Removed test expand with non recurring event.
 * @throws Exception - if something is wrong this exception is thrown.
 */
public void removedTestExpandNonRecurringEvent() throws Exception {
    CalendarBuilder cb = new CalendarBuilder();
    FileInputStream fis = new FileInputStream(baseDir + "expand_nonrecurr_test3.ics");
    Calendar calendar = cb.build(fis);
    
    Assert.assertEquals(1, 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("20060102T140000", tz);
    DateTime end = new DateTime("20060105T140000", tz);
    start.setUtc(true);
    end.setUtc(true);
    
    Period period = new Period(start, end);
    filter.setExpand(period);
    filter.setAllSubComponents();
    filter.setAllProperties();
    
    StringBuilder buffer = new StringBuilder();
    filter.filter(calendar, buffer);
    StringReader sr = new StringReader(buffer.toString());
    
    Calendar filterCal = cb.build(sr);
    
    ComponentList<VEvent> comps = filterCal.getComponents().getComponents("VEVENT");
    
    // Should be the same component
    Assert.assertEquals(1, comps.size());
            
    Iterator<VEvent> it = comps.iterator();
    VEvent event = it.next();
    
    Assert.assertEquals("event 6", event.getProperties().getProperty(Property.SUMMARY).getValue());
    Assert.assertEquals("20060102T190000Z", event.getStartDate().getDate().toString());
    Assert.assertNull(event.getRecurrenceId());
    
    verifyExpandedCalendar(filterCal);
}
 
Example 20
Source File: IcsFileImporter.java    From ganttproject with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Reads calendar events from file
 * @return a list of events if file was parsed successfully or null otherwise
 */
private static List<CalendarEvent> readEvents(File f) {
  try {
    CompatibilityHints.setHintEnabled(CompatibilityHints.KEY_RELAXED_PARSING, true);
    CalendarBuilder builder = new CalendarBuilder();
    List<CalendarEvent> gpEvents = Lists.newArrayList();
    Calendar c = builder.build(new UnfoldingReader(new FileReader(f)));
    for (Component comp : (List<Component>)c.getComponents()) {
      if (comp instanceof VEvent) {
        VEvent event = (VEvent) comp;
        if (event.getStartDate() == null) {
          GPLogger.log("No start date found, ignoring. Event="+event);
          continue;
        }
        Date eventStartDate = event.getStartDate().getDate();
        if (event.getEndDate() == null) {
          GPLogger.log("No end date found, using start date instead. Event="+event);
        }
        Date eventEndDate = event.getEndDate() == null ? eventStartDate : event.getEndDate().getDate();
        TimeDuration oneDay = GPTimeUnitStack.createLength(GPTimeUnitStack.DAY, 1);
        if (eventEndDate != null) {
          java.util.Date startDate = GPTimeUnitStack.DAY.adjustLeft(eventStartDate);
          java.util.Date endDate = GPTimeUnitStack.DAY.adjustLeft(eventEndDate);
          RRule recurrenceRule = (RRule) event.getProperty(Property.RRULE);
          boolean recursYearly = false;
          if (recurrenceRule != null) {
            recursYearly = Recur.YEARLY.equals(recurrenceRule.getRecur().getFrequency()) && 1 == recurrenceRule.getRecur().getInterval();
          }
          while (startDate.compareTo(endDate) <= 0) {
            Summary summary = event.getSummary();
            gpEvents.add(CalendarEvent.newEvent(
                startDate, recursYearly, CalendarEvent.Type.HOLIDAY,
                summary == null ? "" : summary.getValue(),
                null));
            startDate = GPCalendarCalc.PLAIN.shiftDate(startDate, oneDay);
          }
        }
      }
    }
    return gpEvents;
  } catch (IOException | ParserException e) {
    GPLogger.log(e);
    return null;
  }
}