Search in sources :

Example 21 with RRule

use of net.fortuna.ical4j.model.property.RRule in project opencast by opencast.

the class SchedulerRestService method addMultipleEvents.

/**
 * Creates new event based on parameters. All times and dates are in milliseconds.
 */
@POST
@Path("/multiple")
@RestQuery(name = "newrecordings", description = "Creates new event with specified parameters", returnDescription = "If an event was successfully created", restParameters = { @RestParameter(name = "rrule", isRequired = true, type = Type.STRING, description = "The recurrence rule for the events"), @RestParameter(name = "start", isRequired = true, type = Type.INTEGER, description = "The start date of the event in milliseconds from 1970-01-01T00:00:00Z"), @RestParameter(name = "end", isRequired = true, type = Type.INTEGER, description = "The end date of the event in milliseconds from 1970-01-01T00:00:00Z"), @RestParameter(name = "duration", isRequired = true, type = Type.INTEGER, description = "The duration of the events in milliseconds"), @RestParameter(name = "tz", isRequired = true, type = Type.INTEGER, description = "The timezone of the events"), @RestParameter(name = "agent", isRequired = true, type = Type.STRING, description = "The agent of the event"), @RestParameter(name = "users", isRequired = false, type = Type.STRING, description = "Comma separated list of user ids (speakers/lecturers) for the event"), @RestParameter(name = "templateMp", isRequired = true, type = Type.TEXT, description = "The template mediapackage for the events"), @RestParameter(name = "wfproperties", isRequired = false, type = Type.TEXT, description = "Workflow " + "configuration keys for the event. Each key will be prefixed by 'org.opencastproject.workflow" + ".config.' and added to the capture agent parameters."), @RestParameter(name = "agentparameters", isRequired = false, type = Type.TEXT, description = "The capture agent properties for the event"), @RestParameter(name = "optOut", isRequired = false, type = Type.BOOLEAN, description = "The opt out status of the event"), @RestParameter(name = "source", isRequired = false, type = Type.STRING, description = "The scheduling source of the event"), @RestParameter(name = "origin", isRequired = false, type = Type.STRING, description = "The origin") }, reponses = { @RestResponse(responseCode = HttpServletResponse.SC_CREATED, description = "Event is successfully created"), @RestResponse(responseCode = HttpServletResponse.SC_CONFLICT, description = "Unable to create event, conflicting events found (ConflicsFound)"), @RestResponse(responseCode = HttpServletResponse.SC_CONFLICT, description = "Unable to create event, event locked by a transaction  (TransactionLock)"), @RestResponse(responseCode = HttpServletResponse.SC_UNAUTHORIZED, description = "You do not have permission to create the event. Maybe you need to authenticate."), @RestResponse(responseCode = HttpServletResponse.SC_BAD_REQUEST, description = "Missing or invalid information for this request") })
public Response addMultipleEvents(@FormParam("rrule") String rruleString, @FormParam("start") long startTime, @FormParam("end") long endTime, @FormParam("duration") long duration, @FormParam("tz") String tzString, @FormParam("agent") String agentId, @FormParam("users") String users, @FormParam("templateMp") MediaPackage templateMp, @FormParam("wfproperties") String workflowProperties, @FormParam("agentparameters") String agentParameters, @FormParam("optOut") Boolean optOut, @FormParam("source") String schedulingSource, @FormParam("origin") String origin) throws UnauthorizedException {
    if (StringUtils.isBlank(origin))
        origin = SchedulerService.ORIGIN;
    if (endTime <= startTime || startTime < 0) {
        logger.debug("Cannot add event without proper start and end time");
        return RestUtil.R.badRequest("Cannot add event without proper start and end time");
    }
    RRule rrule;
    try {
        rrule = new RRule(rruleString);
    } catch (ParseException e) {
        logger.debug("Could not parse recurrence rule");
        return RestUtil.R.badRequest("Could not parse recurrence rule");
    }
    if (duration < 1) {
        logger.debug("Cannot schedule events with durations less than 1");
        return RestUtil.R.badRequest("Cannot schedule events with durations less than 1");
    }
    if (StringUtils.isBlank(tzString)) {
        logger.debug("Cannot schedule events with blank timezone");
        return RestUtil.R.badRequest("Cannot schedule events with blank timezone");
    }
    TimeZone tz = TimeZone.getTimeZone(tzString);
    if (StringUtils.isBlank(agentId)) {
        logger.debug("Cannot add event without agent identifier");
        return RestUtil.R.badRequest("Cannot add event without agent identifier");
    }
    Map<String, String> caProperties = new HashMap<>();
    if (StringUtils.isNotBlank(agentParameters)) {
        try {
            Properties prop = parseProperties(agentParameters);
            caProperties.putAll((Map) prop);
        } catch (Exception e) {
            logger.info("Could not parse capture agent properties: {}", agentParameters);
            return RestUtil.R.badRequest("Could not parse capture agent properties");
        }
    }
    Map<String, String> wfProperties = new HashMap<>();
    if (StringUtils.isNotBlank(workflowProperties)) {
        try {
            Properties prop = parseProperties(workflowProperties);
            wfProperties.putAll((Map) prop);
        } catch (IOException e) {
            logger.info("Could not parse workflow configuration properties: {}", workflowProperties);
            return RestUtil.R.badRequest("Could not parse workflow configuration properties");
        }
    }
    Set<String> userIds = new HashSet<>();
    String[] ids = StringUtils.split(users, ",");
    if (ids != null)
        userIds.addAll(Arrays.asList(ids));
    DateTime startDate = new DateTime(startTime).toDateTime(DateTimeZone.UTC);
    DateTime endDate = new DateTime(endTime).toDateTime(DateTimeZone.UTC);
    try {
        service.addMultipleEvents(rrule, startDate.toDate(), endDate.toDate(), duration, tz, agentId, userIds, templateMp, wfProperties, caProperties, Opt.nul(optOut), Opt.nul(schedulingSource), origin);
        return Response.status(Status.CREATED).build();
    } catch (UnauthorizedException e) {
        throw e;
    } catch (SchedulerTransactionLockException | SchedulerConflictException e) {
        return Response.status(Status.CONFLICT).entity(generateErrorResponse(e)).type(MediaType.APPLICATION_JSON).build();
    } catch (Exception e) {
        logger.error("Unable to create new events", e);
        return Response.serverError().build();
    }
}
Also used : RRule(net.fortuna.ical4j.model.property.RRule) HashMap(java.util.HashMap) SchedulerConflictException(org.opencastproject.scheduler.api.SchedulerConflictException) IOException(java.io.IOException) Properties(java.util.Properties) SchedulerException(org.opencastproject.scheduler.api.SchedulerException) SchedulerConflictException(org.opencastproject.scheduler.api.SchedulerConflictException) WebApplicationException(javax.ws.rs.WebApplicationException) IOException(java.io.IOException) SchedulerTransactionLockException(org.opencastproject.scheduler.api.SchedulerTransactionLockException) ParseException(java.text.ParseException) MediaPackageException(org.opencastproject.mediapackage.MediaPackageException) UnauthorizedException(org.opencastproject.security.api.UnauthorizedException) NotFoundException(org.opencastproject.util.NotFoundException) DateTime(org.joda.time.DateTime) DateTimeZone(org.joda.time.DateTimeZone) TimeZone(java.util.TimeZone) SchedulerTransactionLockException(org.opencastproject.scheduler.api.SchedulerTransactionLockException) UnauthorizedException(org.opencastproject.security.api.UnauthorizedException) ParseException(java.text.ParseException) HashSet(java.util.HashSet) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) RestQuery(org.opencastproject.util.doc.rest.RestQuery)

