net.fortuna.ical4j.model.TimeZone Java Examples

The following examples show how to use net.fortuna.ical4j.model.TimeZone. 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: IcsCalendarBuilder.java    From fredbet with Creative Commons Attribution Share Alike 4.0 International 7 votes vote down vote up
public byte[] build() {
    TimeZoneRegistry registry = TimeZoneRegistryFactory.getInstance().createRegistry();
    TimeZone timezone = registry.getTimeZone(timeZone);
    VTimeZone tz = timezone.getVTimeZone();
    VEvent vEvent = new VEvent(toDate(this.start), toDate(this.end), this.title);
    vEvent.getProperties().add(tz.getTimeZoneId());
    vEvent.getProperties().add(uidGenerator.generateUid());
    vEvent.getProperties().add(new Description(this.content));
    vEvent.getProperties().add(new Location(this.location));

    net.fortuna.ical4j.model.Calendar icsCalendar = new net.fortuna.ical4j.model.Calendar();
    icsCalendar.getProperties().add(new ProdId("-//FredBet//iCal4j 1.0//EN"));
    icsCalendar.getProperties().add(CalScale.GREGORIAN);
    icsCalendar.getProperties().add(Version.VERSION_2_0);

    icsCalendar.getComponents().add(vEvent);

    try (ByteArrayOutputStream out = new ByteArrayOutputStream();) {
        CalendarOutputter outputter = new CalendarOutputter();
        outputter.output(icsCalendar, out);
        return out.toByteArray();
    } catch (IOException e) {
        LOG.error(e.getMessage());
        return null;
    }
}
 
Example #2
Source File: ICalendarUtils.java    From cosmo with Apache License 2.0 6 votes vote down vote up
/**
 * Return a Date instance that represents the day that a point in
 * time translates into local time given a timezone.
 * @param utcDateTime point in time
 * @param tz timezone The timezone.
 * @return The date.
 */
public static Date normalizeUTCDateTimeToDate(DateTime utcDateTime, TimeZone tz) {
    if(!utcDateTime.isUtc()) {
        throw new IllegalArgumentException("datetime must be utc");
    }
    
    // if no timezone, use default
    if (tz == null) {
        return new Date(utcDateTime);
    }
    
    DateTime copy = (DateTime) Dates.getInstance(utcDateTime, utcDateTime);
    copy.setTimeZone(tz);
    
    try {
        return new Date(copy.toString().substring(0, 8));
    } catch (ParseException e) {
        throw new CosmoParseException("error creating Date instance", e);
    }
}
 
Example #3
Source File: ICal4JUtils.java    From projectforge-webapp with GNU General Public License v3.0 6 votes vote down vote up
public static List<net.fortuna.ical4j.model.Date> parseISODateStringsAsICal4jDates(final String csv, final TimeZone timeZone)
{
  final String[] sa = splitExDates(csv);
  if (sa == null) {
    return null;
  }
  final List<net.fortuna.ical4j.model.Date> result = new ArrayList<net.fortuna.ical4j.model.Date>();
  for (final String str : sa) {
    if (str == null) {
      continue;
    }
    Date date = null;
    if (str.matches("\\d{8}.*") == true) {
      date = parseICalDateString(str, timeZone);
    } else {
      date = parseISODateString(str);
    }
    if (date == null) {
      continue;
    }
    result.add(getICal4jDateTime(date, timeZone));
  }
  return result;
}
 
Example #4
Source File: RecurrenceExpander.java    From cosmo with Apache License 2.0 6 votes vote down vote up
/**
 * Expand recurring event for given time-range.
 * @param calendar calendar containing recurring event and modifications
 * @param rangeStart expand start
 * @param rangeEnd expand end
 * @param timezone Optional timezone to use for floating dates.  If null, the
 *        system default is used.
 * @return InstanceList containing all occurences of recurring event during
 *         time range
 */
