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 *     bstefanescu
018 */
019package org.nuxeo.ecm.automation.jaxrs.io.operations;
020
021import javax.servlet.http.HttpServletRequest;
022import javax.servlet.http.HttpServletResponse;
023
024import org.nuxeo.ecm.automation.OperationContext;
025import org.nuxeo.ecm.automation.OperationException;
026import org.nuxeo.ecm.core.api.NuxeoException;
027import org.nuxeo.ecm.webengine.jaxrs.context.RequestCleanupHandler;
028import org.nuxeo.ecm.webengine.jaxrs.context.RequestContext;
029
030/**
031 * A custom operation context to be used in REST calls on server side. This implementation is delegating the post
032 * execution cleanup to the webengine filter through {@link RequestContext} and {@link RequestCleanupHandler}.
033 * <p>
034 * This way temporary resources like files used by operations are removed after the response is sent to the client.
035 *
036 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a>
037 */
038public class RestOperationContext extends OperationContext {
039
040
041    /**
042     * Specify the http status when no failure occurs.
043     *
044     * @since 7.1
045     */
046    protected int httpStatus = HttpServletResponse.SC_OK;
047
048    /**
049     * Must be called before context execution.
050     */
051    public void addRequestCleanupHandler(HttpServletRequest request) {
052        RequestContext.getActiveContext(request).addRequestCleanupHandler(new RequestCleanupHandler() {
053            @Override
054            public void cleanup(HttpServletRequest req) {
055                try {
056                    close();
057                } catch (OperationException e) {
058                    throw new NuxeoException(e);
059                }
060            }
061        });
062    }
063
064    /**
065     * @since 7.1
066     */
067    public int getHttpStatus() {
068        return httpStatus;
069    }
070
071    /**
072     * @since 7.1
073     */
074    public void setHttpStatus(int httpStatus) {
075        this.httpStatus = httpStatus;
076    }
077
078}