package org.appfuse.webapp.action;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;
import org.appfuse.webapp.form.UploadForm;
public class UploadAction extends Action {
    public ActionForward execute(ActionMapping mapping, ActionForm form,
                                 HttpServletRequest request,
                                 HttpServletResponse response)
      throws Exception {
                if (isCancelled(request)) {
                        request.removeAttribute(mapping.getAttribute());
                        return (mapping.findForward("mainMenu"));
        }
                        String encoding = request.getCharacterEncoding();
        if ((encoding != null) && (encoding.equalsIgnoreCase("utf-8"))) {
            response.setContentType("text/html; charset=utf-8");
        }
        UploadForm theForm = (UploadForm) form;
                String name = theForm.getName();
                FormFile file = theForm.getTheFile();
                String fileName = file.getFileName();
                String contentType = file.getContentType();
                String size = (file.getFileSize() + " bytes");
        String data = null;
        String location = null;
                String uploadDir =
            servlet.getServletContext().getRealPath("/resources") + "/"
            + request.getRemoteUser() + "/";
                File dirPath = new File(uploadDir);
        if (!dirPath.exists()) {
            dirPath.mkdirs();
        }
                InputStream stream = file.getInputStream();
                OutputStream bos = new FileOutputStream(uploadDir + fileName);
        int bytesRead = 0;
        byte[] buffer = new byte[8192];
        while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) {
            bos.write(buffer, 0, bytesRead);
        }
        bos.close();
        location =
            "The file has been written to \"" + dirPath.getAbsolutePath()
            + file.getFileName() + "\"";
                stream.close();
                request.setAttribute("name", name);
        request.setAttribute("fileName", fileName);
        request.setAttribute("contentType", contentType);
        request.setAttribute("size", size);
        request.setAttribute("data", data);
        request.setAttribute("location", location);
                file.destroy();
                return mapping.findForward("success");
    }
}