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 *     Nuxeo - initial API and implementation
018 *
019 */
020
021package org.nuxeo.ecm.automation.server.jaxrs.batch;
022
023import javax.servlet.http.HttpServletRequest;
024
025import org.codehaus.jackson.node.ObjectNode;
026import org.nuxeo.ecm.automation.core.util.JSONBlobDecoder;
027import org.nuxeo.ecm.core.api.Blob;
028import org.nuxeo.ecm.webengine.jaxrs.context.RequestCleanupHandler;
029import org.nuxeo.ecm.webengine.jaxrs.context.RequestContext;
030import org.nuxeo.runtime.api.Framework;
031
032/**
033 * Uses a JSON definition to retrive a Blob uploaded in a batch
034 *
035 * @author Tiry (tdelprat@nuxeo.com)
036 */
037public class JSONBatchBlobDecoder implements JSONBlobDecoder {
038
039    @Override
040    public Blob getBlobFromJSON(ObjectNode jsonObject) {
041
042        Blob blob = null;
043
044        if (!jsonObject.has("upload-batch")) {
045            return null;
046        }
047
048        final String batchId = jsonObject.get("upload-batch").getTextValue();
049        String fileId = null;
050        if (jsonObject.has("upload-fileId")) {
051            fileId = jsonObject.get("upload-fileId").getTextValue();
052        }
053        if (fileId != null) {
054            BatchManager bm = Framework.getLocalService(BatchManager.class);
055            blob = bm.getBlob(batchId, fileId);
056
057            if (RequestContext.getActiveContext() != null) {
058                final boolean drop = !Boolean.parseBoolean(
059                    RequestContext.getActiveContext().getRequest().getHeader(BatchManagerConstants.NO_DROP_FLAG));
060                if (drop) {
061                    RequestContext.getActiveContext().addRequestCleanupHandler(new RequestCleanupHandler() {
062                        @Override
063                        public void cleanup(HttpServletRequest request) {
064                            BatchManager bm = Framework.getLocalService(BatchManager.class);
065                            bm.clean(batchId);
066                        }
067                    });
068                }
069            }
070        }
071        return blob;
072    }
073
074}