/*
 * 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.error.IncorrectParameterException;
import com.queplix.core.integrator.security.LogonSession;
import com.queplix.core.integrator.security.SecurityException;
import com.queplix.core.integrator.security.WebLoginManager;
import com.queplix.core.modules.services.ejb.ScriptManager;
import com.queplix.core.modules.services.ejb.ScriptManagerHome;
import com.queplix.core.utils.JNDINames;
import com.queplix.core.utils.www.AbstractServlet;
import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.List;

/**
 * <p>Class upload servlet<p>
 * <strong>USAGE</strong>: <pre>PUT /classUpload?name="script name"&classname="class name"</pre>
 * <p><strong>Parameters</strong>:
 * name: unique script name
 * classname: java class name
 * </p>
 *
 * @author [ALB] Baranov Andrey
 * @version $Revision: 1.1.1.1 $ $Date: 2005/09/12 15:31:03 $
 */

public class ClassUploadServlet
        extends AbstractServlet {

    // Init parameter names
    private static final String MAX_UPLOAD_SIZE = "maxUploadSize";

    // Init parameters
    private int maxUploadSize;

    //
    // Initialization
    //
    public void init(ServletConfig conf)
            throws ServletException {

        super.init(conf);

        maxUploadSize = Integer.parseInt(conf.getInitParameter(
                MAX_UPLOAD_SIZE));

        if(logger.getLogger().isDebugEnabled()) {
            logger.DEBUG("Init: upload size=" + maxUploadSize);
        }
    }

    //
    // Post method
    //
    public void doPost(HttpServletRequest req, HttpServletResponse res)
            throws IOException, ServletException {

        String scriptName = null;
        String className = null;
        byte[] classData = null;

        try {
            // Check security
            LogonSession ls = WebLoginManager.getLogonSession(req);

            // Get POST items
            DiskFileUpload fileUpload = new DiskFileUpload();
            fileUpload.setSizeMax(maxUploadSize);
            List items = fileUpload.parseRequest(req);

            // Main cycle.
            Iterator it = items.iterator();
            while(it.hasNext()) {
                FileItem fileItem = (FileItem) it.next();

                if(fileItem.isFormField()) {
                    if(fileItem.getFieldName().equals("name")) {
                        scriptName = fileItem.getString();
                    } else if(fileItem.getFieldName().equals("classname")) {
                        className = fileItem.getString();
                    }
                    continue;
                }

                // get class data
                classData = getClassData(req, fileItem);
            }

            // check script name
            if(scriptName == null) {
                throw new IncorrectParameterException("name");
            }

            // check class name
            if(className == null) {
                throw new IncorrectParameterException("classname");
            }

            // check class data
            if(classData == null) {
                throw new IncorrectParameterException("class data");
            }

            // update/create script
            throw new UnsupportedOperationException();

        } catch (SecurityException ex) {
            throw new ServletException(ex);

        } catch (FileUploadException ex) {
            throw new ServletException(ex);
        }
    }

    //
    // Retrive class data from request
    //
    private byte[] getClassData(HttpServletRequest req, FileItem fileItem)
            throws IOException, SecurityException {

        InputStream is = null;
        ByteArrayOutputStream baos = null;

        try {
            is = fileItem.getInputStream();
            baos = new ByteArrayOutputStream();

            byte buf[] = new byte[1024];
            int len;
            while((len = is.read(buf)) > 0) {
                baos.write(buf, 0, len);
            }

            return baos.toByteArray();

        } finally {
            if(baos != null) {
                try {
                    baos.close();
                } catch (Exception ex) {
                }
            }
            if(is != null) {
                try {
                    is.close();
                } catch (Exception ex) {
                }
            }
        }
    }

    //
    // Get ScriptManager remote interface
    //
    private ScriptManager getScriptManager()
            throws ServletException {

        return (ScriptManager)
                getRemoteObject(JNDINames.ScriptManagerRemote,
                        ScriptManagerHome.class);
    }
}