public InstanceList getOcurrences(Calendar calendar, Date rangeStart, Date rangeEnd, TimeZone timezone) {
    ComponentList<VEvent> vevents = calendar.getComponents().getComponents(Component.VEVENT);
    
    List<Component> exceptions = new ArrayList<Component>();
    Component masterComp = null;
    
    // get list of exceptions (VEVENT with RECURRENCEID)
    for (Iterator<VEvent> i = vevents.iterator(); i.hasNext();) {
        VEvent event = i.next();
        if (event.getRecurrenceId() != null) {
            exceptions.add(event);
        }
        else {
            masterComp = event; 
        }
        
    }
    
    return getOcurrences(masterComp, exceptions, rangeStart, rangeEnd, timezone);
}
 
Example #5
Source File: Calendar_EventRepeatMaster.java    From o2oa with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * 获取重复时间表达式中结束的日期
 * @return
 */
public Date getRecurrenceEndDate() {
	final TimeZone tz = TimeZoneRegistryFactory.getInstance().createRegistry()
			.getTimeZone(java.util.Calendar.getInstance().getTimeZone().getID());
	if (recurrenceRule != null) {
		try {
			final Recur recur = new Recur(recurrenceRule);
			final Date dUntil = recur.getUntil();
			final DateTime dtUntil = dUntil == null ? null : new DateTime(dUntil.getTime());
			if (dtUntil != null) {
				dtUntil.setTimeZone(tz);
				return dtUntil;
			}
		} catch (final ParseException e) {
			System.out.println("cannot restore recurrence rule");
			e.printStackTrace();
		}
	}
	return null;
}
 
Example #6
Source File: ICal4JUtils.java    From projectforge-webapp with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Format is '20130327T090000'
 * @param dateString
 * @param timeZone
 * @return
 */
public static Date parseICalDateString(final String dateString, final java.util.TimeZone timeZone)
{
  if (StringUtils.isBlank(dateString) == true) {
    return null;
  }
  String pattern;
  java.util.TimeZone tz = timeZone;
  if (dateString.indexOf('T') > 0) {
    pattern = ICAL_DATETIME_FORMAT;
  } else {
    pattern = ICAL_DATE_FORMAT;
    tz = DateHelper.UTC;
  }
  final DateFormat df = new SimpleDateFormat(pattern);
  df.setTimeZone(tz);
  try {
    return df.parse(dateString);
  } catch (final ParseException ex) {
    log.error("Can't parse ical date ('" + pattern + "': " + ex.getMessage(), ex);
    return null;
  }
}
 
Example #7
Source File: ICalendarUtils.java    From cosmo with Apache License 2.0 6 votes vote down vote up
/**
 * Construct a new DateTime instance for floating times (no timezone).
 * If the specified date is not floating, then the instance is returned. 
 * 
 * This allows a floating time to be converted to an instant in time
 * depending on the specified timezone.
 * 
 * @param date floating date
 * @param tz timezone
 * @return new DateTime instance representing floating time pinned to
 *         the specified timezone
 */
public static DateTime pinFloatingTime(Date date, TimeZone tz) {
    
    try {   
        if(date instanceof DateTime) {
            DateTime dt = (DateTime) date;
            if(dt.isUtc() || dt.getTimeZone()!=null) {
                return dt;
            }
            else {
                return new DateTime(date.toString(), tz);
            }
        }
        else {
            return new DateTime(date.toString() + "T000000", tz);
        }
    } catch (ParseException e) {
        throw new CosmoParseException("error parsing date", e);
    }
}
 
Example #8
Source File: Util.java    From openhab1-addons with Eclipse Public License 2.0 6 votes vote down vote up
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;
}
 
Example #9
Source File: ICalendarUtils.java    From cosmo with Apache License 2.0 6 votes vote down vote up
/**
 * Return a DateTime instance that is normalized according to the
 * offset of the specified timezone as compared to the default
 * system timezone.
 * 
 * @param utcDateTime point in time
 * @param tz timezone The timezone.
 * @return The date.
 */
