Search in sources :

Example 16 with CalendarBuilder

use of net.fortuna.ical4j.data.CalendarBuilder in project openhab1-addons by openhab.

the class EventReloaderJob method loadEvents.

public void loadEvents(String filename, org.joda.time.DateTime lastResourceChangeFS, final InputStream inputStream, final CalDavConfig config, final List<String> oldEventIds, boolean readFromFile) throws IOException, ParserException {
    CalendarBuilder builder = new CalendarBuilder();
    InputStreamReader is = new InputStreamReader(inputStream, config.getCharset());
    BufferedReader in = new BufferedReader(is, 50);
    final UnfoldingReader uin = new UnfoldingReader(in, 50, true);
    Calendar calendar = builder.build(uin);
    uin.close();
    // log.trace("calendar: {}", calendar);
    EventContainer eventContainer = new EventContainer(config.getKey());
    eventContainer.setFilename(filename);
    eventContainer.setLastChanged(lastResourceChangeFS);
    org.joda.time.DateTime loadFrom = org.joda.time.DateTime.now().minusMinutes(config.getHistoricLoadMinutes());
    org.joda.time.DateTime loadTo = org.joda.time.DateTime.now().plusMinutes(config.getPreloadMinutes());
    final ComponentList<CalendarComponent> vEventComponents = calendar.getComponents(Component.VEVENT);
    if (vEventComponents.size() == 0) {
        log.debug("could not find a VEVENT from calendar build, based on file {}", filename);
        // no events inside
        if (!readFromFile) {
            Util.storeToDisk(config.getKey(), filename, calendar);
        }
        return;
    }
    org.joda.time.DateTime lastModifedVEventOverAll = null;
    for (CalendarComponent comp : vEventComponents) {
        VEvent vEvent = (VEvent) comp;
        log.trace("loading event: " + vEvent.getUid().getValue() + ":" + vEvent.getSummary().getValue());
        // fallback, because 'LastModified' in VEvent is optional
        org.joda.time.DateTime lastModifedVEvent = lastResourceChangeFS;
        if (vEvent.getLastModified() != null) {
            lastModifedVEvent = new org.joda.time.DateTime(vEvent.getLastModified().getDateTime());
            log.trace("overriding lastmodified from file FS ({}) with event's last-modified property ({})", lastResourceChangeFS, lastModifedVEvent);
        }
        if (!config.isLastModifiedFileTimeStampValid()) {
            if (lastModifedVEventOverAll == null || lastModifedVEvent.isAfter(lastModifedVEventOverAll)) {
                lastModifedVEventOverAll = lastModifedVEvent;
            }
            if (eventContainer != null && !lastModifedVEvent.isBefore(eventContainer.getLastChanged())) {
                // to be created
                if (eventContainer.getCalculatedUntil() != null && vEventComponents.size() == 1 && eventContainer.getCalculatedUntil().isAfter(org.joda.time.DateTime.now().plusMinutes(config.getReloadMinutes()))) {
                    // the event is calculated as long as the next reload
                    // interval can handle this
                    log.trace("skipping resource processing {}, not changed", filename);
                    continue;
                }
                if (eventContainer.isHistoricEvent()) {
                    // no more upcoming events, do nothing
                    log.trace("skipping resource processing {}, not changed", filename);
                    continue;
                }
            }
        }
        Period period = new Period(new DateTime(loadFrom.toDate()), new DateTime(loadTo.toDate()));
        PeriodList periods = vEvent.calculateRecurrenceSet(period);
        periods = periods.normalise();
        String eventId = vEvent.getUid().getValue();
        final String eventName = vEvent.getSummary().getValue();
        // no more upcoming events
        if (periods.size() > 0) {
            if (vEvent.getConsumedTime(new net.fortuna.ical4j.model.Date(), new net.fortuna.ical4j.model.Date(org.joda.time.DateTime.now().plusYears(10).getMillis())).size() == 0) {
                log.trace("event will never be occur (historic): {}", eventName);
                eventContainer.setHistoricEvent(true);
            }
        }
        // expecting this is for every vEvent inside a calendar equals
        eventContainer.setEventId(eventId);
        eventContainer.setCalculatedUntil(loadTo);
        for (Period p : periods) {
            org.joda.time.DateTime start = getDateTime("start", p.getStart(), p.getRangeStart());
            org.joda.time.DateTime end = getDateTime("end", p.getEnd(), p.getRangeEnd());
            CalDavEvent event = new CalDavEvent(eventName, vEvent.getUid().getValue(), config.getKey(), start, end);
            event.setLastChanged(lastModifedVEvent);
            if (vEvent.getLocation() != null) {
                event.setLocation(vEvent.getLocation().getValue());
            }
            if (vEvent.getDescription() != null) {
                event.setContent(vEvent.getDescription().getValue());
            }
            event.getCategoryList().addAll(readCategory(vEvent));
            event.setFilename(filename);
            log.trace("adding event: " + event.getShortName());
            eventContainer.getEventList().add(event);
        }
    }
    if (lastModifedVEventOverAll != null && !config.isLastModifiedFileTimeStampValid()) {
        eventContainer.setLastChanged(lastModifedVEventOverAll);
        log.debug("changing eventcontainer last modified to {}", lastModifedVEventOverAll);
    }
    // if (!eventContainer.getEventList().isEmpty()) {
    CalDavLoaderImpl.instance.addEventToMap(eventContainer, true);
    if (!readFromFile) {
        Util.storeToDisk(config.getKey(), filename, calendar);
    }
// }
}
Also used : VEvent(net.fortuna.ical4j.model.component.VEvent) InputStreamReader(java.io.InputStreamReader) CalendarBuilder(net.fortuna.ical4j.data.CalendarBuilder) EventContainer(org.openhab.io.caldav.internal.EventStorage.EventContainer) CalendarComponent(net.fortuna.ical4j.model.component.CalendarComponent) UnfoldingReader(net.fortuna.ical4j.data.UnfoldingReader) Calendar(net.fortuna.ical4j.model.Calendar) Period(net.fortuna.ical4j.model.Period) PeriodList(net.fortuna.ical4j.model.PeriodList) DateTime(net.fortuna.ical4j.model.DateTime) LocalDateTime(org.joda.time.LocalDateTime) CalDavEvent(org.openhab.io.caldav.CalDavEvent) BufferedReader(java.io.BufferedReader) CalendarRuntime(org.openhab.io.caldav.internal.EventStorage.CalendarRuntime)

