Search in sources :

Example 1 with RequestContext

use of org.apache.commons.fileupload.RequestContext in project acs-community-packaging by Alfresco.

the class UploadFileServlet method service.

/**
 * @see javax.servlet.http.HttpServlet#service(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 */
@SuppressWarnings("unchecked")
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String uploadId = null;
    String returnPage = null;
    final RequestContext requestContext = new ServletRequestContext(request);
    boolean isMultipart = ServletFileUpload.isMultipartContent(requestContext);
    try {
        AuthenticationStatus status = servletAuthenticate(request, response);
        if (status == AuthenticationStatus.Failure) {
            return;
        }
        if (!isMultipart) {
            throw new AlfrescoRuntimeException("This servlet can only be used to handle file upload requests, make" + "sure you have set the enctype attribute on your form to multipart/form-data");
        }
        if (logger.isDebugEnabled())
            logger.debug("Uploading servlet servicing...");
        FacesContext context = FacesContext.getCurrentInstance();
        Map<Object, Object> session = context.getExternalContext().getSessionMap();
        ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
        // ensure that the encoding is handled correctly
        upload.setHeaderEncoding("UTF-8");
        List<FileItem> fileItems = upload.parseRequest(request);
        FileUploadBean bean = new FileUploadBean();
        for (FileItem item : fileItems) {
            if (item.isFormField()) {
                if (item.getFieldName().equalsIgnoreCase("return-page")) {
                    returnPage = item.getString();
                } else if (item.getFieldName().equalsIgnoreCase("upload-id")) {
                    uploadId = item.getString();
                }
            } else {
                String filename = item.getName();
                if (filename != null && filename.length() != 0) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("Processing uploaded file: " + filename);
                    }
                    // ADB-41: Ignore non-existent files i.e. 0 byte streams.
                    if (allowZeroByteFiles() == true || item.getSize() > 0) {
                        // workaround a bug in IE where the full path is returned
                        // IE is only available for Windows so only check for the Windows path separator
                        filename = FilenameUtils.getName(filename);
                        final File tempFile = TempFileProvider.createTempFile("alfresco", ".upload");
                        item.write(tempFile);
                        bean.setFile(tempFile);
                        bean.setFileName(filename);
                        bean.setFilePath(tempFile.getAbsolutePath());
                        if (logger.isDebugEnabled()) {
                            logger.debug("Temp file: " + tempFile.getAbsolutePath() + " size " + tempFile.length() + " bytes created from upload filename: " + filename);
                        }
                    } else {
                        if (logger.isWarnEnabled())
                            logger.warn("Ignored file '" + filename + "' as there was no content, this is either " + "caused by uploading an empty file or a file path that does not exist on the client.");
                    }
                }
            }
        }
        session.put(FileUploadBean.getKey(uploadId), bean);
        if (bean.getFile() == null && uploadId != null && logger.isWarnEnabled()) {
            logger.warn("no file uploaded for upload id: " + uploadId);
        }
        if (returnPage == null || returnPage.length() == 0) {
            throw new AlfrescoRuntimeException("return-page parameter has not been supplied");
        }
        JSONObject json;
        try {
            json = new JSONObject(returnPage);
            if (json.has("id") && json.has("args")) {
                // finally redirect
                if (logger.isDebugEnabled()) {
                    logger.debug("Sending back javascript response " + returnPage);
                }
                response.setContentType(MimetypeMap.MIMETYPE_HTML);
                response.setCharacterEncoding("utf-8");
                // work-around for WebKit protection against embedded javascript on POST body response
                response.setHeader("X-XSS-Protection", "0");
                final PrintWriter out = response.getWriter();
                out.println("<html><body><script type=\"text/javascript\">");
                out.println("window.parent.upload_complete_helper(");
                out.println("'" + json.getString("id") + "'");
                out.println(", ");
                out.println(json.getJSONObject("args"));
                out.println(");");
                out.println("</script></body></html>");
                out.close();
            }
        } catch (JSONException e) {
            // finally redirect
            if (logger.isDebugEnabled())
                logger.debug("redirecting to: " + returnPage);
            response.sendRedirect(returnPage);
        }
        if (logger.isDebugEnabled())
            logger.debug("upload complete");
    } catch (Throwable error) {
        handleUploadException(request, response, error, returnPage);
    }
}
Also used : FacesContext(javax.faces.context.FacesContext) ServletRequestContext(org.apache.commons.fileupload.servlet.ServletRequestContext) JSONException(org.json.JSONException) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) FileItem(org.apache.commons.fileupload.FileItem) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) JSONObject(org.json.JSONObject) FileUploadBean(org.alfresco.web.bean.FileUploadBean) AlfrescoRuntimeException(org.alfresco.error.AlfrescoRuntimeException) JSONObject(org.json.JSONObject) ServletRequestContext(org.apache.commons.fileupload.servlet.ServletRequestContext) RequestContext(org.apache.commons.fileupload.RequestContext) File(java.io.File) PrintWriter(java.io.PrintWriter)