public static Date normalizeUTCDateTimeToDefaultOffset(DateTime utcDateTime, TimeZone tz) {
    if(!utcDateTime.isUtc()) {
        throw new IllegalArgumentException("datetime must be utc");
    }
    
    // if no timezone nothing to do
    if (tz == null) {
        return utcDateTime;
    }
    
    // create copy, and set timezone
    DateTime copy = (DateTime) Dates.getInstance(utcDateTime, utcDateTime);
    copy.setTimeZone(tz);
    
    
    // Create floating instance of local time, which will give
    // us the correct offset
    try {
        return new DateTime(copy.toString());
    } catch (ParseException e) {
        throw new CosmoParseException("error creating Date instance", e);
    }
}
 
Example #10
Source File: CalendarEntry.java    From olat with Apache License 2.0 6 votes vote down vote up
/**
 * @param rule
 * @return date of recurrence end
 */
public Date getRecurrenceEndDate() {
    final TimeZone tz = TimeZoneRegistryFactory.getInstance().createRegistry().getTimeZone(java.util.Calendar.getInstance().getTimeZone().getID());

    if (recurrenceRule != null) {
        try {
            final Recur recur = new Recur(recurrenceRule);
            final Date dUntil = recur.getUntil();
            final DateTime dtUntil = dUntil == null ? null : new DateTime(dUntil.getTime());
            if (dtUntil != null) {
                dtUntil.setTimeZone(tz);
                return dtUntil;
            }
        } catch (final ParseException e) {
            log.error("cannot restore recurrence rule", e);
        }
    }

    return null;
}
 
Example #11
Source File: CalendarEntry.java    From olat with Apache License 2.0 6 votes vote down vote up
/**
 * @param rule
 * @return date of recurrence end
 */
public Date getRecurrenceEndDate() {
    final TimeZone tz = TimeZoneRegistryFactory.getInstance().createRegistry().getTimeZone(java.util.Calendar.getInstance().getTimeZone().getID());

    if (recurrenceRule != null) {
        try {
            final Recur recur = new Recur(recurrenceRule);
            final Date dUntil = recur.getUntil();
            final DateTime dtUntil = dUntil == null ? null : new DateTime(dUntil.getTime());
            if (dtUntil != null) {
                dtUntil.setTimeZone(tz);
                return dtUntil;
            }
        } catch (final ParseException e) {
            log.error("cannot restore recurrence rule", e);
        }
    }

    return null;
}
 
Example #12
Source File: RecurrenceExpanderTest.java    From cosmo with Apache License 2.0 6 votes vote down vote up
/**
 * Tests occurence.
 * @throws Exception - if something is wrong this exception is thrown.
 */
@Test
public void testIsOccurrence() throws Exception {
    RecurrenceExpander expander = new RecurrenceExpander();
    Calendar calendar = getCalendar("floating_recurring3.ics");
    
    
    Assert.assertTrue(expander.isOccurrence(calendar, new DateTime("20070102T100000")));
    Assert.assertFalse(expander.isOccurrence(calendar, new DateTime("20070102T110000")));
    Assert.assertFalse(expander.isOccurrence(calendar, new DateTime("20070102T100001")));

    // test DATE
    calendar = getCalendar("allday_recurring3.ics");
    
    Assert.assertTrue(expander.isOccurrence(calendar, new Date("20070101")));
    Assert.assertFalse(expander.isOccurrence(calendar, new Date("20070102")));
    Assert.assertTrue(expander.isOccurrence(calendar, new Date("20070108")));
    
    // test DATETIME with timezone
    calendar = getCalendar("tz_recurring3.ics");
    TimeZone ctz = TIMEZONE_REGISTRY.getTimeZone("America/Chicago");
    
    Assert.assertTrue(expander.isOccurrence(calendar, new DateTime("20070102T100000", ctz)));
    Assert.assertFalse(expander.isOccurrence(calendar, new DateTime("20070102T110000", ctz)));
    Assert.assertFalse(expander.isOccurrence(calendar, new DateTime("20070102T100001", ctz)));
}
 
Example #13
Source File: CalendarFilterEvaluater.java    From cosmo with Apache License 2.0 6 votes vote down vote up
/**
 * Evaluates VJournal time range.
 * @param journal The VJournal.
 * @param filter The time range filter.
 * @return The result.
 */
