001/*
002 * (C) Copyright 2006-2011 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 *     bstefanescu
018 */
019package org.nuxeo.ecm.platform.picture.operation;
020
021import java.io.IOException;
022import java.io.Serializable;
023import java.util.ArrayList;
024import java.util.HashMap;
025import java.util.Iterator;
026import java.util.Map;
027import java.util.Map.Entry;
028
029import org.apache.commons.logging.Log;
030import org.apache.commons.logging.LogFactory;
031import org.codehaus.jackson.JsonNode;
032import org.codehaus.jackson.map.ObjectMapper;
033import org.nuxeo.ecm.automation.core.Constants;
034import org.nuxeo.ecm.automation.core.annotations.Context;
035import org.nuxeo.ecm.automation.core.annotations.Operation;
036import org.nuxeo.ecm.automation.core.annotations.OperationMethod;
037import org.nuxeo.ecm.automation.core.annotations.Param;
038import org.nuxeo.ecm.automation.core.collectors.DocumentModelCollector;
039import org.nuxeo.ecm.automation.core.util.ComplexTypeJSONDecoder;
040import org.nuxeo.ecm.automation.core.util.DocumentHelper;
041import org.nuxeo.ecm.automation.core.util.Properties;
042import org.nuxeo.ecm.core.api.Blob;
043import org.nuxeo.ecm.core.api.CoreSession;
044import org.nuxeo.ecm.core.api.DocumentModel;
045import org.nuxeo.ecm.core.api.DocumentRef;
046import org.nuxeo.ecm.platform.picture.api.adapters.PictureResourceAdapter;
047
048/**
049 * Create a Picture document into the input document
050 *
051 * @author <a href="mailto:tdelprat@nuxeo.com">Thierry Delprat</a>
052 */
053@Operation(id = CreatePicture.ID, category = Constants.CAT_SERVICES, label = "Create Picture", description = "Create a Picture document in the input folder. You can initialize the document properties using the 'properties' parameter. The properties are specified as <i>key=value</i> pairs separated by a new line. The key <i>originalPicture</i> is used to reference the JSON representation of the Blob for the original picture. The <i>pictureTemplates</i> parameter can be used to define the size of the different views to be generated, each line must be a JSONObject { title=\"title\", description=\"description\", maxsize=maxsize}. Returns the created document.")
054public class CreatePicture {
055
056    public static final String ID = "Picture.Create";
057
058    public static final String PICTURE_FIELD = "originalPicture";
059
060    @Context
061    protected CoreSession session;
062
063    @Param(name = "name", required = false)
064    protected String name;
065
066    @Param(name = "properties", required = false)
067    protected Properties content;
068
069    @Param(name = "pictureTemplates", required = false)
070    protected Properties pictureTemplates;
071
072    protected static final Log log = LogFactory.getLog(CreatePicture.class);
073
074    protected ArrayList<Map<String, Object>> computePictureTemplates() {
075        if (pictureTemplates == null || pictureTemplates.size() == 0) {
076            return null;
077        }
078        ArrayList<Map<String, Object>> templates = new ArrayList<Map<String, Object>>();
079
080        try {
081            ObjectMapper mapper = new ObjectMapper();
082
083            // for (String templateDef : pictureTemplates) {
084            for (String name : pictureTemplates.keySet()) {
085                String templateDef = pictureTemplates.get(name);
086                JsonNode node = mapper.readTree(templateDef);
087                Map<String, Object> map = new HashMap<String, Object>();
088                map.put("tag", name);
089                Iterator<Entry<String, JsonNode>> it = node.getFields();
090                while (it.hasNext()) {
091                    Entry<String, JsonNode> entry = it.next();
092                    if (entry.getValue().isInt() || entry.getValue().isLong()) {
093                        map.put(entry.getKey(), entry.getValue().getLongValue());
094                    } else {
095                        map.put(entry.getKey(), entry.getValue().getValueAsText());
096                    }
097                }
098                templates.add(map);
099            }
100        } catch (IOException e) {
101            log.error("Error while parsing picture templates", e);
102        }
103
104        return templates;
105    }
106
107    @OperationMethod(collector = DocumentModelCollector.class)
108    public DocumentModel run(DocumentModel doc) throws IOException {
109        if (name == null) {
110            name = "Untitled";
111        }
112        String jsonBlob = content.get(PICTURE_FIELD);
113        content.remove(PICTURE_FIELD);
114
115        ArrayList<Map<String, Object>> templates = computePictureTemplates();
116
117        DocumentModel newDoc = session.createDocumentModel(doc.getPathAsString(), name, "Picture");
118        if (content != null) {
119            DocumentHelper.setProperties(session, newDoc, content);
120        }
121        DocumentModel picture = session.createDocument(newDoc);
122
123        if (jsonBlob == null) {
124            log.warn("Properties does not contains originalPicture field");
125        } else {
126            Blob blob = (Blob) ComplexTypeJSONDecoder.decode(null, jsonBlob);
127            if (blob == null) {
128                log.warn("Unable to read Blob from properties");
129            } else {
130                picture.setPropertyValue("file:content", (Serializable) blob);
131                PictureResourceAdapter adapter = picture.getAdapter(PictureResourceAdapter.class);
132                adapter.fillPictureViews(blob, blob.getFilename(), picture.getTitle(), templates);
133                picture = session.saveDocument(picture);
134            }
135        }
136        return picture;
137    }
138
139    @OperationMethod(collector = DocumentModelCollector.class)
140    public DocumentModel run(DocumentRef doc) throws IOException {
141        return run(session.getDocument(doc));
142    }
143
144}