/*
 * Copyright 2006-2007 Queplix Corp.
 *
 * Licensed under the Queplix Public License, Version 1.1.1 (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.queplix.com/solutions/commercial-open-source/queplix-public-license/
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 *
 */

package com.queplix.core.modules.services.www;

import com.queplix.core.integrator.security.LogonSession;
import com.queplix.core.integrator.security.WebLoginManager;
import com.queplix.core.modules.services.Service;
import com.queplix.core.utils.www.AbstractServlet;
import com.queplix.core.utils.www.ServletHelper;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Serializable;
import java.util.Enumeration;

/**
 * User action caller servlet.
 * <p/>
 * <p/>
 * Usage:
 * <pre>
 *   /action?a=ACTION_NAME[&param1=value1&...]
 * </pre>,
 * where <code>ACTION_NAME</code> is an action (script) short name
 * </p>
 *
 * @author [ONZ] Oleg N. Zhovtanyuk
 * @author [ALB] Baranov Andrey
 * @version $Revision: 1.2 $ $Date: 2006/04/03 06:47:56 $
 */
public class ActionServlet
        extends AbstractServlet {

    /* (non-Javadoc)
     * @see HttpServlet#service(HttpServletRequest, HttpServletResponse)
     */
    public void service(HttpServletRequest request,
                        HttpServletResponse response)
            throws IOException, ServletException {

        // Login check.
        LogonSession ls = null;
        try {
            ls = WebLoginManager.getLogonSession(request);
        } catch (Exception ex) {
            throw new ServletException(ex);
        }

        // Get an action name.
        String scriptName = ServletHelper.getParamAsString(request, "a");

        // Create a new service object.
        Service service = new Service(ls, scriptName);

        // Add the HTTP request parameters to the service object.
        Enumeration names = request.getParameterNames();
        while(names.hasMoreElements()) {
            String name = (String) names.nextElement();
            String param = request.getParameter(name);
            service.addParameter(name, param);
        }

        // Perform the action.
        logger.DEBUG("Performing action: " + service);
        Serializable value = service.performWithXAContext();
        if(value != null) {
            response.getWriter().println(value);
        }

    }

}