Example 2 with RequestContext

use of org.apache.commons.fileupload.RequestContext in project openmrs-core by openmrs.

the class StartupErrorFilter method doPost.

/**
 * @see org.openmrs.web.filter.StartupFilter#doPost(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse)
 */
@Override
protected void doPost(HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws IOException, ServletException {
    // if they are uploading modules
    if (getModel().errorAtStartup instanceof OpenmrsCoreModuleException) {
        RequestContext requestContext = new ServletRequestContext(httpRequest);
        if (!ServletFileUpload.isMultipartContent(requestContext)) {
            throw new ServletException("The request is not a valid multipart/form-data upload request");
        }
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        try {
            Context.openSession();
            List<FileItem> items = upload.parseRequest(requestContext);
            for (FileItem item : items) {
                InputStream uploadedStream = item.getInputStream();
                ModuleUtil.insertModuleFile(uploadedStream, item.getName());
            }
        } catch (FileUploadException ex) {
            throw new ServletException("Error while uploading file(s)", ex);
        } finally {
            Context.closeSession();
        }
        Map<String, Object> map = new HashMap<>();
        map.put("success", Boolean.TRUE);
        renderTemplate("coremoduleerror.vm", map, httpResponse);
    // TODO restart openmrs here instead of going to coremodulerror template
    }
}
Also used : HashMap(java.util.HashMap) InputStream(java.io.InputStream) ServletRequestContext(org.apache.commons.fileupload.servlet.ServletRequestContext) OpenmrsCoreModuleException(org.openmrs.module.OpenmrsCoreModuleException) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) FileItemFactory(org.apache.commons.fileupload.FileItemFactory) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) ServletException(javax.servlet.ServletException) FileItem(org.apache.commons.fileupload.FileItem) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) ServletRequestContext(org.apache.commons.fileupload.servlet.ServletRequestContext) RequestContext(org.apache.commons.fileupload.RequestContext) FileUploadException(org.apache.commons.fileupload.FileUploadException)

Example 3 with RequestContext

use of org.apache.commons.fileupload.RequestContext in project MassBank-web by MassBank.

the class AdminActions method doUpload.

@Action(name = "doUpload", post = true)
public Redirect doUpload(HttpServletRequest req) throws ServletException {
    RequestContext reqContext = new ServletRequestContext(req);
    boolean isMultipart = ServletFileUpload.isMultipartContent(reqContext);
    if (isMultipart) {
        try {
            // Create a factory for disk-based file items
            FileItemFactory factory = new DiskFileItemFactory();
            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<?> items = upload.parseRequest(req);
            // Process the uploaded items
            Iterator<?> iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                if (!item.isFormField()) {
                    String fileName = item.getName();
                    String fileExtesion = fileName;
                    fileExtesion = fileExtesion.toLowerCase();
                    if (!(fileExtesion.endsWith(".jar") || fileExtesion.endsWith(".aar"))) {
                        return new Redirect(UPLOAD).withStatus(false, "Unsupported file type " + fileExtesion);
                    } else {
                        String fileNameOnly;
                        if (fileName.indexOf("\\") < 0) {
                            fileNameOnly = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length());
                        } else {
                            fileNameOnly = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length());
                        }
                        File uploadedFile = new File(serviceDir, fileNameOnly);
                        item.write(uploadedFile);
                        return new Redirect(UPLOAD).withStatus(true, "File " + fileNameOnly + " successfully uploaded");
                    }
                }
            }
        } catch (Exception e) {
            return new Redirect(UPLOAD).withStatus(false, "The following error occurred: " + e.getMessage());
        }
    }
    throw new ServletException("Invalid request");
}
Also used : ServletRequestContext(org.apache.commons.fileupload.servlet.ServletRequestContext) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) FileItemFactory(org.apache.commons.fileupload.FileItemFactory) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) ServletException(javax.servlet.ServletException) ServletException(javax.servlet.ServletException) FileItem(org.apache.commons.fileupload.FileItem) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) ServletRequestContext(org.apache.commons.fileupload.servlet.ServletRequestContext) RequestContext(org.apache.commons.fileupload.RequestContext) File(java.io.File)