Example 17 with CalendarBuilder

use of net.fortuna.ical4j.data.CalendarBuilder in project OpenOLAT by OpenOLAT.

the class CalendarImportTest method testImportAllFromOutlook.

@Test
public void testImportAllFromOutlook() throws IOException, ParserException {
    InputStream in = CalendarImportTest.class.getResourceAsStream("BB_Alles.ics");
    CalendarBuilder builder = new CalendarBuilder();
    Calendar calendar = builder.build(in);
    assertNotNull(calendar);
}
Also used : CalendarBuilder(net.fortuna.ical4j.data.CalendarBuilder) InputStream(java.io.InputStream) Calendar(net.fortuna.ical4j.model.Calendar) Test(org.junit.Test)

Example 18 with CalendarBuilder

use of net.fortuna.ical4j.data.CalendarBuilder in project OpenOLAT by OpenOLAT.

the class ICalFileCalendarManager method synchronizeCalendarFrom.

@Override
public boolean synchronizeCalendarFrom(InputStream in, String source, Kalendar targetCalendar) {
    try (BufferedReader reader = new BufferedReader(new InputStreamReader(in))) {
        Calendar inCalendar = new CalendarBuilder().build(reader);
        Kalendar inTmpKalendar = createKalendar("TEMP", UUID.randomUUID().toString(), inCalendar);
        String targetId = "-" + targetCalendar.getType() + "-" + targetCalendar.getCalendarID() + "-";
        OLATResourceable calOres = getOresHelperFor(targetCalendar);
        Boolean updatedSuccessful = CoordinatorManager.getInstance().getCoordinator().getSyncer().doInSync(calOres, new SyncerCallback<Boolean>() {

            @Override
            public Boolean execute() {
                // remove event in target calendar which doesn't exist in stream
                Collection<KalendarEvent> currentEvents = targetCalendar.getEvents();
                for (KalendarEvent currentEvent : currentEvents) {
                    if (currentEvent.getExternalSource() != null && source.equals(currentEvent.getExternalSource())) {
                        String eventId = currentEvent.getID();
                        String recurrenceId = currentEvent.getRecurrenceID();
                        if (inTmpKalendar.getEvent(eventId, recurrenceId) == null) {
                            targetCalendar.removeEvent(currentEvent);
                        } else if (eventId.contains(targetId)) {
                            // don't import myself;
                            targetCalendar.removeEvent(currentEvent);
                        }
                    }
                }
                Collection<KalendarEvent> inEvents = inTmpKalendar.getEvents();
                for (KalendarEvent inEvent : inEvents) {
                    if (inEvent.getID().contains(targetId)) {
                        continue;
                    }
                    inEvent.setManagedFlags(new CalendarManagedFlag[] { CalendarManagedFlag.all });
                    inEvent.setExternalSource(source);
                    KalendarEvent currentEvent = targetCalendar.getEvent(inEvent.getID(), inEvent.getRecurrenceID());
                    if (currentEvent == null) {
                        targetCalendar.addEvent(inEvent);
                    } else {
                        // need perhaps more refined synchronization per event
                        targetCalendar.addEvent(inEvent);
                    }
                }
                boolean successfullyPersist = persistCalendar(targetCalendar);
                // inform all controller about calendar change for reload
                CoordinatorManager.getInstance().getCoordinator().getEventBus().fireEventToListenersOf(new CalendarGUIModifiedEvent(targetCalendar), OresHelper.lookupType(CalendarManager.class));
                return new Boolean(successfullyPersist);
            }
        });
        return updatedSuccessful.booleanValue();
    } catch (Exception e) {
        log.error("", e);
        return false;
    }
}
Also used : InputStreamReader(java.io.InputStreamReader) CalendarBuilder(net.fortuna.ical4j.data.CalendarBuilder) OLATResourceable(org.olat.core.id.OLATResourceable) Calendar(net.fortuna.ical4j.model.Calendar) KalendarEvent(org.olat.commons.calendar.model.KalendarEvent) URISyntaxException(java.net.URISyntaxException) ParseException(java.text.ParseException) FileNotFoundException(java.io.FileNotFoundException) OLATRuntimeException(org.olat.core.logging.OLATRuntimeException) Kalendar(org.olat.commons.calendar.model.Kalendar) BufferedReader(java.io.BufferedReader) CalendarManagedFlag(org.olat.commons.calendar.CalendarManagedFlag) Collection(java.util.Collection) CalendarGUIModifiedEvent(org.olat.commons.calendar.ui.events.CalendarGUIModifiedEvent)

