/*
 * See the NOTICE file distributed with this work for additional
 * information regarding copyright ownership.
 *
 * This 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 (at your option) any later version.
 *
 * This software 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 software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 *
 */
package com.xpn.xwiki.web;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.suigeneris.jrcs.rcs.Version;

import com.xpn.xwiki.XWikiContext;
import com.xpn.xwiki.XWikiException;
import com.xpn.xwiki.doc.XWikiAttachment;
import com.xpn.xwiki.doc.XWikiDocument;
import com.xpn.xwiki.plugin.fileupload.FileUploadPlugin;

public class UploadAction extends XWikiAction
{
    private static final Log log = LogFactory.getLog(UploadAction.class);

    public boolean action(XWikiContext context) throws XWikiException
    {
        XWikiResponse response = context.getResponse();
        XWikiDocument doc = context.getDoc();
        String username = context.getUser();
        Object exception = context.get("exception");
        boolean ajax = ((Boolean) context.get("ajax")).booleanValue();
        // check Exception File upload is large
        if (exception != null) {
            if (exception instanceof XWikiException) {
                XWikiException exp = (XWikiException) exception;
                if (exp.getCode() == XWikiException.ERROR_XWIKI_APP_FILE_EXCEPTION_MAXSIZE) {
                    response.setStatus(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE);
                    context.put("message", "fileuploadislarge");
                    return true;
                }
            }
        }
        FileUploadPlugin fileupload = (FileUploadPlugin) context.get("fileuploadplugin");
        String filename;
        try {
            filename = fileupload.getFileItemAsString("filename", context);
        } catch (Exception ex) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            context.put("message", "tempdirnotset");
            return true;
        }

        if (filename != null) {
            if (filename.indexOf("/") != -1 || filename.indexOf("\\") != -1
                || filename.indexOf(";") != -1) {
                response.setStatus(HttpServletResponse.SC_FORBIDDEN);
                context.put("message", "notsupportcharacters");
                return true;
            }
        }

        byte[] data = fileupload.getFileItemData("filepath", context);
        if (filename == null || filename.trim().equals("")) {
            String fname = fileupload.getFileName("filepath", context);
            int i = fname.lastIndexOf("\\");
            if (i == -1)
                i = fname.lastIndexOf("/");
            filename = fname.substring(i + 1);
        }
        filename = filename.replaceAll("\\+", " ");

        XWikiDocument olddoc = (XWikiDocument) doc.clone();
        // Read XWikiAttachment
        XWikiAttachment attachment = olddoc.getAttachment(filename);

        if (attachment == null) {
            attachment = new XWikiAttachment();
            olddoc.getAttachmentList().add(attachment);
        }
        attachment.setContent(data);
        attachment.setFilename(filename);
        // TODO: handle Author
        attachment.setAuthor(username);

        // Add the attachment to the document
        attachment.setDoc(olddoc);

        olddoc.setAuthor(username);
        if (olddoc.isNew()) {
            olddoc.setCreator(username);
        }

        // Adding a comment with a link to the download URL
        String comment;
        String nextRev = attachment.getNextVersion();
        ArrayList params = new ArrayList();
        params.add(filename);
        params.add(olddoc.getAttachmentRevisionURL(filename, nextRev, context));
        if (attachment.isImage(context))
            comment = context.getMessageTool().get("core.comment.uploadImageComment", params);
        else
            comment = context.getMessageTool().get("core.comment.uploadAttachmentComment", params);
        olddoc.setComment(comment);

        // Save the content and the archive
        try {
            olddoc.saveAttachmentContent(attachment, context);
        } catch (XWikiException e) {
            // check Exception is ERROR_XWIKI_APP_JAVA_HEAP_SPACE when saving Attachment
            if (e.getCode() == XWikiException.ERROR_XWIKI_APP_JAVA_HEAP_SPACE) {
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                context.put("message", "javaheapspace");
                return true;
            }
            throw e;
        }

        if (ajax) {
            try {
                response.getOutputStream().println("ok");
            } catch (IOException ex) {
                log.error("Unhandled exception writing output:", ex);
            }
            return false;
        }
        // forward to attach page
        String redirect = fileupload.getFileItemAsString("xredirect", context);
        if ((redirect == null) || (redirect.equals("")))
            redirect = context.getDoc().getURL("attach", true, context);
        sendRedirect(response, redirect);
        return false;
    }

    public String render(XWikiContext context) throws XWikiException
    {
        boolean ajax = ((Boolean) context.get("ajax")).booleanValue();
        if (ajax) {
            try {
                context.getResponse().getOutputStream().println("error: " + context.getMessageTool().get((String)context.get("message")));
            } catch (IOException ex) {
                log.error("Unhandled exception writing output:", ex);
            }
            return null;
        }
        return "exception";

    }
}

@@ -1111,48 +1111,8 @@
 ory;
-%0Aimport org.suigeneris.jrcs.rcs.Version;
 %0A%0Aim
@@ -4489,17 +4489,19 @@
 ontext))
+ %7B
 %0A
-
         
@@ -4598,13 +4598,17 @@
     
+ %7D
  else
+ %7B
 %0A   
@@ -4617,32 +4617,48 @@
        comment =
+%0A               
  context.getMess
@@ -4712,32 +4712,42 @@
 ment%22, params);%0A
+        %7D%0A
         olddoc.s
@@ -5734,16 +5734,18 @@
 ls(%22%22)))
+ %7B
 %0A       
@@ -5802,32 +5802,42 @@
 true, context);%0A
+        %7D%0A
         sendRedi
@@ -6139,16 +6139,37 @@
 println(
+%0A                    
 %22error: 
@@ -6209,16 +6209,17 @@
 (String)
+ 
 context.

Apply codestyle