Example 22 with RRule

use of net.fortuna.ical4j.model.property.RRule in project zm-mailbox by Zimbra.

the class ZoneInfo2iCalendar method toObservanceComp.

private static Observance toObservanceComp(int hintYear, RuleLine rline, boolean isStandard, Time standardOffset, Time daylightOffset, String tznameFormat) {
    PropertyList props = new PropertyList();
    String tzname = getObservanceName(tznameFormat, rline);
    if (tzname != null) {
        props.add(new TzName(tzname));
    }
    Time at = rline.getAt();
    Time onset;
    switch(at.getType()) {
        case STANDARD_TIME:
            if (isStandard) {
                // We're moving from daylight time to standard time.  In iCalendar we want hh:mm:ss in
                // wall clock in the pre-transition time, so it's daylight time.
                // daylight = utc + daylight offset = (standard - standard offset) + daylight offset
                onset = addTimes(subtractTimes(at, standardOffset), daylightOffset);
            } else {
                // We're moving from standard time to daylight time.  In iCalendar we want hh:mm:ss in
                // wall clock in the pre-transition time, so it's standard time.  at is already in
                // standard time.
                onset = at;
            }
            break;
        case UTC_TIME:
            if (isStandard) {
                // We're moving from daylight time to standard time.  In iCalendar we want hh:mm:ss in
                // wall clock in the pre-transition time, so it's daylight time.
                // daylight = utc + daylightOffset.
                onset = addTimes(at, daylightOffset);
            } else {
                // We're moving from standard time to daylight time.  In iCalendar we want hh:mm:ss in
                // wall clock in the pre-transition time, so it's standard time.
                // standard = utc + standard offset.
                onset = addTimes(at, standardOffset);
            }
            break;
        default:
            // WALL_TIME
            // at is already in the iCalendar style.
            onset = at;
            break;
    }
    int hh = onset.getHour();
    int mm = onset.getMinute();
    int ss = onset.getSecond();
    if (hh >= 24) {
        // Hour should be between 0 and 23, but sometimes we can get 24:00:00 from the zoneinfo source.
        // Since hour part in iCalendar only allows 0-23, let's approximate any time with hour >= 24 to
        // 23:59:59.
        hh = 23;
        mm = 59;
        ss = 59;
    }
    // YYYYMMDD fixed to 16010101 (MS Outlook style)
    props.add(getDtStart(String.format("16010101T%02d%02d%02d", hh, mm, ss)));
    Time toOffset, fromOffset;
    if (isStandard) {
        toOffset = standardOffset;
        fromOffset = daylightOffset;
    } else {
        toOffset = daylightOffset;
        fromOffset = standardOffset;
    }
    props.add(new TzOffsetTo(new UtcOffset(getUtcOffset(toOffset))));
    props.add(new TzOffsetFrom(new UtcOffset(getUtcOffset(fromOffset))));
    int month = rline.getIn();
    StringBuilder rruleVal = new StringBuilder();
    rruleVal.append("FREQ=YEARLY;WKST=MO;INTERVAL=1;BYMONTH=").append(month).append(";");
    rruleVal.append(dayToICalRRulePart(hintYear, month, rline.getOn()));
    try {
        RRule rrule = new RRule(new ParameterList(), rruleVal.toString());
        props.add(rrule);
    } catch (ParseException e) {
    }
    if (isStandard) {
        return new Standard(props);
    } else {
        return new Daylight(props);
    }
}
Also used : TzName(net.fortuna.ical4j.model.property.TzName) RRule(net.fortuna.ical4j.model.property.RRule) DateTime(net.fortuna.ical4j.model.DateTime) Time(com.zimbra.common.calendar.ZoneInfoParser.Time) Standard(net.fortuna.ical4j.model.component.Standard) UtcOffset(net.fortuna.ical4j.model.UtcOffset) PropertyList(net.fortuna.ical4j.model.PropertyList) Daylight(net.fortuna.ical4j.model.component.Daylight) TzOffsetTo(net.fortuna.ical4j.model.property.TzOffsetTo) TzOffsetFrom(net.fortuna.ical4j.model.property.TzOffsetFrom) ParameterList(net.fortuna.ical4j.model.ParameterList) ParseException(java.text.ParseException) TZDataParseException(com.zimbra.common.calendar.ZoneInfoParser.TZDataParseException)