private boolean evaluateVJournalTimeRange(VJournal journal, TimeRangeFilter filter) {
    DtStart start = journal.getStartDate();
  
    if(start==null) {
        return false;
    }
    
    InstanceList instances = new InstanceList();
    if (filter.getTimezone() != null) {
        instances.setTimezone(new TimeZone(filter.getTimezone()));
    }
    instances.addComponent(journal, filter.getPeriod().getStart(),
            filter.getPeriod().getEnd());
    return instances.size() > 0;
}
 
Example #14
Source File: ICalendarUtilsTest.java    From cosmo with Apache License 2.0 6 votes vote down vote up
/**
 * Tests pin floating time.
 * @throws Exception - if something is wrong this exception is thrown.
 */
@Test
public void testPinFloatingTime() throws Exception {
    TimeZone tz1 = TIMEZONE_REGISTRY.getTimeZone("America/Chicago");
   
    Assert.assertEquals("20070101T000000", ICalendarUtils.pinFloatingTime(new Date("20070101"), tz1).toString());
    Assert.assertEquals("20070101T000000", ICalendarUtils.pinFloatingTime(new DateTime("20070101T000000"), tz1).toString());
    
    
    TimeZone tz2 = TIMEZONE_REGISTRY.getTimeZone("America/Los_Angeles");
    Assert.assertEquals("20070101T000000", ICalendarUtils.pinFloatingTime(new Date("20070101"), tz1).toString());
    Assert.assertEquals("20070101T000000", ICalendarUtils.pinFloatingTime(new DateTime("20070101T000000"), tz1).toString());

    Assert.assertTrue(ICalendarUtils.pinFloatingTime(
            new Date("20070101"), tz1).before(
            ICalendarUtils.pinFloatingTime(new Date("20070101"),
                    tz2)));
    Assert.assertTrue(ICalendarUtils.pinFloatingTime(
            new DateTime("20070101T000000"), tz1).before(
            ICalendarUtils.pinFloatingTime(new DateTime("20070101T000000"),
                    tz2)));
}
 
Example #15
Source File: CalendarFilterConverter.java    From cosmo with Apache License 2.0 6 votes vote down vote up
private void handleEventCompFilter(ComponentFilter compFilter, NoteItemFilter itemFilter) {
    // TODO: handle case of multiple VEVENT filters
    EventStampFilter eventFilter = new EventStampFilter();
    itemFilter.getStampFilters().add(eventFilter);

    TimeRangeFilter trf = compFilter.getTimeRangeFilter();

    // handle time-range filter
    if (trf != null) {
        eventFilter.setPeriod(trf.getPeriod());
        if (trf.getTimezone() != null) {
            eventFilter.setTimezone(new TimeZone(trf.getTimezone()));
        }
    }

    for (ComponentFilter subComp : compFilter.getComponentFilters()) {
        throw new IllegalArgumentException("unsupported sub component filter: " + subComp.getName());
    }

    for (PropertyFilter propFilter : compFilter.getPropFilters()) {
        handleEventPropFilter(propFilter, itemFilter);
    }
}
 
Example #16
Source File: EntityConverter.java    From cosmo with Apache License 2.0 6 votes vote down vote up
/**
 * Compact timezones.
 * @param calendar The calendar.
 */
private void compactTimezones(Calendar calendar) {
    
    if (calendar==null) {
        return;
    }

    // Get list of timezones in master calendar and remove all timezone
    // definitions that are in the registry.  The idea is to not store
    // extra data.  Instead, the timezones will be added to the calendar
    // by the getCalendar() api.
    ComponentList<VTimeZone> timezones = calendar.getComponents(Component.VTIMEZONE);
    List<VTimeZone> toRemove = new ArrayList<>();
    for(VTimeZone vtz : timezones) {
        String tzid = vtz.getTimeZoneId().getValue();
        TimeZone tz = TIMEZONE_REGISTRY.getTimeZone(tzid);
        //  Remove timezone iff it matches the one in the registry
        if(tz!=null && vtz.equals(tz.getVTimeZone())) {
            toRemove.add(vtz);
        }
    }

    // remove known timezones from master calendar
    calendar.getComponents().removeAll(toRemove);
}
 