Example 4 with RequestContext

use of org.apache.commons.fileupload.RequestContext in project sling by apache.

the class ParameterSupport method parseMultiPartPost.

private void parseMultiPartPost(ParameterMap parameters) {
    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload();
    upload.setSizeMax(ParameterSupport.maxRequestSize);
    upload.setFileSizeMax(ParameterSupport.maxFileSize);
    upload.setFileItemFactory(new DiskFileItemFactory(ParameterSupport.fileSizeThreshold, ParameterSupport.location));
    RequestContext rc = new ServletRequestContext(this.getServletRequest()) {

        @Override
        public String getCharacterEncoding() {
            String enc = super.getCharacterEncoding();
            return (enc != null) ? enc : Util.ENCODING_DIRECT;
        }
    };
    // Parse the request
    List<?> /* FileItem */
    items = null;
    try {
        items = upload.parseRequest(rc);
    } catch (FileUploadException fue) {
        this.log.error("parseMultiPartPost: Error parsing request", fue);
    }
    if (items != null && items.size() > 0) {
        for (Iterator<?> ii = items.iterator(); ii.hasNext(); ) {
            FileItem fileItem = (FileItem) ii.next();
            RequestParameter pp = new MultipartRequestParameter(fileItem);
            parameters.addParameter(pp, false);
        }
    }
}
Also used : FileItem(org.apache.commons.fileupload.FileItem) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) RequestParameter(org.apache.sling.api.request.RequestParameter) ServletRequestContext(org.apache.commons.fileupload.servlet.ServletRequestContext) ServletRequestContext(org.apache.commons.fileupload.servlet.ServletRequestContext) RequestContext(org.apache.commons.fileupload.RequestContext) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) FileUploadException(org.apache.commons.fileupload.FileUploadException)

Example 5 with RequestContext

use of org.apache.commons.fileupload.RequestContext in project xwiki-platform by xwiki.

the class FileUploadPlugin method loadFileList.

/**
 * Loads the list of uploaded files in the context if there are any uploaded files.
 *
 * @param uploadMaxSize Maximum size of the uploaded files.
 * @param uploadSizeThreashold Threashold over which the file data should be stored on disk, and not in memory.
 * @param tempdir Temporary directory to store the uploaded files that are not kept in memory.
 * @param context Context of the request.
 * @throws XWikiException if the request could not be parsed, or the maximum file size was reached.
 * @see FileUploadPluginApi#loadFileList(long, int, String)
 */
