001/*
002 * Copyright (c) 2006-2011 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the Eclipse Public License v1.0
006 * which accompanies this distribution, and is available at
007 * http://www.eclipse.org/legal/epl-v10.html
008 *
009 * Contributors:
010 *     bstefanescu
011 */
012package org.nuxeo.ecm.automation.jaxrs.io.operations;
013
014import javax.servlet.http.HttpServletRequest;
015
016import org.nuxeo.ecm.automation.OperationContext;
017import org.nuxeo.ecm.automation.OperationException;
018import org.nuxeo.ecm.webengine.jaxrs.context.RequestCleanupHandler;
019import org.nuxeo.ecm.webengine.jaxrs.context.RequestContext;
020
021/**
022 * A custom operation context to be used in REST calls on server side. This implementation is delegating the post
023 * execution cleanup to the webengine filter through {@link RequestContext} and {@link RequestCleanupHandler}.
024 * <p>
025 * This way temporary resources like files used by operations are removed after the response is sent to the client.
026 *
027 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a>
028 */
029public class RestOperationContext extends OperationContext {
030
031
032    /**
033     * Specify the http status when no failure occurs.
034     *
035     * @since 7.1
036     */
037    protected int httpStatus;
038
039    /**
040     * Must be called before context execution.
041     */
042    public void addRequestCleanupHandler(HttpServletRequest request) {
043        RequestContext.getActiveContext(request).addRequestCleanupHandler(new RequestCleanupHandler() {
044            @Override
045            public void cleanup(HttpServletRequest req) {
046                try {
047                    deferredDispose();
048                } catch (OperationException e) {
049                    throw new RuntimeException(e);
050                }
051            }
052        });
053    }
054
055    /**
056     * @since 7.1
057     */
058    public int getHttpStatus() {
059        return httpStatus;
060    }
061
062    /**
063     * @since 7.1
064     */
065    public void setHttpStatus(int httpStatus) {
066        this.httpStatus = httpStatus;
067    }
068
069    protected void deferredDispose() throws OperationException {
070        super.dispose();
071    }
072
073    @Override
074    public void dispose() {
075        // do nothing
076    }
077
078}