001/*
002 * Copyright (c) 2006-2011 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the Eclipse Public License v1.0
006 * which accompanies this distribution, and is available at
007 * http://www.eclipse.org/legal/epl-v10.html
008 *
009 * Contributors:
010 *     bstefanescu
011 */
012package org.nuxeo.ecm.platform.picture.operation;
013
014import java.io.IOException;
015import java.io.Serializable;
016import java.util.ArrayList;
017import java.util.HashMap;
018import java.util.Iterator;
019import java.util.Map;
020import java.util.Map.Entry;
021
022import org.apache.commons.logging.Log;
023import org.apache.commons.logging.LogFactory;
024import org.codehaus.jackson.JsonNode;
025import org.codehaus.jackson.map.ObjectMapper;
026import org.nuxeo.ecm.automation.core.Constants;
027import org.nuxeo.ecm.automation.core.annotations.Context;
028import org.nuxeo.ecm.automation.core.annotations.Operation;
029import org.nuxeo.ecm.automation.core.annotations.OperationMethod;
030import org.nuxeo.ecm.automation.core.annotations.Param;
031import org.nuxeo.ecm.automation.core.collectors.DocumentModelCollector;
032import org.nuxeo.ecm.automation.core.util.ComplexTypeJSONDecoder;
033import org.nuxeo.ecm.automation.core.util.DocumentHelper;
034import org.nuxeo.ecm.automation.core.util.Properties;
035import org.nuxeo.ecm.core.api.Blob;
036import org.nuxeo.ecm.core.api.CoreSession;
037import org.nuxeo.ecm.core.api.DocumentModel;
038import org.nuxeo.ecm.core.api.DocumentRef;
039import org.nuxeo.ecm.platform.picture.api.adapters.PictureResourceAdapter;
040
041/**
042 * Create a Picture document into the input document
043 *
044 * @author <a href="mailto:tdelprat@nuxeo.com">Thierry Delprat</a>
045 */
046@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.")
047public class CreatePicture {
048
049    public static final String ID = "Picture.Create";
050
051    public static final String PICTURE_FIELD = "originalPicture";
052
053    @Context
054    protected CoreSession session;
055
056    @Param(name = "name", required = false)
057    protected String name;
058
059    @Param(name = "properties", required = false)
060    protected Properties content;
061
062    @Param(name = "pictureTemplates", required = false)
063    protected Properties pictureTemplates;
064
065    protected static final Log log = LogFactory.getLog(CreatePicture.class);
066
067    protected ArrayList<Map<String, Object>> computePictureTemplates() {
068        if (pictureTemplates == null || pictureTemplates.size() == 0) {
069            return null;
070        }
071        ArrayList<Map<String, Object>> templates = new ArrayList<Map<String, Object>>();
072
073        try {
074            ObjectMapper mapper = new ObjectMapper();
075
076            // for (String templateDef : pictureTemplates) {
077            for (String name : pictureTemplates.keySet()) {
078                String templateDef = pictureTemplates.get(name);
079                JsonNode node = mapper.readTree(templateDef);
080                Map<String, Object> map = new HashMap<String, Object>();
081                map.put("tag", name);
082                Iterator<Entry<String, JsonNode>> it = node.getFields();
083                while (it.hasNext()) {
084                    Entry<String, JsonNode> entry = it.next();
085                    if (entry.getValue().isInt() || entry.getValue().isLong()) {
086                        map.put(entry.getKey(), entry.getValue().getLongValue());
087                    } else {
088                        map.put(entry.getKey(), entry.getValue().getValueAsText());
089                    }
090                }
091                templates.add(map);
092            }
093        } catch (IOException e) {
094            log.error("Error while parsing picture templates", e);
095        }
096
097        return templates;
098    }
099
100    @OperationMethod(collector = DocumentModelCollector.class)
101    public DocumentModel run(DocumentModel doc) throws IOException {
102        if (name == null) {
103            name = "Untitled";
104        }
105        String jsonBlob = content.get(PICTURE_FIELD);
106        content.remove(PICTURE_FIELD);
107
108        ArrayList<Map<String, Object>> templates = computePictureTemplates();
109
110        DocumentModel newDoc = session.createDocumentModel(doc.getPathAsString(), name, "Picture");
111        if (content != null) {
112            DocumentHelper.setProperties(session, newDoc, content);
113        }
114        DocumentModel picture = session.createDocument(newDoc);
115
116        if (jsonBlob == null) {
117            log.warn("Properties does not contains originalPicture field");
118        } else {
119            Blob blob = (Blob) ComplexTypeJSONDecoder.decode(null, jsonBlob);
120            if (blob == null) {
121                log.warn("Unable to read Blob from properties");
122            } else {
123                picture.setPropertyValue("file:content", (Serializable) blob);
124                picture.setPropertyValue("file:filename", blob.getFilename());
125                PictureResourceAdapter adapter = picture.getAdapter(PictureResourceAdapter.class);
126                adapter.fillPictureViews(blob, blob.getFilename(), picture.getTitle(), templates);
127                picture = session.saveDocument(picture);
128            }
129        }
130        return picture;
131    }
132
133    @OperationMethod(collector = DocumentModelCollector.class)
134    public DocumentModel run(DocumentRef doc) throws IOException {
135        return run(session.getDocument(doc));
136    }
137
138}