public void loadFileList(long uploadMaxSize, int uploadSizeThreashold, String tempdir, XWikiContext context) throws XWikiException {
    LOGGER.debug("Loading uploaded files");
    // Continuing would empty the list.. We need to stop.
    if (context.get(FILE_LIST_KEY) != null) {
        LOGGER.debug("Called loadFileList twice");
        return;
    }
    // Get the FileUpload Data
    // Make sure the factory only ever creates file items which will be deleted when the jvm is stopped.
    DiskFileItemFactory factory = new DiskFileItemFactory() {

        @Override
        public FileItem createItem(String fieldName, String contentType, boolean isFormField, String fileName) {
            try {
                final DiskFileItem item = (DiskFileItem) super.createItem(fieldName, contentType, isFormField, fileName);
                // Needed to make sure the File object is created.
                item.getOutputStream();
                return item;
            } catch (IOException e) {
                String path = System.getProperty("java.io.tmpdir");
                if (super.getRepository() != null) {
                    path = super.getRepository().getPath();
                }
                throw new RuntimeException("Unable to create a temporary file for saving the attachment. " + "Do you have write access on " + path + "?");
            }
        }
    };
    factory.setSizeThreshold(uploadSizeThreashold);
    if (tempdir != null) {
        File tempdirFile = new File(tempdir);
        if (tempdirFile.mkdirs() && tempdirFile.canWrite()) {
            factory.setRepository(tempdirFile);
        }
    }
    // TODO: Does this work in portlet mode, or we must use PortletFileUpload?
    FileUpload fileupload = new ServletFileUpload(factory);
    RequestContext reqContext = new ServletRequestContext(context.getRequest().getHttpServletRequest());
    fileupload.setSizeMax(uploadMaxSize);
    try {
        @SuppressWarnings("unchecked") List<FileItem> list = fileupload.parseRequest(reqContext);
        if (list.size() > 0) {
            LOGGER.info("Loaded " + list.size() + " uploaded files");
        }
        // We store the file list in the context
        context.put(FILE_LIST_KEY, list);
    } catch (FileUploadBase.SizeLimitExceededException e) {
        throw new XWikiException(XWikiException.MODULE_XWIKI_APP, XWikiException.ERROR_XWIKI_APP_FILE_EXCEPTION_MAXSIZE, "Exception uploaded file");
    } catch (Exception e) {
        throw new XWikiException(XWikiException.MODULE_XWIKI_APP, XWikiException.ERROR_XWIKI_APP_UPLOAD_PARSE_EXCEPTION, "Exception while parsing uploaded file", e);
    }
}
Also used : ServletRequestContext(org.apache.commons.fileupload.servlet.ServletRequestContext) IOException(java.io.IOException) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) XWikiException(com.xpn.xwiki.XWikiException) IOException(java.io.IOException) FileItem(org.apache.commons.fileupload.FileItem) DiskFileItem(org.apache.commons.fileupload.disk.DiskFileItem) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) FileUploadBase(org.apache.commons.fileupload.FileUploadBase) ServletRequestContext(org.apache.commons.fileupload.servlet.ServletRequestContext) RequestContext(org.apache.commons.fileupload.RequestContext) File(java.io.File) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) FileUpload(org.apache.commons.fileupload.FileUpload) XWikiException(com.xpn.xwiki.XWikiException) DiskFileItem(org.apache.commons.fileupload.disk.DiskFileItem)

Aggregations

FileItem (org.apache.commons.fileupload.FileItem)5 RequestContext (org.apache.commons.fileupload.RequestContext)5 DiskFileItemFactory (org.apache.commons.fileupload.disk.DiskFileItemFactory)5 ServletFileUpload (org.apache.commons.fileupload.servlet.ServletFileUpload)5 ServletRequestContext (org.apache.commons.fileupload.servlet.ServletRequestContext)5 File (java.io.File)3 ServletException (javax.servlet.ServletException)2 FileItemFactory (org.apache.commons.fileupload.FileItemFactory)2 FileUploadException (org.apache.commons.fileupload.FileUploadException)2 XWikiException (com.xpn.xwiki.XWikiException)1 IOException (java.io.IOException)1 InputStream (java.io.InputStream)1 PrintWriter (java.io.PrintWriter)1 HashMap (java.util.HashMap)1 FacesContext (javax.faces.context.FacesContext)1 AlfrescoRuntimeException (org.alfresco.error.AlfrescoRuntimeException)1 FileUploadBean (org.alfresco.web.bean.FileUploadBean)1 FileUpload (org.apache.commons.fileupload.FileUpload)1 FileUploadBase (org.apache.commons.fileupload.FileUploadBase)1 DiskFileItem (org.apache.commons.fileupload.disk.DiskFileItem)1