/*
 * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved.
 *
 * The contents of this file are subject to the CCM Public
 * License (the "License"); you may not use this file except in
 * compliance with the License. You may obtain a copy of the
 * License at http://www.redhat.com/licenses/ccmpl.html.
 *
 * Software distributed under the License is distributed on an
 * "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express
 * or implied. See the License for the specific language
 * governing rights and limitations under the License.
 *
 */
package com.arsdigita.web;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;

import com.arsdigita.kernel.URLService;
import com.arsdigita.kernel.NoValidURLException;
import com.arsdigita.kernel.URLFinderNotFoundException;

import com.arsdigita.persistence.OID;
import com.arsdigita.toolbox.ui.OIDParameter;

import org.apache.log4j.Logger;


public class OIDRedirectServlet extends BaseServlet {
    
    private static final Logger s_log = 
        Logger.getLogger(OIDRedirectServlet.class);

    public static final String OID_PARAM = "oid";

    private static final OIDParameter param = new OIDParameter(OID_PARAM);

    protected void doService(HttpServletRequest sreq,
                             HttpServletResponse sresp)
        throws ServletException, IOException {

        OID oid = (OID)param.transformValue(sreq);
        
        if (oid == null) {
            if (s_log.isDebugEnabled()) {
                s_log.debug("No OID parameter supplied");
            }
            sresp.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        
        try {
	    String context = sreq.getParameter("context");
            String url = URLService.locate(oid,context);

            if (s_log.isDebugEnabled()) {
                s_log.debug("Redirecting oid " + oid + " to " + url);
            }
            
            throw new RedirectSignal(url, false);
        } catch (URLFinderNotFoundException ex) {
            if (s_log.isDebugEnabled()) {
                s_log.debug("No URL finder for oid " + oid);
            }
            sresp.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        } catch (NoValidURLException ex) {
            if (s_log.isDebugEnabled()) {
                s_log.debug("No URL for oid " + oid);
            }
            sresp.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
    }
}