Example 19 with CalendarBuilder

use of net.fortuna.ical4j.data.CalendarBuilder in project OpenOLAT by OpenOLAT.

the class ICalFileCalendarManager method buildKalendarFrom.

@Override
public Kalendar buildKalendarFrom(InputStream in, String calType, String calId) {
    Kalendar kalendar = null;
    try (BufferedReader reader = new BufferedReader(new InputStreamReader(in))) {
        CalendarBuilder builder = new CalendarBuilder();
        Calendar calendar = builder.build(reader);
        kalendar = createKalendar(calType, calId, calendar);
    } catch (Exception e) {
        throw new OLATRuntimeException("Error parsing calendar file.", e);
    }
    return kalendar;
}
Also used : Kalendar(org.olat.commons.calendar.model.Kalendar) InputStreamReader(java.io.InputStreamReader) CalendarBuilder(net.fortuna.ical4j.data.CalendarBuilder) OLATRuntimeException(org.olat.core.logging.OLATRuntimeException) Calendar(net.fortuna.ical4j.model.Calendar) BufferedReader(java.io.BufferedReader) URISyntaxException(java.net.URISyntaxException) ParseException(java.text.ParseException) FileNotFoundException(java.io.FileNotFoundException) OLATRuntimeException(org.olat.core.logging.OLATRuntimeException)

Example 20 with CalendarBuilder

use of net.fortuna.ical4j.data.CalendarBuilder in project ofbiz-framework by apache.

the class ICalConverter method storeCalendar.

/**
 * Update work efforts from an incoming iCalendar request.
 * @param is
 * @param context
 * @throws IOException
 * @throws ParserException
 * @throws GenericEntityException
 * @throws GenericServiceException
 */