Example #17
Source File: StandardCalendarService.java    From cosmo with Apache License 2.0 6 votes vote down vote up
@Override
public Set<Item> findEvents(CollectionItem collection, Date rangeStart, Date rangeEnd, String timeZoneId,
        boolean expandRecurringEvents) {
    Set<Item> resultSet = new HashSet<>();
    String uid = collection.getUid();
    if (UuidExternalGenerator.get().containsUuid(uid) || UuidSubscriptionGenerator.get().containsUuid(uid)) {
        NoteItemFilter filter = new NoteItemFilter();
        filter.setParent(collection);
        EventStampFilter eventFilter = new EventStampFilter();
        eventFilter.setTimeRange(rangeStart, rangeEnd);
        if (timeZoneId != null) {
            TimeZone timezone = TIMEZONE_REGISTRY.getTimeZone(timeZoneId);
            eventFilter.setTimezone(timezone);
        }
        filter.getStampFilters().add(eventFilter);
        Set<Item> externalItems = this.contentDao.findItems(filter);
        if (externalItems != null) {
            resultSet.addAll(externalItems);
        }
    } else {
        Set<Item> internalItems = calendarDao.findEvents(collection, rangeStart, rangeEnd, timeZoneId,
                expandRecurringEvents);
        resultSet.addAll(internalItems);
    }
    return resultSet;
}
 
Example #18
Source File: ICal4JUtils.java    From projectforge-webapp with GNU General Public License v3.0 5 votes vote down vote up
public static net.fortuna.ical4j.model.Date getICal4jDate(final java.util.Date javaDate, final java.util.TimeZone timeZone)
{
  if (javaDate == null) {
    return null;
  }
  return new MyIcal4JDate(javaDate, timeZone);
}
 
Example #19
Source File: TriageStatusQueryContext.java    From cosmo with Apache License 2.0 5 votes vote down vote up
/**
 * @param triageStatus triage status label to match (ignored if null)
 * @param pointInTime time that is considered "NOW"
 * @param timezone Optional timezone to use in interpreting
 *                 floating times. If null, the system default
 *                 will be used.
 */
public TriageStatusQueryContext(String triageStatus,
                                Date pointInTime,
                                TimeZone timezone) {
    this.triageStatus = triageStatus;
    this.pointInTime = pointInTime != null ? (Date)pointInTime.clone() : null;
    this.timezone = timezone;
}
 
Example #20
Source File: ExternalCalendaringServiceImpl.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
public VTimeZone getTimeZone(boolean timeIsLocal) {
	//timezone. All dates are in GMT so we need to explicitly set that
	TimeZoneRegistry registry = TimeZoneRegistryFactory.getInstance().createRegistry();
	
	//To prevent NPE on timezone
	TimeZone timezone = null;
	if (timeIsLocal == true) {
		timezone = registry.getTimeZone(timeService.getLocalTimeZone().getID());
	}
	if (timezone == null) {
		//This is guaranteed to return timezone if timeIsLocal == false or it fails and returns null
		timezone = registry.getTimeZone("GMT");
	}
	return timezone.getVTimeZone();
}
 
Example #21
Source File: ICal4JUtils.java    From projectforge-webapp with GNU General Public License v3.0 5 votes vote down vote up
public static String asISODateString(final Date date, final java.util.TimeZone timeZone)
{
  if (date == null) {
    return null;
  }
  final DateFormat df = new SimpleDateFormat(DateFormats.ISO_DATE);
  df.setTimeZone(timeZone);
  return df.format(date);
}
 
