001/*
002 * (C) Copyright 2013-2020 Nuxeo (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 *     dmetzler
018 */
019package org.nuxeo.ecm.restapi.server.jaxrs;
020
021import java.util.List;
022
023import javax.ws.rs.Consumes;
024import javax.ws.rs.DELETE;
025import javax.ws.rs.GET;
026import javax.ws.rs.POST;
027import javax.ws.rs.PUT;
028import javax.ws.rs.Path;
029import javax.ws.rs.Produces;
030import javax.ws.rs.core.Context;
031import javax.ws.rs.core.HttpHeaders;
032import javax.ws.rs.core.MediaType;
033import javax.ws.rs.core.Response;
034import javax.ws.rs.core.Response.Status;
035
036import org.apache.commons.lang3.StringUtils;
037import org.apache.commons.logging.Log;
038import org.apache.commons.logging.LogFactory;
039import org.nuxeo.ecm.core.api.CoreSession;
040import org.nuxeo.ecm.core.api.DocumentModel;
041import org.nuxeo.ecm.core.api.DocumentRef;
042import org.nuxeo.ecm.core.api.NuxeoException;
043import org.nuxeo.ecm.core.api.PathRef;
044import org.nuxeo.ecm.core.api.VersioningOption;
045import org.nuxeo.ecm.core.api.versioning.VersioningService;
046import org.nuxeo.ecm.core.io.marshallers.json.document.DocumentModelJsonReader;
047import org.nuxeo.ecm.core.rest.DocumentObject;
048import org.nuxeo.ecm.restapi.jaxrs.io.RestConstants;
049import org.nuxeo.ecm.webengine.model.WebObject;
050
051/**
052 * This object basically overrides the default DocumentObject that doesn't know how to produce/consume JSON
053 *
054 * @since 5.7.2
055 */
056
057@WebObject(type = "Document")
058@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_JSON + "+esentity" })
059public class JSONDocumentObject extends DocumentObject {
060
061    protected static final Log log = LogFactory.getLog(JSONDocumentObject.class);
062
063    private boolean isVersioning;
064
065    @Override
066    @GET
067    public DocumentModel doGet() {
068        return doc;
069    }
070
071    /**
072     * @return the document or the last version document in case of versioning handled
073     */
074    @PUT
075    @Consumes(MediaType.APPLICATION_JSON)
076    public DocumentModel doPut(DocumentModel inputDoc, @Context HttpHeaders headers) {
077        DocumentModelJsonReader.applyPropertyValues(inputDoc, doc);
078        CoreSession session = ctx.getCoreSession();
079        versioningDocFromHeaderIfExists(doc, headers);
080        updateCommentFromHeader(headers);
081        doc = session.saveDocument(doc);
082        session.save();
083        return isVersioning ? session.getLastDocumentVersion(doc.getRef()) : doc;
084    }
085
086    @POST
087    @Consumes(MediaType.APPLICATION_JSON)
088    public Response doPost(DocumentModel inputDoc, @Context HttpHeaders headers) {
089        CoreSession session = ctx.getCoreSession();
090        if (StringUtils.isBlank(inputDoc.getType()) || StringUtils.isBlank(inputDoc.getName())) {
091            throw new NuxeoException("type or name property is missing", Status.BAD_REQUEST.getStatusCode());
092        }
093        DocumentModel createdDoc = session.createDocumentModel(doc.getPathAsString(), inputDoc.getName(),
094                inputDoc.getType());
095        DocumentModelJsonReader.applyPropertyValues(inputDoc, createdDoc);
096        versioningDocFromHeaderIfExists(createdDoc, headers);
097        createdDoc = session.createDocument(createdDoc);
098        session.save();
099        return Response.ok(createdDoc).status(Status.CREATED).build();
100    }
101
102    @Override
103    @DELETE
104    public Response doDelete() {
105        super.doDelete();
106        return Response.noContent().build();
107    }
108
109    @Override
110    @Path("@search")
111    public Object search() {
112        return ctx.newAdapter(this, "search");
113    }
114
115    @Override
116    public DocumentObject newDocument(String path) {
117        PathRef pathRef = new PathRef(doc.getPath().append(path).toString());
118        DocumentModel doc = ctx.getCoreSession().getDocument(pathRef);
119        return (DocumentObject) ctx.newObject("Document", doc);
120    }
121
122    @Override
123    public DocumentObject newDocument(DocumentRef ref) {
124        DocumentModel doc = ctx.getCoreSession().getDocument(ref);
125        return (DocumentObject) ctx.newObject("Document", doc);
126    }
127
128    @Override
129    public DocumentObject newDocument(DocumentModel doc) {
130        return (DocumentObject) ctx.newObject("Document", doc);
131    }
132
133    /**
134     * In case of version option header presence, checkin the related document
135     *
136     * @param headers X-Versioning-Option or Source (for automatic versioning) Header
137     */
138    private void versioningDocFromHeaderIfExists(DocumentModel doc, HttpHeaders headers) {
139        isVersioning = false;
140        List<String> versionHeader = headers.getRequestHeader(RestConstants.X_VERSIONING_OPTION);
141        List<String> sourceHeader = headers.getRequestHeader(RestConstants.SOURCE);
142        if (versionHeader != null && !versionHeader.isEmpty()) {
143            VersioningOption versioningOption = VersioningOption.valueOf(versionHeader.get(0).toUpperCase());
144            if (!versioningOption.equals(VersioningOption.NONE)) {
145                doc.putContextData(VersioningService.VERSIONING_OPTION, versioningOption);
146                isVersioning = true;
147            }
148        } else if (sourceHeader != null && !sourceHeader.isEmpty()) {
149            doc.putContextData(CoreSession.SOURCE, sourceHeader.get(0));
150            isVersioning = true;
151        }
152    }
153
154    /**
155     * Fills the {@code doc} context data with a comment from the {@code Update-Comment} header if present.
156     *
157     * @since 9.3
158     */
159    protected void updateCommentFromHeader(HttpHeaders headers) {
160        List<String> updateCommentHeader = headers.getRequestHeader(RestConstants.UPDATE_COMMENT_HEADER);
161        if (updateCommentHeader != null && !updateCommentHeader.isEmpty()) {
162            String comment = updateCommentHeader.get(0);
163            doc.putContextData("comment", comment);
164        }
165    }
166}