/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2005 Bull S.A.
 * Contact: jonas-team@ow2.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
 * USA
 *
 * --------------------------------------------------------------------------
 * $Id: ApplyUploadAction.java 16121 2009-01-07 16:17:40Z eyindanga $
 * --------------------------------------------------------------------------
 */

package org.ow2.jonas.webapp.jonasadmin.deploy;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;

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

import org.ow2.jonas.lib.management.extensions.base.JonasManagementRepr;
import org.ow2.jonas.lib.management.javaee.J2eeObjectName;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;


/**
 * Upload a file to the J2EE server.
 * @author Florent Benoit
 */
public class ApplyUploadAction extends BaseDeployAction {

    /**
     * Size of Buffer
     */
    private static final int BUFFER_SIZE = 1024;

    /**
     * Execute the action with given params
     * @param actionMapping The ActionMapping used to select this instance
     * @param actionForm The optional ActionForm bean for this request (if any)
     * @param request The HTTP request we are processing
     * @param response The HTTP response we are creating
     * @return a forward when action is finished
     * @exception ServletException if business logic throws an exception
     */
    public ActionForward executeAction(ActionMapping actionMapping, ActionForm actionForm, HttpServletRequest request,
            HttpServletResponse response) throws ServletException {
        String sForward = "Upload Result";

        if (!(actionForm instanceof UploadForm)) {
            Throwable t = new Throwable("Action not instance of UploadForm");
            addGlobalError(t);
            saveErrors(request, m_Errors);
            return (actionMapping.findForward("Global Error"));
        }

        // this line is here for when the input page is upload-utf8.jsp,
        // it sets the correct character encoding for the response
        String encoding = request.getCharacterEncoding();
        if ((encoding != null) && (encoding.equalsIgnoreCase("utf-8"))) {
            response.setContentType("text/html; charset=utf-8");
        }

        UploadForm uploadForm = (UploadForm) actionForm;

        // indicated whether to return to regular or domain deployment page
        uploadForm.setIsDomain(isDomain());

        // retrieve the file representation
        FormFile file = uploadForm.getUploadedFile();

        // retrieve the file name
        String fileName = file.getFileName();

        // retrieve the content type
        String contentType = file.getContentType();

        // retrieve the file size
        String size = (file.getFileSize() + " bytes");

        String serverName = m_WhereAreYou.getCurrentJonasServerName();

        // J2EE server MBean
        ObjectName j2eeServer = J2eeObjectName.J2EEServer(m_WhereAreYou.getCurrentDomainName(), serverName);

        // invoke method on the MBean
        String sentFile = null;
        InputStream inputStream = null;
        ByteArrayOutputStream baos = null;
        int len;
        try {
            inputStream = file.getInputStream();
            baos = new ByteArrayOutputStream();
            byte[] buf = new byte[BUFFER_SIZE];
            // Read bytes
            while ((len = inputStream.read(buf)) > 0) {
                baos.write(buf, 0, len);
            }
            byte[] bytesOfFile = baos.toByteArray();
            Object[] param = new Object[] {bytesOfFile, fileName, Boolean.valueOf(uploadForm.isOverwrite())};
            String[] signature = {"[B", "java.lang.String", "boolean"};
            sentFile = (String) JonasManagementRepr.invoke(j2eeServer, "sendFile", param, signature, serverName);
        } catch (Exception e) {
            addGlobalError(e);
            saveErrors(request, m_Errors);
            return (actionMapping.findForward("Upload"));
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (baos != null) {
                    baos.close();
                }
            } catch (Exception e) {
                getServlet().log("Cannot close streams", e);
            }

        }

        // place the data into the request for retrieval for display
        request.setAttribute("fileName", fileName);
        request.setAttribute("contentType", contentType);
        request.setAttribute("size", size);
        request.setAttribute("data", "File uploaded in '" + sentFile + "'");
        // destroy the temporary file created
        file.destroy();

        // Forward to the jsp.
        return (actionMapping.findForward(sForward));
    }
}