Example #22
Source File: ICal4JUtils.java    From projectforge-webapp with GNU General Public License v3.0 5 votes vote down vote up
public static net.fortuna.ical4j.model.DateTime getICal4jDateTime(final java.util.Date javaDate, final java.util.TimeZone timeZone)
{
  if (javaDate == null) {
    return null;
  }
  final String dateString = DateHelper.formatIsoTimestamp(javaDate, timeZone);
  final String pattern = DateFormats.ISO_TIMESTAMP_SECONDS;
  try {
    final net.fortuna.ical4j.model.DateTime dateTime = new net.fortuna.ical4j.model.DateTime(dateString, pattern, getTimeZone(timeZone));
    return dateTime;
  } catch (final ParseException ex) {
    log.error("Can't parse date '" + dateString + "' with pattern '" + pattern + "': " + ex.getMessage(), ex);
    return null;
  }
}
 
Example #23
Source File: ICalUtils.java    From camel-quarkus with Apache License 2.0 5 votes vote down vote up
protected static Calendar createTestCalendar(ZonedDateTime start, ZonedDateTime end, String summary, String attendee) {
    // Create a TimeZone
    TimeZoneRegistry registry = TimeZoneRegistryFactory.getInstance().createRegistry();
    String tzId = start.getZone().getId();
    TimeZone timezone = registry.getTimeZone(tzId.equals("Z") ? "UTC" : tzId);
    VTimeZone tz = timezone.getVTimeZone();

    // Create the event
    PropertyList propertyList = new PropertyList();
    DateTime ts = new DateTime(true);
    ts.setTime(0);
    propertyList.add(new DtStamp(ts));
    propertyList.add(new DtStart(toDateTime(start, registry)));
    propertyList.add(new DtEnd(toDateTime(end, registry)));
    propertyList.add(new Summary(summary));
    VEvent meeting = new VEvent(propertyList);

    // add timezone info..
    meeting.getProperties().add(tz.getTimeZoneId());

    // generate unique identifier..
    meeting.getProperties().add(new Uid("00000000"));

    // add attendees..
    Attendee dev1 = new Attendee(URI.create("mailto:" + attendee));
    dev1.getParameters().add(Role.REQ_PARTICIPANT);
    dev1.getParameters().add(new Cn(attendee));
    meeting.getProperties().add(dev1);

    // Create a calendar
    net.fortuna.ical4j.model.Calendar icsCalendar = new net.fortuna.ical4j.model.Calendar();
    icsCalendar.getProperties().add(Version.VERSION_2_0);
    icsCalendar.getProperties().add(new ProdId("-//Events Calendar//iCal4j 1.0//EN"));
    icsCalendar.getProperties().add(CalScale.GREGORIAN);

    // Add the event and print
    icsCalendar.getComponents().add(meeting);
    return icsCalendar;
}
 
Example #24
Source File: TeamEventUtils.java    From projectforge-webapp with GNU General Public License v3.0 5 votes vote down vote up
public static VEvent createVEvent(final TeamEventDO eventDO, final TimeZone timezone)
{
  final VEvent vEvent = ICal4JUtils.createVEvent(eventDO.getStartDate(), eventDO.getEndDate(), eventDO.getUid(), eventDO.getSubject(),
      eventDO.isAllDay(), timezone);
  if (eventDO.hasRecurrence() == true) {
    final RRule rrule = eventDO.getRecurrenceRuleObject();
    vEvent.getProperties().add(rrule);
  }
  return vEvent;
}
 
