package org.mortbay.gwt;

import com.google.gwt.user.server.rpc.OpenRemoteServiceServlet14;
import com.google.gwt.user.server.rpc.UnexpectedException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.ServletException;
import java.io.IOException;

/**
 * Jetty Continuation support for GWT RPC.
 * 
 * @author Craig Day (craig@alderaan.com.au)
 */
public class AsyncRemoteServiceServlet14 extends OpenRemoteServiceServlet14 {

    public static final String PAYLOAD = "com.google.gwt.payload";

    private static final String JETTY_RETRY_REQUEST_EXCEPTION = "org.mortbay.jetty.RetryRequest";

    /* ------------------------------------------------------------ */
    /* (non-Javadoc)
     * @see com.google.gwt.user.server.rpc.OpenRemoteServiceServlet#readPayloadAsUtf8(javax.servlet.http.HttpServletRequest)
     */
    protected String readPayloadAsUtf8(HttpServletRequest request) throws IOException, ServletException {
        String payload = (String) request.getAttribute(PAYLOAD);
        if (payload == null) {
            payload = super.readPayloadAsUtf8(request);
            request.setAttribute(PAYLOAD, payload);
        }
        return payload;
    }


    /**
     * Overridden to really throw Jetty RetryRequest Exception (as opposed to sending failure to client).
     *
     * @param caught the exception
     */
    protected void doUnexpectedFailure(Throwable caught) {
        throwIfRetyRequest(caught);
        super.doUnexpectedFailure(caught);
    }

    /**
     * Throws the Jetty RetryRequest if found.
     *
     * @param caught the exception
     */
    protected void throwIfRetyRequest(Throwable caught) {
        if (caught instanceof UnexpectedException) {
            caught = caught.getCause();
        }
        if (caught instanceof RuntimeException && JETTY_RETRY_REQUEST_EXCEPTION.equals(caught.getClass().getName())) {
            throw (RuntimeException) caught;
        }
    }


}

