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 *     Thierry Delprat
018 */
019package org.nuxeo.template.xdocreport.jaxrs;
020
021import java.io.ByteArrayOutputStream;
022import java.io.IOException;
023import java.util.ArrayList;
024import java.util.List;
025
026import javax.ws.rs.GET;
027import javax.ws.rs.Path;
028import javax.ws.rs.PathParam;
029
030import org.apache.commons.logging.Log;
031import org.apache.commons.logging.LogFactory;
032import org.nuxeo.ecm.automation.jaxrs.io.JsonHelper;
033import org.nuxeo.ecm.core.api.Blob;
034import org.nuxeo.ecm.core.api.Blobs;
035import org.nuxeo.ecm.core.api.CoreSession;
036import org.nuxeo.ecm.core.api.DocumentModel;
037import org.nuxeo.ecm.core.api.IdRef;
038import org.nuxeo.ecm.core.api.PropertyException;
039import org.nuxeo.ecm.core.schema.DocumentType;
040import org.nuxeo.ecm.core.schema.SchemaManager;
041import org.nuxeo.runtime.api.Framework;
042import org.nuxeo.template.api.adapters.TemplateSourceDocument;
043import org.nuxeo.template.processors.xdocreport.FieldDefinitionGenerator;
044
045import com.fasterxml.jackson.core.JsonGenerator;
046
047import fr.opensagres.xdocreport.remoting.resources.domain.BinaryData;
048import fr.opensagres.xdocreport.remoting.resources.domain.Filter;
049import fr.opensagres.xdocreport.remoting.resources.domain.LargeBinaryData;
050import fr.opensagres.xdocreport.remoting.resources.domain.Resource;
051import fr.opensagres.xdocreport.remoting.resources.domain.ResourceType;
052import fr.opensagres.xdocreport.remoting.resources.services.ResourcesException;
053import fr.opensagres.xdocreport.remoting.resources.services.jaxrs.JAXRSResourcesService;
054
055/**
056 * @author <a href="mailto:tdelprat@nuxeo.com">Tiry</a>
057 */
058public class XDocReportResourceService extends AbstractResourceService implements JAXRSResourcesService {
059
060    protected static final Log log = LogFactory.getLog(XDocReportResourceService.class);
061
062    public XDocReportResourceService(CoreSession session) {
063        super(session);
064    }
065
066    public List<BinaryData> download(List<String> resourcePaths) {
067        return null;
068    }
069
070    @Override
071    public String getName() {
072        return "Nuxeo-Repository";
073    }
074
075    @Override
076    public Resource getRoot() {
077        Resource root = new NonRecursiveResource();
078        root.setType(ResourceType.CATEGORY);
079        root.setName("Nuxeo");
080        root.setId("nuxeo");
081        List<Resource> children = new ArrayList<Resource>();
082        List<TemplateSourceDocument> templates = getTemplates();
083        for (TemplateSourceDocument template : templates) {
084            children.add(ResourceWrapper.wrap(template));
085        }
086        root.getChildren().addAll(children);
087        return root;
088    }
089
090    @GET
091    @Path("model/list")
092    public String listModels() throws IOException {
093        SchemaManager sm = Framework.getService(SchemaManager.class);
094        DocumentType[] docTypes = sm.getDocumentTypes();
095        List<String> names = new ArrayList<String>();
096
097        for (DocumentType dt : docTypes) {
098            names.add(dt.getName());
099        }
100
101        ByteArrayOutputStream out = new ByteArrayOutputStream();
102        try (JsonGenerator jg = JsonHelper.createJsonGenerator(out)) {
103            jg.writeObject(names);
104        }
105        return out.toString();
106    }
107
108    @GET
109    @Path("model/{type}")
110    public String getFieldDefinition(@PathParam("type") String type) {
111        return FieldDefinitionGenerator.generate(type);
112    }
113
114    @Override
115    public void upload(BinaryData dataIn) {
116        String id = dataIn.getResourceId();
117        if (id != null) {
118            IdRef ref = new IdRef(id);
119            try {
120                DocumentModel target = session.getDocument(ref);
121                TemplateSourceDocument template = target.getAdapter(TemplateSourceDocument.class);
122                if (template != null) {
123                    Blob oldBlob = template.getTemplateBlob();
124
125                    Blob newBlob = Blobs.createBlob(dataIn.getContent(), oldBlob.getMimeType());
126                    newBlob.setFilename(oldBlob.getFilename());
127                    template.setTemplateBlob(newBlob, true);
128                }
129            } catch (PropertyException | IOException e) {
130                log.error("Error during template upload", e);
131            }
132        }
133    }
134
135    @Override
136    public List<BinaryData> downloadMultiple(List<String> arg0) throws ResourcesException {
137        return null;
138    }
139
140    @Override
141    public Resource getRootWithFilter(Filter filter) throws ResourcesException {
142        return getRoot();
143    }
144
145    @Override
146    public LargeBinaryData downloadLarge(String resourcePath) throws ResourcesException {
147        CoreSession session = getCoreSession();
148        if (resourcePath.endsWith(".fields.xml")) {
149            String uuid = resourcePath.replace(".fields.xml", "");
150            DocumentModel targetDoc = session.getDocument(new IdRef(uuid));
151            TemplateSourceDocument template = targetDoc.getAdapter(TemplateSourceDocument.class);
152
153            List<String> types = template.getApplicableTypes();
154            String targetType = "File";
155            if (types.size() > 0) {
156                targetType = types.get(0);
157            }
158            String xml = FieldDefinitionGenerator.generate(targetType);
159            try {
160                return BinaryDataWrapper.wrapXml(xml, resourcePath);
161            } catch (IOException e) {
162                throw new ResourcesException(e);
163            }
164        } else {
165            String uuid = resourcePath;
166            DocumentModel targetDoc = session.getDocument(new IdRef(uuid));
167            TemplateSourceDocument template = targetDoc.getAdapter(TemplateSourceDocument.class);
168            try {
169                return BinaryDataWrapper.wrap(template);
170            } catch (IOException e) {
171                throw new ResourcesException(e);
172            }
173        }
174    }
175
176    @Override
177    public BinaryData download(String resourcePath) {
178        return null;
179    }
180
181    @Override
182    public void uploadLarge(LargeBinaryData dataIn) throws ResourcesException {
183        String id = dataIn.getResourceId();
184        if (id != null) {
185            IdRef ref = new IdRef(id);
186            try {
187                DocumentModel target = session.getDocument(ref);
188                TemplateSourceDocument template = target.getAdapter(TemplateSourceDocument.class);
189                if (template != null) {
190                    Blob oldBlob = template.getTemplateBlob();
191                    Blob newBlob = Blobs.createBlob(dataIn.getContent(), oldBlob.getMimeType());
192                    newBlob.setFilename(oldBlob.getFilename());
193                    template.setTemplateBlob(newBlob, true);
194                }
195            } catch (PropertyException | IOException e) {
196                log.error("Error during template upload", e);
197            }
198        }
199    }
200
201}