001/*
002 * (C) Copyright 2012 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 *
016 * Contributors:
017 *     Arnaud Kervern
018 */
019package org.nuxeo.ecm.agenda;
020
021import java.io.Serializable;
022import java.util.Date;
023import java.util.Map;
024
025import org.apache.commons.lang.StringUtils;
026import org.apache.commons.logging.Log;
027import org.apache.commons.logging.LogFactory;
028import org.joda.time.DateTime;
029import org.joda.time.format.DateTimeFormatter;
030import org.joda.time.format.ISODateTimeFormat;
031import org.nuxeo.common.utils.IdUtils;
032import org.nuxeo.ecm.core.api.CoreSession;
033import org.nuxeo.ecm.core.api.DocumentModel;
034import org.nuxeo.ecm.core.api.DocumentModelList;
035import org.nuxeo.ecm.core.api.NuxeoException;
036import org.nuxeo.ecm.core.api.PropertyException;
037import org.nuxeo.ecm.platform.userworkspace.api.UserWorkspaceService;
038import org.nuxeo.runtime.api.Framework;
039import org.nuxeo.runtime.model.DefaultComponent;
040
041/**
042 * @author <a href="mailto:akervern@nuxeo.com">Arnaud Kervern</a>
043 * @since 5.6
044 */
045public class AgendaComponent extends DefaultComponent implements AgendaService {
046
047    public static final String VEVENT_TYPE = "VEVENT";
048
049    public static final String SCHEDULABLE_TYPE = "Schedulable";
050
051    protected static final DateTimeFormatter dateTimeFormatter = ISODateTimeFormat.dateTime();
052
053    protected static final String QUERY_BETWEEN_DATES = "SELECT * FROM Document WHERE " + "ecm:mixinType = '"
054            + SCHEDULABLE_TYPE + "' " + "AND ((vevent:dtstart BETWEEN TIMESTAMP '%s' AND TIMESTAMP '%s') "
055            + "OR (vevent:dtend BETWEEN TIMESTAMP '%s' AND TIMESTAMP '%s') "
056            + "OR (vevent:dtstart < TIMESTAMP '%s' AND vevent:dtend > TIMESTAMP '%s') "
057            + "OR (vevent:dtstart > TIMESTAMP '%s' AND vevent:dtend < TIMESTAMP '%s')) "
058            + "AND ecm:currentLifeCycleState != 'deleted' " + "AND ecm:isCheckedInVersion = 0 AND ecm:isProxy = 0 "
059            + "AND ecm:path STARTSWITH '%s' ORDER BY vevent:dtstart";
060
061    protected static final String QUERY_LIMIT = "SELECT * FROM Document WHERE " + "ecm:mixinType = '"
062            + SCHEDULABLE_TYPE + "' " + "AND vevent:dtend > TIMESTAMP '%s' "
063            + "AND ecm:currentLifeCycleState != 'deleted' " + "AND ecm:isCheckedInVersion = 0 AND ecm:isProxy = 0 "
064            + "AND ecm:path STARTSWITH '%s' ORDER BY vevent:dtstart";
065
066    private static final Log log = LogFactory.getLog(AgendaComponent.class);
067
068    @Override
069    public DocumentModelList listEvents(CoreSession session, String path, Date dtStart, Date dtEnd)
070            {
071        if (dtStart == null) {
072            throw new NuxeoException("Start datetime should not be null");
073        }
074        if (dtEnd == null) {
075            dtEnd = new Date(dtStart.getTime() + 24 * 3600);
076        }
077        if (dtEnd.before(dtStart)) {
078            throw new NuxeoException("End datetime is before start datetime");
079        }
080
081        String strStart = formatDate(dtStart);
082        String strEnd = formatDate(dtEnd);
083        return session.query(String.format(QUERY_BETWEEN_DATES, strStart, strEnd, strStart, strEnd, strStart, strEnd,
084                strStart, strEnd, path));
085    }
086
087    @Override
088    public DocumentModelList listEvents(CoreSession session, String path, int limit) {
089        if (limit <= 0) {
090            throw new NuxeoException("Limit must be greater than 0");
091        }
092
093        return session.query(String.format(QUERY_LIMIT, formatDate(new Date()), path), limit);
094    }
095
096    protected static String formatDate(Date date) {
097        return new DateTime(date.getTime()).toString(dateTimeFormatter);
098    }
099
100    @Override
101    public DocumentModel createEvent(CoreSession session, String path, Map<String, Serializable> properties)
102            {
103        if (StringUtils.isBlank(path) || "/".equals(path)) {
104            path = getCurrentUserWorkspacePath(session);
105        }
106        DocumentModel doc = session.createDocumentModel(VEVENT_TYPE);
107        doc.setPathInfo(path, IdUtils.generateStringId());
108        for (String key : properties.keySet()) {
109            try {
110                doc.setPropertyValue(key, properties.get(key));
111            } catch (PropertyException pe) {
112                log.info("Trying to set an unknown property " + key);
113            }
114        }
115        return session.createDocument(doc);
116    }
117
118    protected String getCurrentUserWorkspacePath(CoreSession session) {
119        UserWorkspaceService userWorkspaceService = Framework.getService(UserWorkspaceService.class);
120        DocumentModel userPersonalWorkspace = userWorkspaceService.getUserPersonalWorkspace(
121                session.getPrincipal().getName(), session.getRootDocument());
122        return userPersonalWorkspace.getPathAsString();
123    }
124}