Example #25
Source File: ICalFormatTest.java    From wildfly-camel with Apache License 2.0 5 votes vote down vote up
private Calendar createTestCalendar() throws ParseException {
    // Create a TimeZone
    TimeZoneRegistry registry = TimeZoneRegistryFactory.getInstance().createRegistry();
    TimeZone timezone = registry.getTimeZone("America/New_York");
    VTimeZone tz = timezone.getVTimeZone();

    // Start Date is on: April 1, 2013, 9:00 am
    java.util.Calendar startDate = new GregorianCalendar();
    startDate.setTimeZone(timezone);
    startDate.set(java.util.Calendar.MONTH, java.util.Calendar.APRIL);
    startDate.set(java.util.Calendar.DAY_OF_MONTH, 1);
    startDate.set(java.util.Calendar.YEAR, 2013);
    startDate.set(java.util.Calendar.HOUR_OF_DAY, 17);
    startDate.set(java.util.Calendar.MINUTE, 0);
    startDate.set(java.util.Calendar.SECOND, 0);

    // End Date is on: April 1, 2013, 13:00
    java.util.Calendar endDate = new GregorianCalendar();
    endDate.setTimeZone(timezone);
    endDate.set(java.util.Calendar.MONTH, java.util.Calendar.APRIL);
    endDate.set(java.util.Calendar.DAY_OF_MONTH, 1);
    endDate.set(java.util.Calendar.YEAR, 2013);
    endDate.set(java.util.Calendar.HOUR_OF_DAY, 21);
    endDate.set(java.util.Calendar.MINUTE, 0);
    endDate.set(java.util.Calendar.SECOND, 0);

    // Create the event
    PropertyList propertyList = new PropertyList();
    propertyList.add(new DtStamp("20130324T180000Z"));
    propertyList.add(new DtStart(new DateTime(startDate.getTime())));
    propertyList.add(new DtEnd(new DateTime(endDate.getTime())));
    propertyList.add(new Summary("Progress Meeting"));
    VEvent meeting = new VEvent(propertyList);

    // add timezone info..
    meeting.getProperties().add(tz.getTimeZoneId());

    // generate unique identifier..
    meeting.getProperties().add(new Uid("00000000"));

    // add attendees..
    Attendee dev1 = new Attendee(URI.create("mailto:[email protected]"));
    dev1.getParameters().add(Role.REQ_PARTICIPANT);
    dev1.getParameters().add(new Cn("Developer 1"));
    meeting.getProperties().add(dev1);

    Attendee dev2 = new Attendee(URI.create("mailto:[email protected]"));
    dev2.getParameters().add(Role.OPT_PARTICIPANT);
    dev2.getParameters().add(new Cn("Developer 2"));
    meeting.getProperties().add(dev2);

    // Create a calendar
    net.fortuna.ical4j.model.Calendar icsCalendar = new net.fortuna.ical4j.model.Calendar();
    icsCalendar.getProperties().add(Version.VERSION_2_0);
    icsCalendar.getProperties().add(new ProdId("-//Events Calendar//iCal4j 1.0//EN"));
    icsCalendar.getProperties().add(CalScale.GREGORIAN);

    // Add the event and print
    icsCalendar.getComponents().add(meeting);
    return icsCalendar;
}
 
Example #26
Source File: ICalendarUtilsTest.java    From cosmo with Apache License 2.0 5 votes vote down vote up
/**
 * Tests compare dates.
 * @throws Exception - if something is wrong this exception is thrown.
 */
@Test
public void testCompareDates() throws Exception {
    TimeZone tz = TIMEZONE_REGISTRY.getTimeZone("America/Chicago");
    
    DateTime dt = new DateTime("20070201T070000Z");
    Date toTest = new Date("20070201");
    
    Assert.assertEquals(-1, ICalendarUtils.compareDates(toTest, dt, tz));
    
    tz = TIMEZONE_REGISTRY.getTimeZone("America/Los_Angeles");
    Assert.assertEquals(1, ICalendarUtils.compareDates(toTest, dt, tz));
}
 
Example #27
Source File: ICalendarUtilsTest.java    From cosmo with Apache License 2.0 5 votes vote down vote up
/**
 * Tests normalize UTC dateTime to date.
 * @throws Exception - if something is wrong this exception is thrown.
 */
@Test
public void testNormalizeUTCDateTimeToDate() throws Exception {
    TimeZone tz = TIMEZONE_REGISTRY.getTimeZone("America/Chicago");
    
    DateTime dt = new DateTime("20070201T070000Z");
    
    Assert.assertEquals("20070201", ICalendarUtils.normalizeUTCDateTimeToDate(dt, tz).toString());
    
    tz = TIMEZONE_REGISTRY.getTimeZone("America/Los_Angeles");
    Assert.assertEquals("20070131", ICalendarUtils.normalizeUTCDateTimeToDate(dt, tz).toString());
    
    tz = TIMEZONE_REGISTRY.getTimeZone("Australia/Sydney");
    Assert.assertEquals("20070201", ICalendarUtils.normalizeUTCDateTimeToDate(dt, tz).toString());
}
 