public static ResponseProperties storeCalendar(InputStream is, Map<String, Object> context) throws IOException, ParserException, GenericEntityException, GenericServiceException {
    CalendarBuilder builder = new CalendarBuilder();
    Calendar calendar = null;
    try {
        calendar = builder.build(is);
    } finally {
        if (is != null) {
            is.close();
        }
    }
    if (Debug.verboseOn()) {
        Debug.logVerbose("Processing calendar:\r\n" + calendar, module);
    }
    String workEffortId = fromXProperty(calendar.getProperties(), workEffortIdXPropName);
    if (workEffortId == null) {
        workEffortId = (String) context.get("workEffortId");
    }
    if (!workEffortId.equals(context.get("workEffortId"))) {
        Debug.logWarning("Spoof attempt: received calendar workEffortId " + workEffortId + " on URL workEffortId " + context.get("workEffortId"), module);
        return ICalWorker.createForbiddenResponse(null);
    }
    Delegator delegator = (Delegator) context.get("delegator");
    GenericValue publishProperties = EntityQuery.use(delegator).from("WorkEffort").where("workEffortId", workEffortId).queryOne();
    if (!isCalendarPublished(publishProperties)) {
        Debug.logInfo("WorkEffort calendar is not published: " + workEffortId, module);
        return ICalWorker.createNotFoundResponse(null);
    }
    if (context.get("userLogin") == null) {
        return ICalWorker.createNotAuthorizedResponse(null);
    }
    if (!hasPermission(workEffortId, "UPDATE", context)) {
        return ICalWorker.createForbiddenResponse(null);
    }
    boolean hasCreatePermission = hasPermission(workEffortId, "CREATE", context);
    List<GenericValue> workEfforts = getRelatedWorkEfforts(publishProperties, context);
    Set<String> validWorkEfforts = new HashSet<>();
    if (UtilValidate.isNotEmpty(workEfforts)) {
        // Security issue: make sure only related work efforts get updated
        for (GenericValue workEffort : workEfforts) {
            validWorkEfforts.add(workEffort.getString("workEffortId"));
        }
    }
    List<Component> components = UtilGenerics.checkList(calendar.getComponents(), Component.class);
    ResponseProperties responseProps = null;
    for (Component component : components) {
        if (Component.VEVENT.equals(component.getName()) || Component.VTODO.equals(component.getName())) {
            workEffortId = fromXProperty(component.getProperties(), workEffortIdXPropName);
            if (workEffortId == null) {
                Property uid = component.getProperty(Uid.UID);
                if (uid != null) {
                    GenericValue workEffort = EntityQuery.use(delegator).from("WorkEffort").where("universalId", uid.getValue()).queryFirst();
                    if (workEffort != null) {
                        workEffortId = workEffort.getString("workEffortId");
                    }
                }
            }
            if (workEffortId != null) {
                if (validWorkEfforts.contains(workEffortId)) {
                    replaceProperty(component.getProperties(), toXProperty(workEffortIdXPropName, workEffortId));
                    responseProps = storeWorkEffort(component, context);
                } else {
                    Debug.logWarning("Spoof attempt: unrelated workEffortId " + workEffortId + " on URL workEffortId " + context.get("workEffortId"), module);
                    responseProps = ICalWorker.createForbiddenResponse(null);
                }
            } else if (hasCreatePermission) {
                responseProps = createWorkEffort(component, context);
            }
            if (responseProps != null) {
                return responseProps;
            }
        }
    }
    Map<String, ? extends Object> serviceMap = UtilMisc.toMap("workEffortId", context.get("workEffortId"), "icalData", calendar.toString());
    GenericValue iCalData = publishProperties.getRelatedOne("WorkEffortIcalData", false);
    Map<String, Object> serviceResult = null;
    if (iCalData == null) {
        serviceResult = invokeService("createWorkEffortICalData", serviceMap, context);
    } else {
        serviceResult = invokeService("updateWorkEffortICalData", serviceMap, context);
    }
    if (ServiceUtil.isError(serviceResult)) {
        return ICalWorker.createPartialContentResponse(ServiceUtil.getErrorMessage(serviceResult));
    }
    return ICalWorker.createOkResponse(null);
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) CalendarBuilder(net.fortuna.ical4j.data.CalendarBuilder) Calendar(net.fortuna.ical4j.model.Calendar) Delegator(org.apache.ofbiz.entity.Delegator) ResponseProperties(org.apache.ofbiz.workeffort.workeffort.ICalWorker.ResponseProperties) Component(net.fortuna.ical4j.model.Component) XProperty(net.fortuna.ical4j.model.property.XProperty) Property(net.fortuna.ical4j.model.Property) HashSet(java.util.HashSet)

Aggregations

CalendarBuilder (net.fortuna.ical4j.data.CalendarBuilder)28 Calendar (net.fortuna.ical4j.model.Calendar)25 Test (org.junit.Test)15 InputStream (java.io.InputStream)14 URISyntaxException (java.net.URISyntaxException)7 OLATRuntimeException (org.olat.core.logging.OLATRuntimeException)6 BufferedReader (java.io.BufferedReader)5 IOException (java.io.IOException)5 InputStreamReader (java.io.InputStreamReader)5 ParserException (net.fortuna.ical4j.data.ParserException)5 FileNotFoundException (java.io.FileNotFoundException)4 ParseException (java.text.ParseException)4 Property (net.fortuna.ical4j.model.Property)4 VEvent (net.fortuna.ical4j.model.component.VEvent)4 Kalendar (org.olat.commons.calendar.model.Kalendar)4 Date (java.util.Date)3 Component (net.fortuna.ical4j.model.Component)3 DateTime (net.fortuna.ical4j.model.DateTime)3 Period (net.fortuna.ical4j.model.Period)3 PeriodList (net.fortuna.ical4j.model.PeriodList)3