/**
 * JaDOrT: JASMINe Deployment Orchestration Tool
 * Copyright (C) 2008-2009 Bull S.A.S.
 * Copyright (C) 2008-2009 France Telecom R&D
 * Contact: jasmine@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: UploadFileServlet.java 2965 2009-01-12 12:14:51Z alitokmen $
 * --------------------------------------------------------------------------
 */
package org.ow2.jasmine.jadort.servlet;

import java.io.File;
import java.io.IOException;
import java.util.List;

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

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * A servlet that allows the client to upload a file on the server. This servlet
 * only supports POST, not GET.
 * 
 * @author Malek Chahine
 * @author Remy Bresson
 * @author S. Ali Tokmen
 */
public class UploadFileServlet extends HttpServlet {

    private static final long serialVersionUID = -4729955174780787192L;

    @Override
    protected void doPost(final HttpServletRequest req, final HttpServletResponse res) throws ServletException, IOException {
        try {
            // Parse the incoming HTTP request
            // Commons takes over incoming request at this point
            // Get an iterator for all the data that was sent

            // Set a response content type
            res.setContentType("text/xml");

            // Setup the output stream for the return XML data
            ServletOutputStream out = res.getOutputStream();
            out.println("<response>");

            for (FileItem item : this.getFileItems(req)) {
                if (item.isFormField()) {
                    // If the current item is an HTML form field
                    // return an XML node with the field name and value
                    out.println("<field name=\"" + item.getFieldName() + "\"value=\"" + item.getString() + "\" />");
                } else {
                    // Else the current item is file data,
                    // write the file data to disk
                    File file = new File(System.getProperty("java.io.tmpdir") + File.separatorChar + "JaDOrT.temp."
                        + System.currentTimeMillis());
                    file.mkdirs();
                    file = new File(file, item.getName());
                    item.write(file);

                    // Return an XML node with the file name and size (in bytes)
                    out.println("<file name=\"" + file.getAbsolutePath() + "\" size=\"" + item.getSize() + "\" />");
                }
            }

            // Close off the response XML data and stream
            out.println("</response>");
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServletException(e);
        }
    }

    @SuppressWarnings("unchecked")
    protected List<FileItem> getFileItems(final HttpServletRequest req) throws FileUploadException {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        return upload.parseRequest(req);
    }
}