Example #28
Source File: StandardTriageStatusQueryProcessor.java    From cosmo with Apache License 2.0 5 votes vote down vote up
/**
 * Create NoteItemFilter that matches all recurring event NoteItems that belong
 * to a specified parent collection.
 * 
 * @param collection CollectionItem
 * @param start Date
 * @param end Date
 * @param timezone Timezone
 * @return NoteItemFiler 
 */
private NoteItemFilter getRecurringEventFilter(CollectionItem collection, Date start, Date end, TimeZone timezone) {
    NoteItemFilter eventNoteFilter = new NoteItemFilter();
    eventNoteFilter.setFilterProperty(EventStampFilter.PROPERTY_DO_TIMERANGE_SECOND_PASS, "false");
    EventStampFilter eventFilter = new EventStampFilter();
    eventFilter.setIsRecurring(true);
    eventFilter.setTimeRange(new DateTime(start), new DateTime(end));
    eventFilter.setTimezone(timezone);
    eventNoteFilter.setParent(collection);
    eventNoteFilter.getStampFilters().add(eventFilter);
    return eventNoteFilter;
}
 
Example #29
Source File: ICalendarUtilsTest.java    From cosmo with Apache License 2.0 5 votes vote down vote up
/**
 * Tests convert to UTC.
 * @throws Exception - if something is wrong this exception is thrown.
 */
@Test
public void testConvertToUTC() throws Exception {
    TimeZone tz = TIMEZONE_REGISTRY.getTimeZone("America/Chicago");
   
    Assert.assertEquals("20070101T060000Z", ICalendarUtils.convertToUTC(new Date("20070101"), tz).toString());
    Assert.assertEquals("20070101T160000Z", ICalendarUtils.convertToUTC(new DateTime("20070101T100000"), tz).toString());
    
    
    tz = TIMEZONE_REGISTRY.getTimeZone("America/Los_Angeles");
    Assert.assertEquals("20070101T080000Z", ICalendarUtils.convertToUTC(new Date("20070101"), tz).toString());
    Assert.assertEquals("20070101T180000Z", ICalendarUtils.convertToUTC(new DateTime("20070101T100000"), tz).toString());
    
}
 
Example #30
Source File: StandardTriageStatusQueryProcessor.java    From cosmo with Apache License 2.0 5 votes vote down vote up
/**
 * Calculate and return the first ocurring instance or modification
 * for the specified master event and date range.
 * The instance must begin after the start of the range and if it
 * is a modification it must have a triageStatus of LATER.
 * 
 * @param event Eventstamp
 * @param rangeStart Date
 * @param rangeEnd Date
 * @param timezone Timezone
 * @return NoteItem 
 */
private NoteItem getFirstInstanceOrModification(EventStamp event, Date rangeStart, Date rangeEnd, TimeZone timezone) {
    NoteItem note = (NoteItem) event.getItem();
    RecurrenceExpander expander = new RecurrenceExpander();
    
    InstanceList instances = expander.getOcurrences(event.getEvent(), 
            event.getExceptions(), new DateTime(rangeStart), new DateTime(rangeEnd),
            timezone );
 
    // Find the first occurrence that begins after the start range
    while(instances.size()>0) {
        String firstKey = (String) instances.firstKey();
        Instance instance = (Instance) instances.remove(firstKey);
        if(instance.getStart().after(rangeStart)) {
            if(instance.isOverridden()) {
                ModificationUid modUid = new ModificationUidImpl(note, instance.getRid());
                NoteItem mod = (NoteItem) contentDao.findItemByUid(modUid.toString());
                // shouldn't happen, but log and continue if it does
                if(mod==null) {
                    LOG.error("no modification found for uid: {}", modUid.toString());
                    continue;
                }
                TriageStatus status = mod.getTriageStatus();
                if(status==null || status.getCode().equals(TriageStatus.CODE_LATER)) {
                    return mod;
                }
            } else {
                return NoteOccurrenceUtil.createNoteOccurrence(instance.getRid(), note);
            }
        }   
    }
    
    return null;
}