Example 23 with RRule

use of net.fortuna.ical4j.model.property.RRule in project openolat by klemens.

the class ICalFileCalendarManager method removeFutureOfEvent.

@Override
public boolean removeFutureOfEvent(Kalendar cal, KalendarRecurEvent kalendarEvent) {
    OLATResourceable calOres = getOresHelperFor(cal);
    Boolean removeSuccessful = CoordinatorManager.getInstance().getCoordinator().getSyncer().doInSync(calOres, new SyncerCallback<Boolean>() {

        @Override
        public Boolean execute() {
            boolean successfullyPersist = false;
            try {
                String uid = kalendarEvent.getID();
                Date occurenceDate = kalendarEvent.getOccurenceDate();
                Kalendar loadedCal = getCalendarFromCache(cal.getType(), cal.getCalendarID());
                KalendarEvent rootEvent = loadedCal.getEvent(kalendarEvent.getID(), null);
                String rRule = rootEvent.getRecurrenceRule();
                Recur recur = new Recur(rRule);
                recur.setUntil(CalendarUtils.createDate(occurenceDate));
                RRule rrule = new RRule(recur);
                rootEvent.setRecurrenceRule(rrule.getValue());
                for (KalendarEvent kEvent : loadedCal.getEvents()) {
                    if (uid.equals(kEvent.getID()) && StringHelper.containsNonWhitespace(kEvent.getRecurrenceID()) && occurenceDate.before(kEvent.getBegin())) {
                        loadedCal.removeEvent(kEvent);
                    }
                }
                successfullyPersist = persistCalendar(loadedCal);
            } catch (ParseException e) {
                log.error("", e);
            }
            return new Boolean(successfullyPersist);
        }
    });
    // inform all controller about calendar change for reload
    CoordinatorManager.getInstance().getCoordinator().getEventBus().fireEventToListenersOf(new CalendarGUIModifiedEvent(cal), OresHelper.lookupType(CalendarManager.class));
    return removeSuccessful.booleanValue();
}
Also used : RRule(net.fortuna.ical4j.model.property.RRule) OLATResourceable(org.olat.core.id.OLATResourceable) KalendarEvent(org.olat.commons.calendar.model.KalendarEvent) Date(java.util.Date) ExDate(net.fortuna.ical4j.model.property.ExDate) CalendarManager(org.olat.commons.calendar.CalendarManager) Kalendar(org.olat.commons.calendar.model.Kalendar) ParseException(java.text.ParseException) CalendarGUIModifiedEvent(org.olat.commons.calendar.ui.events.CalendarGUIModifiedEvent) Recur(net.fortuna.ical4j.model.Recur)

Aggregations

RRule (net.fortuna.ical4j.model.property.RRule)23 ParseException (java.text.ParseException)14 Date (java.util.Date)11 Recur (net.fortuna.ical4j.model.Recur)9 DateTime (net.fortuna.ical4j.model.DateTime)8 PropertyList (net.fortuna.ical4j.model.PropertyList)7 ExDate (net.fortuna.ical4j.model.property.ExDate)6 VEvent (net.fortuna.ical4j.model.component.VEvent)5 MediaPackage (org.opencastproject.mediapackage.MediaPackage)5 TimeZone (java.util.TimeZone)4 WebApplicationException (javax.ws.rs.WebApplicationException)4 Period (net.fortuna.ical4j.model.Period)4 RecurrenceId (net.fortuna.ical4j.model.property.RecurrenceId)4 Kalendar (org.olat.commons.calendar.model.Kalendar)4 KalendarEvent (org.olat.commons.calendar.model.KalendarEvent)4 IOException (java.io.IOException)3 Calendar (java.util.Calendar)3 Path (javax.ws.rs.Path)3 Date (net.fortuna.ical4j.model.Date)3 CalFacadeException (org.bedework.calfacade.exc.CalFacadeException)3