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.codehaus.jackson.JsonGenerator;
033import org.nuxeo.ecm.automation.jaxrs.io.JsonHelper;
034import org.nuxeo.ecm.core.api.Blob;
035import org.nuxeo.ecm.core.api.Blobs;
036import org.nuxeo.ecm.core.api.CoreSession;
037import org.nuxeo.ecm.core.api.DocumentModel;
038import org.nuxeo.ecm.core.api.IdRef;
039import org.nuxeo.ecm.core.api.PropertyException;
040import org.nuxeo.ecm.core.schema.DocumentType;
041import org.nuxeo.ecm.core.schema.SchemaManager;
042import org.nuxeo.runtime.api.Framework;
043import org.nuxeo.template.api.adapters.TemplateSourceDocument;
044import org.nuxeo.template.processors.xdocreport.FieldDefinitionGenerator;
045
046import fr.opensagres.xdocreport.remoting.resources.domain.BinaryData;
047import fr.opensagres.xdocreport.remoting.resources.domain.Filter;
048import fr.opensagres.xdocreport.remoting.resources.domain.LargeBinaryData;
049import fr.opensagres.xdocreport.remoting.resources.domain.Resource;
050import fr.opensagres.xdocreport.remoting.resources.domain.ResourceType;
051import fr.opensagres.xdocreport.remoting.resources.services.ResourcesException;
052import fr.opensagres.xdocreport.remoting.resources.services.jaxrs.JAXRSResourcesService;
053
054/**
055 * @author <a href="mailto:tdelprat@nuxeo.com">Tiry</a>
056 */
057public class XDocReportResourceService extends AbstractResourceService implements JAXRSResourcesService {
058
059    protected static final Log log = LogFactory.getLog(XDocReportResourceService.class);
060
061    public XDocReportResourceService(CoreSession session) {
062        super(session);
063    }
064
065    public List<BinaryData> download(List<String> resourcePaths) {
066        return null;
067    }
068
069    @Override
070    public String getName() {
071        return "Nuxeo-Repository";
072    }
073
074    @Override
075    public Resource getRoot() {
076        Resource root = new NonRecursiveResource();
077        root.setType(ResourceType.CATEGORY);
078        root.setName("Nuxeo");
079        root.setId("nuxeo");
080        List<Resource> children = new ArrayList<Resource>();
081        List<TemplateSourceDocument> templates = getTemplates();
082        for (TemplateSourceDocument template : templates) {
083            children.add(ResourceWrapper.wrap(template));
084        }
085        root.getChildren().addAll(children);
086        return root;
087    }
088
089    @GET
090    @Path("model/list")
091    public String listModels() throws IOException {
092        SchemaManager sm = Framework.getService(SchemaManager.class);
093        DocumentType[] docTypes = sm.getDocumentTypes();
094        List<String> names = new ArrayList<String>();
095
096        for (DocumentType dt : docTypes) {
097            names.add(dt.getName());
098        }
099
100        ByteArrayOutputStream out = new ByteArrayOutputStream();
101
102        JsonGenerator gen = JsonHelper.createJsonGenerator(out);
103        gen.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}