Example usage for org.apache.commons.fileupload.disk DiskFileItemFactory setSizeThreshold

List of usage examples for org.apache.commons.fileupload.disk DiskFileItemFactory setSizeThreshold

Introduction

In this page you can find the example usage for org.apache.commons.fileupload.disk DiskFileItemFactory setSizeThreshold.

Prototype

public void setSizeThreshold(int sizeThreshold) 

Source Link

Document

Sets the size threshold beyond which files are written directly to disk.

Usage

From source file:org.more.webui.components.upload.Upload.java

public void onEvent(Event event, UIComponent component, ViewContext viewContext) throws Throwable {
    Upload swfUpload = (Upload) component;
    HttpServletRequest httpRequest = viewContext.getHttpRequest();
    ServletContext servletContext = httpRequest.getSession(true).getServletContext();
    if (ServletFileUpload.isMultipartContent(httpRequest) == false)
        return;// ??multipart??
    try {/*from  www.  jav a  2  s  .co  m*/
        //1.
        DiskFileItemFactory factory = new DiskFileItemFactory();// DiskFileItemFactory??????List
        ServletFileUpload upload = new ServletFileUpload(factory);
        String charset = httpRequest.getCharacterEncoding();
        if (charset != null)
            upload.setHeaderEncoding(charset);
        factory.setSizeThreshold(swfUpload.getUploadSizeThreshold());
        File uploadTempDir = new File(servletContext.getRealPath(swfUpload.getUploadTempDir()));
        if (uploadTempDir.exists() == false)
            uploadTempDir.mkdirs();
        factory.setRepository(uploadTempDir);
        //2.?
        List<FileItem> itemList = upload.parseRequest(httpRequest);
        List<FileItem> finalList = new ArrayList<FileItem>();
        Map<String, String> finalParam = new HashMap<String, String>();
        for (FileItem item : itemList)
            if (item.isFormField() == false)
                finalList.add(item);
            else
                finalParam.put(new String(item.getFieldName().getBytes("iso-8859-1")),
                        new String(item.getString().getBytes("iso-8859-1")));
        //3.
        Object returnData = null;
        MethodExpression onBizActionExp = swfUpload.getOnBizActionExpression();
        if (onBizActionExp != null) {
            HashMap<String, Object> upObject = new HashMap<String, Object>();
            upObject.put("files", finalList);
            upObject.put("params", finalParam);
            HashMap<String, Object> upParam = new HashMap<String, Object>();
            upParam.put("up", upObject);
            returnData = onBizActionExp.execute(component, viewContext, upParam);
        }
        //4.??
        for (FileItem item : itemList)
            try {
                item.delete();
            } catch (Exception e) {
            }
        //5.
        viewContext.sendObject(returnData);
    } catch (Exception e) {
        viewContext.sendError(e);
    }
}

From source file:org.ms123.common.rpc.JsonRpcServlet.java

protected String getRequestString(final HttpServletRequest request) throws Exception {
    String requestString = null;//from ww w. ja  va  2 s . c  om
    InputStream is = null;
    Reader reader = null;
    boolean rpcForm = false;
    if (request.getPathInfo().indexOf("__rpcForm__") != -1) {
        rpcForm = true;
    } else if (request.getPathInfo().indexOf("/get") != -1) {
        rpcForm = true;
    }
    final String contentType = request.getHeader(CONTENT_TYPE);
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    debug("getRequestString:isMultipart:" + isMultipart + "/rpcForm:" + rpcForm);
    if (isMultipart) {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(0);
        ServletFileUpload upload = new ServletFileUpload(factory);
        List<FileItem> items = upload.parseRequest(request);
        if (items.size() < 1) {
            throw new RuntimeException("insert:No Uploadfile");
        }
        Map dataMap = new HashMap();
        for (FileItem fi : items) {
            if (fi.isFormField()) {
                String fieldname = fi.getFieldName();
                String fieldvalue = fi.getString();
                debug("ItemValue:" + fieldname + "=" + fieldvalue);
                dataMap.put(fieldname, fieldvalue);
            } else {
                debug("FileItem:" + fi.getFieldName());
                dataMap.put(fi.getFieldName(), unpackFileItem((DiskFileItem) fi));
            }
        }
        debug("dataMap:" + dataMap);
        requestString = (String) dataMap.get("__rpc__");
        if (requestString == null) {
            requestString = (String) dataMap.get("rpc");
        }
        debug("rpcParams:" + requestString);
        dataMap.remove("__rpc__");
        dataMap.remove("rpc");
        dataMap.remove("__hints__");
        Map p = (Map) m_ds.deserialize(requestString);
        Map params = (Map) p.get("params");
        params.put("fileMap", dataMap);
        params.put("docid", dataMap.get("docid"));
        flexjson.JSONSerializer js = new flexjson.JSONSerializer();
        requestString = js.deepSerialize(p);
    } else if (rpcForm) {
        requestString = request.getParameter("__rpc__");
        if (requestString == null) {
            requestString = request.getParameter("rpc");
        }
    } else {
        try {
            is = request.getInputStream();
            reader = new InputStreamReader(is, UTF_8);
            final StringBuilder sb = new StringBuilder(READ_BUFFER_SIZE);
            char[] readBuffer = new char[READ_BUFFER_SIZE];
            int length;
            while ((length = reader.read(readBuffer)) != -1) {
                sb.append(readBuffer, 0, length);
            }
            requestString = sb.toString();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                }
            }
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                }
            }
        }
    }
    return requestString;
}

From source file:org.my.eaptest.UploadServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    resp.setContentType("text/html;charset=UTF-8");
    ServletOutputStream out = resp.getOutputStream();

    // Check that we have a file upload request.
    if (!ServletFileUpload.isMultipartContent(req)) {
        out.println(// w  ww .ja v  a 2 s .  c om
                "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">");
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet upload</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<p>No file uploaded!</p>");
        out.println("</body>");
        out.println("</html>");

        return;
    }

    // Create a factory for disk-based file items.
    DiskFileItemFactory factory = new DiskFileItemFactory();
    // Configure a repository (to ensure a secure temp location is used).
    ServletContext servletContext = this.getServletConfig().getServletContext();
    File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
    factory.setRepository(repository);
    // Maximum size that will be stored in memory.
    factory.setSizeThreshold(MAX_FILE_SIZE);
    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);

    // Parse the request to get file items.
    try {
        List<FileItem> items = upload.parseRequest(req);

        out.println(
                "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">");
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet upload</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<div style=\"text-align: left;\">");
        // we look for a filename item and/or file item with file content
        Iterator<FileItem> iter = items.iterator();
        String filename = null;
        String contents = null;
        boolean delete = false;
        while (iter.hasNext()) {
            FileItem item = iter.next();
            boolean isFormField = item.isFormField();
            String fieldName = item.getFieldName();
            if (isFormField && fieldName.equals("filename")) {
                String name = item.getString();
                if (name.length() > 0 || filename == null) {
                    filename = name;
                }
            } else if (isFormField && fieldName.equals("readonly")) {
                // means no filename or file provided
            } else if (isFormField && fieldName.equals("delete")) {
                // delete one or all fiels depending on whether filename is provided
                delete = true;
            } else if (!isFormField && fieldName.equals("file")) {
                contents = fromStream(item.getInputStream());
                contents = StringEscapeUtils.escapeHtml(contents);
                if (filename == null || filename.length() == 0) {
                    filename = item.getName();
                }
            } else {
                if (isFormField) {
                    out.print("<p><pre>Unexpected field name : ");
                    out.print(fieldName);
                    out.println("</pre>");
                } else {
                    String name = item.getName();
                    out.print("<p><pre>Unexpected file item : ");
                    out.print(name);
                    out.print(" for field ");
                    out.print(fieldName);
                    out.println("</pre>");
                }
                out.println("</body>");
                out.println("</html>");
                return;
            }
        }

        // if we don't have a filename then either list or delete all files in the hashtable

        if (filename == null) {
            if (delete) {
                filedata.clear();
                out.println("All files deleted!<br/>");
            } else {
                Set<String> keys = filedata.keySet();
                out.println("All files:<br/>");
                out.println("<pre>");
                if (keys.isEmpty()) {
                    out.println("No files found!");
                } else {
                    for (String key : keys) {
                        out.print(key);
                        FileSet set = filedata.get(key);
                        if (set != null) {
                            out.print(" ");
                            out.println(set.size());
                        } else {
                            out.println(" 0");
                        }
                    }
                }
                out.println("</pre>");
            }
            out.println("</body>");
            out.println("</html>");
            return;
        }
        // if we have a filename and no contents then we
        // retrieve the file contents from the hashmap
        // and maybe delete the file
        // if we have a filename and contents then we update
        // the hashmap -- delete should not be supplied in
        // this case

        boolean noUpdate = (contents == null);
        if (noUpdate) {
            if (delete) {
                FileSet set = filedata.remove(filename);
                contents = (set != null ? set.get() : null);
            } else {
                FileSet set = filedata.get(filename);
                contents = (set != null ? set.get() : null);
            }
        } else {
            FileSet set = new FileSet();
            FileSet old = filedata.putIfAbsent(filename, set);
            if (old != null) {
                set = old;
            }
            set.add(contents);
        }

        // now hand the contents back
        out.print("<pre>File: ");
        out.print(filename);
        boolean printContents = true;
        if (noUpdate) {
            if (contents == null) {
                out.println(" not found");
                printContents = false;
            } else if (delete) {
                out.print(" deleted");
            }
        } else {
            if (contents == null) {
                out.print(" added");
            } else {
                out.print(" updated");
            }
        }
        out.println("</pre><br/>");
        if (printContents) {
            out.println("<pre>");
            out.println(contents);
            out.println("</pre>");
        }
        out.println("</body>");
        out.println("</html>");
    } catch (FileUploadException fuEx) {
        log.error("Problem with process file upload:", fuEx);
    }
}

From source file:org.n52.geoar.codebase.resources.InfoResource.java

private Representation handleUpload() throws FileUploadException, Exception {
    // 1/ Create a factory for disk-based file items
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(1000240);

    // 2/ Create a new file upload handler based on the Restlet FileUpload
    // extension that will
    // parse Restlet requests and generates FileItems.
    RestletFileUpload upload = new RestletFileUpload(factory);

    // 3/ Request is parsed by the handler which generates a list of
    // FileItems//ww  w . j  a  v  a2  s .c o m
    List<FileItem> items = upload.parseRequest(getRequest());

    // Process the uploaded item and the associated fields, then save file
    // on disk

    // get the form inputs
    FileItem dsFileItem = null;

    for (FileItem fi : items) {
        if (fi.getFieldName().equals(FORM_INPUT_FILE)) {
            dsFileItem = fi;
            break;
        }
    }

    if (dsFileItem.getName().isEmpty()) {
        return new StringRepresentation("Missing file!", MediaType.TEXT_PLAIN);
    }
    if (!FilenameUtils.getExtension(dsFileItem.getName()).equals(CodebaseProperties.APK_FILE_EXTENSION)) {
        return new StringRepresentation("Wrong filename extension", MediaType.TEXT_PLAIN);
    }

    PluginDescriptor pluginDescriptor = readPluginDescriptorFromPluginInputStream(dsFileItem.getInputStream());
    if (pluginDescriptor == null) {
        return new StringRepresentation(
                "The uploaded plugin has no descriptor (" + GEOAR_PLUGIN_XML_NAME + ")!", MediaType.TEXT_PLAIN);
    }
    if (pluginDescriptor.identifier == null) {
        return new StringRepresentation("The uploaded plugin has no identifier!", MediaType.TEXT_PLAIN);
    }

    log.debug("Plugin: {}, {}, {}, {}, {}", new Object[] { pluginDescriptor.identifier, pluginDescriptor.name,
            pluginDescriptor.description, pluginDescriptor.publisher, pluginDescriptor.version });

    // see if it already exists
    CodebaseDatabase db = CodebaseDatabase.getInstance();
    boolean databaseEntryExists = db.containsResource(pluginDescriptor.identifier);

    File pluginFile = new File(CodebaseProperties.getInstance().getApkPath(pluginDescriptor.identifier));
    File imageFile = new File(CodebaseProperties.getInstance().getImagePath(pluginDescriptor.identifier));
    if (pluginFile.exists()) {
        log.warn("Deleting apk file " + pluginFile.getName());
        if (!pluginFile.delete()) {
            log.error("Could not delete file " + pluginFile.getPath());
        }
    }
    if (imageFile.exists()) {
        log.warn("Deleting image file " + imageFile.getName());
        if (!imageFile.delete()) {
            log.error("Could not delete file " + imageFile.getPath());
        }
    }
    // write the file!
    dsFileItem.write(pluginFile);
    extractPluginImage(pluginFile, imageFile);

    if (databaseEntryExists) {
        db.updateResource(pluginDescriptor.identifier, pluginDescriptor.name, pluginDescriptor.description,
                pluginDescriptor.publisher, pluginDescriptor.version);
        return new StringRepresentation("Updated datasource (" + pluginDescriptor.identifier + ").",
                MediaType.TEXT_PLAIN);
    } else {
        db.addResource(pluginDescriptor.identifier, pluginDescriptor.name, pluginDescriptor.description,
                pluginDescriptor.publisher, pluginDescriptor.version);
        return new StringRepresentation("Uploaded datasource (" + pluginDescriptor.identifier + ").",
                MediaType.TEXT_PLAIN);
    }
}

From source file:org.nordapp.web.servlet.DEVServlet.java

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    try {/*from  ww w.j  a va 2  s  . c  om*/

        //@SuppressWarnings("unused")
        final String mandatorId = RequestPath.getMandator(req);
        final String uuid = RequestPath.getSession(req);

        //
        // Session handler (HTTP) and session control (OSGi)
        //
        //SessionControl ctrl = new HttpSessionControlImpl(context, req.getSession());
        SessionControl ctrl = new SessionControlImpl(context);
        ctrl.setMandatorID(mandatorId);
        ctrl.setCertID(uuid);

        //RequestHandler rqHdl = new RequestHandler(context, ctrl);

        ctrl.loadTempSession();
        ctrl.getAll();
        ctrl.incRequestCounter();
        ctrl.setAll();
        ctrl.saveTempSession();

        //
        // Session and other services
        //
        String cert = null;

        //The '0' session of the mandator
        Session mSession = SessionServiceImpl.getSession(context, cert, ctrl.getMandatorID(), "0");

        //The 'user' session
        mSession = SessionServiceImpl.getSession(context, cert, ctrl.getMandatorID(),
                ctrl.decodeCert().toString());
        if (mSession == null) {
            List<String> list = ctrl.getShortTimePassword();
            if (ctrl.getCertID() == null || (!list.contains(ctrl.getCertID())))
                throw new UnavailableException("Needs a valid User-Session.");
        }

        //The mandator
        Mandator mandator = MandatorServiceImpl.getMandator(context, ctrl.getMandatorID());
        if (mandator == null) {
            throw new UnavailableException("Needs a valid mandator id:" + ctrl.getMandatorID() + ".");
        }

        //
        // Get some data
        //

        FilePath tmpLoc = FilePath.get(mandator.getPath()).add("temp");

        //
        // prepare the engine
        //

        String[] elem = RequestPath.getPath(req);
        if (elem.length != 0)
            throw new MalformedURLException("The URL needs the form '" + req.getServletPath() + "' but was '"
                    + req.getRequestURI() + "'");

        //
        // Initialize the work
        //

        ServiceReference<DeployService> srDeploy = context.getServiceReference(DeployService.class);
        if (srDeploy == null)
            throw new IOException(
                    "The deploy service reference is not available (maybe down or a version conflict).");
        DeployService svDeploy = context.getService(srDeploy);
        if (svDeploy == null)
            throw new IOException("The deploy service is not available (maybe down or a version conflict).");

        String processID = IdGen.getURLSafeString(IdGen.getUUID());
        String mandatorID = ctrl.getMandatorID();
        String groupID = ctrl.getGroupID();
        String artifactID = ctrl.getArtifactID();

        //
        // Process upload
        //

        // Create a factory for disk-based file items
        DiskFileItemFactory factory = new DiskFileItemFactory();

        // sets memory threshold - beyond which files are stored in disk
        factory.setSizeThreshold(MEMORY_THRESHOLD);

        File repository = tmpLoc.add("http-upload").toFile();
        if (!repository.exists()) {
            repository.mkdirs();
        }
        factory.setRepository(repository);

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);

        // sets maximum size of upload file
        upload.setFileSizeMax(MAX_FILE_SIZE);

        // sets maximum size of request (include file + form data)
        upload.setSizeMax(MAX_REQUEST_SIZE);

        try {
            // parses the request's content to extract file data
            //@SuppressWarnings("unchecked")
            List<FileItem> formItems = upload.parseRequest(req);

            if (formItems != null && formItems.size() > 0) {
                // iterates over form's fields
                for (FileItem item : formItems) {
                    // processes only fields that are not form fields
                    if (item.isFormField()) {
                        //data
                    } else {
                        File zip = svDeploy.createEmptyZip(processID, mandatorID, groupID, artifactID);
                        OutputStream os = new FileOutputStream(zip);
                        InputStream is = item.getInputStream();
                        try {
                            IOUtils.copy(is, os);
                        } finally {
                            IOUtils.closeQuietly(is);
                            IOUtils.closeQuietly(os);
                        }
                        svDeploy.zipToData(processID, mandatorID, groupID, artifactID, zip.getName());
                    } //fi
                } //for
            } //fi
        } catch (Exception ex) {
            req.setAttribute("message", "There was an error: " + ex.getMessage());
        }

        //
        // Prints the result from the user-session
        //
        StringBuffer buffer = new StringBuffer();
        ResponseHandler rsHdl = new ResponseHandler(context, ctrl);

        logger.debug("The user session is{}found mandatorId:{}, sessionId:{}.",
                (mSession == null ? " not " : " "), ctrl.getMandatorID(), ctrl.getCertID());
        rsHdl.getSessionData(buffer, mSession);

        //
        //
        //
        byte[] bytes = buffer.toString().getBytes();

        //
        // Send the resource
        //
        rsHdl.avoidCaching(resp);
        rsHdl.sendData(bytes, resp);

    } catch (Exception e) {
        ResponseHandler rsHdl = new ResponseHandler(context, null);
        rsHdl.sendError(logger, e, resp, null);
    }
}

From source file:org.nordapp.web.servlet.IOServlet.java

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    try {/*from ww w. j a  v a 2s .  com*/

        //@SuppressWarnings("unused")
        final String mandatorId = RequestPath.getMandator(req);
        final String uuid = RequestPath.getSession(req);

        //
        // Session handler (HTTP) and session control (OSGi)
        //
        //SessionControl ctrl = new HttpSessionControlImpl(context, req.getSession());
        SessionControl ctrl = new SessionControlImpl(context);
        ctrl.setMandatorID(mandatorId);
        ctrl.setCertID(uuid);

        //RequestHandler rqHdl = new RequestHandler(context, ctrl);

        ctrl.loadTempSession();
        ctrl.getAll();
        ctrl.incRequestCounter();

        //
        // Session and other services
        //
        String cert = null;

        //The '0' session of the mandator
        Session mSession = SessionServiceImpl.getSession(context, cert, ctrl.getMandatorID(), "0");
        Integer baseIndex = ((Integer) mSession.getValue(Session.ENGINE_BASE_INDEX)).intValue();

        //The 'user' session
        mSession = SessionServiceImpl.getSession(context, cert, ctrl.getMandatorID(),
                ctrl.decodeCert().toString());
        if (mSession == null) {
            List<String> list = ctrl.getShortTimePassword();
            if (ctrl.getCertID() == null || (!list.contains(ctrl.getCertID())))
                throw new UnavailableException("Needs a valid User-Session.");
        }

        //The mandator
        Mandator mandator = MandatorServiceImpl.getMandator(context, ctrl.getMandatorID());
        if (mandator == null) {
            throw new UnavailableException("Needs a valid mandator id:" + ctrl.getMandatorID() + ".");
        }

        EngineBaseService engineBaseService = null;
        try {
            engineBaseService = EngineBaseServiceImpl.getService(context, ctrl.getMandatorID(),
                    String.valueOf(baseIndex));
        } catch (InvalidSyntaxException e1) {
        }
        if (engineBaseService == null)
            throw new IOException(
                    "The mandator base service is not available (maybe down or a version conflict).");

        //
        // Get some data
        //

        FilePath tmpLoc = FilePath.get(mandator.getPath()).add("temp");

        //
        // prepare the engine
        //

        String[] elem = RequestPath.getPath(req);
        if (elem.length == 0)
            throw new MalformedURLException("The URL needs the form '" + req.getServletPath()
                    + "/function-id' but was '" + req.getRequestURI() + "'");

        BigInteger engineId = ctrl.decodeCert();
        String functionId = elem.length >= 1 ? elem[0] : null;

        Engine engine = null;
        try {
            engine = engineBaseService.getEngine(engineId);
        } catch (Exception e1) {
            throw new ServletException(e1);
        }
        if (!engine.isLogin())
            throw new ServletException("There is no login to this session.");

        //
        // Initialize the work
        //

        engine.setLocalValue(httpSessionID, engineId.toString()); //ctrl.decodeCert().toString()

        IdRep processUUID = IdGen.getUUID();
        engine.setLocalValue(httpProcessID, processUUID);

        IOContainer ioc = new IOContainer();
        ioc.setProcessUUID(processUUID.toString());
        engine.setLocalValue(httpIOContainer, ioc);

        //
        // Process upload
        //

        // Create a factory for disk-based file items
        DiskFileItemFactory factory = new DiskFileItemFactory();

        // sets memory threshold - beyond which files are stored in disk
        factory.setSizeThreshold(MEMORY_THRESHOLD);

        File repository = tmpLoc.add("http-upload").toFile();
        if (!repository.exists()) {
            repository.mkdirs();
        }
        factory.setRepository(repository);

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);

        // sets maximum size of upload file
        upload.setFileSizeMax(MAX_FILE_SIZE);

        // sets maximum size of request (include file + form data)
        upload.setSizeMax(MAX_REQUEST_SIZE);

        try {
            // parses the request's content to extract file data
            //@SuppressWarnings("unchecked")
            List<FileItem> formItems = upload.parseRequest(req);

            if (formItems != null && formItems.size() > 0) {
                // iterates over form's fields
                for (FileItem item : formItems) {
                    // processes only fields that are not form fields
                    if (item.isFormField()) {
                        //data
                        ioc.setField(item.getFieldName(), item);
                    } else {
                        ioc.setFile(IdGen.getUUID().toString(), item);
                    } //fi
                } //for
            } //fi
        } catch (Exception ex) {
            req.setAttribute("message", "There was an error: " + ex.getMessage());
        }

        //
        // Call script
        //

        try {
            engine.call(functionId);
        } catch (Exception e) {
            e.printStackTrace();
        }

        ioc.cleanup();
        engine.setLocalValue(httpSessionID, null);
        engine.setLocalValue(httpProcessID, null);
        engine.setLocalValue(httpIOContainer, null);

        //
        // Prints the result from the user-session
        //
        StringBuffer buffer = new StringBuffer();
        ResponseHandler rsHdl = new ResponseHandler(context, ctrl);

        logger.debug("The user session is{}found mandatorId:{}, sessionId:{}.",
                (mSession == null ? " not " : " "), ctrl.getMandatorID(), ctrl.getCertID());
        rsHdl.getSessionData(buffer, mSession);

        //
        //
        //
        byte[] bytes = buffer.toString().getBytes();

        //
        // Send the resource
        //
        rsHdl.avoidCaching(resp);
        rsHdl.sendData(bytes, resp);

    } catch (Exception e) {
        ResponseHandler rsHdl = new ResponseHandler(context, null);
        rsHdl.sendError(logger, e, resp, null);
    }
}

From source file:org.nordapp.web.servlet.SessionCallServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    try {/*from  w w  w  .  j  av a  2  s.c  o m*/

        //@SuppressWarnings("unused")
        final String mandatorId = RequestPath.getMandator(req);
        final String uuid = RequestPath.getSession(req);

        //
        // Session handler
        //
        //SessionControl ctrl = new HttpSessionControlImpl(context, req.getSession());
        SessionControl ctrl = new SessionControlImpl(context);
        ctrl.setMandatorID(mandatorId);
        ctrl.setCertID(uuid);

        ctrl.loadTempSession();
        ctrl.getAll();
        ctrl.incRequestCounter();
        ctrl.setAll();
        ctrl.saveTempSession();

        //
        // Process upload
        //

        // Create a factory for disk-based file items
        DiskFileItemFactory factory = new DiskFileItemFactory();

        // sets memory threshold - beyond which files are stored in disk
        factory.setSizeThreshold(MEMORY_THRESHOLD);

        //The mandator
        Mandator mandator = MandatorServiceImpl.getMandator(context, ctrl.getMandatorID());
        if (mandator == null) {
            throw new UnavailableException("Needs a valid mandator id:" + ctrl.getMandatorID() + ".");
        }

        FilePath tmpLoc = FilePath.get(mandator.getPath()).add("temp");

        File repository = tmpLoc.add("http-upload").toFile();
        if (!repository.exists()) {
            repository.mkdirs();
        }
        factory.setRepository(repository);

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);

        // sets maximum size of upload file
        upload.setFileSizeMax(MAX_FILE_SIZE);

        // sets maximum size of request (include file + form data)
        upload.setSizeMax(MAX_REQUEST_SIZE);

        // Gets the JSON data
        GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.registerTypeAdapter(LinkedHashMap.class, new GsonHashMapDeserializer());
        Gson gson = gsonBuilder.create();

        Map<String, Object> res = new HashMap<String, Object>();
        try {
            // parses the request's content to extract file data
            //@SuppressWarnings("unchecked")
            List<FileItem> formItems = upload.parseRequest(req);

            if (formItems != null && formItems.size() > 0) {
                // iterates over form's fields
                for (FileItem item : formItems) {
                    // processes only fields that are not form fields
                    if (item.isFormField()) {
                        //data
                        res.put(item.getFieldName(), item.getString());
                        //ioc.setField(item.getFieldName(), item);
                    } else {
                        //Gets JSON as Stream
                        Reader json = new InputStreamReader(item.getInputStream());
                        //String json = item.getString();

                        try {
                            @SuppressWarnings("unchecked")
                            LinkedHashMap<String, Object> mapJ = gson.fromJson(json, LinkedHashMap.class);
                            for (String key : mapJ.keySet()) {
                                Object val = mapJ.get(key);
                                if (val == null)
                                    continue;

                                res.put(key, val);
                            } //for
                        } finally {
                            json.close();
                        }
                    } //fi
                } //for

            } //fi
        } catch (Exception ex) {
            req.setAttribute("message", "There was an error: " + ex.getMessage());
        }

        process(ctrl, req, resp, res);

    } catch (Exception e) {
        ResponseHandler rsHdl = new ResponseHandler(context, null);
        rsHdl.sendError(logger, e, resp, null);
    }
}

From source file:org.onesocialweb.openfire.web.FileServlet.java

private void processPost(HttpServletRequest request, HttpServletResponse response) throws Exception {
    final PrintWriter out = response.getWriter();

    // 1- Bind this request to a XMPP JID
    final JID user = getAuthenticatedUser(request);
    if (user == null) {
        throw new AuthenticationException();
    }//  ww  w.ja  v a2  s .c o m

    // 2- Process the file
    final UploadManager uploadManager = UploadManager.getInstance();

    // Files larger than a threshold should be stored on disk in temporary
    // storage place
    final DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(256000);
    factory.setRepository(getTempFolder());

    // Prepare the upload parser and set a max size to enforce
    final ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setSizeMax(512000000);

    // Get the request ID
    final String requestId = request.getParameter("requestId");

    // Create a progress listener
    ProgressListener progressListener = new ProgressListener() {
        private long lastNotification = 0;

        public void update(long pBytesRead, long pContentLength, int pItems) {
            if (lastNotification == 0 || (pBytesRead - lastNotification) > NOTIFICATION_THRESHOLD) {
                lastNotification = pBytesRead;
                UploadManager.getInstance().updateProgress(user, pBytesRead, pContentLength, requestId);
            }
        }
    };
    upload.setProgressListener(progressListener);

    // Process the upload
    List items = upload.parseRequest(request);
    for (Object objItem : items) {
        FileItem item = (FileItem) objItem;
        if (!item.isFormField()) {
            String fileID = UUID.randomUUID().toString();
            File target = new File(getUploadFolder(), fileID);
            item.write(target);
            UploadManager.getInstance().commitFile(user, target, item.getName(), requestId);
            break; // Store only one file
        }
    }
}

From source file:org.opencms.ade.upload.CmsUploadBean.java

/**
 * Parses a request of the form <code>multipart/form-data</code>.<p>
 * // w  ww  . j av a  2s  . c o  m
 * The result list will contain items of type <code>{@link FileItem}</code>.
 * If the request has no file items, then <code>null</code> is returned.<p>
 * 
 * @param listener the upload listener
 * 
 * @return the list of <code>{@link FileItem}</code> extracted from the multipart request,
 *      or <code>null</code> if the request has no file items
 *      
 * @throws Exception if anything goes wrong
 */
private List<FileItem> readMultipartFileItems(CmsUploadListener listener) throws Exception {

    DiskFileItemFactory factory = new DiskFileItemFactory();
    // maximum size that will be stored in memory
    factory.setSizeThreshold(4096);
    // the location for saving data that is larger than the threshold
    factory.setRepository(new File(OpenCms.getSystemInfo().getPackagesRfsPath()));

    // create a file upload servlet
    ServletFileUpload fu = new ServletFileUpload(factory);
    // set the listener
    fu.setProgressListener(listener);
    // set encoding to correctly handle special chars (e.g. in filenames)
    fu.setHeaderEncoding(getRequest().getCharacterEncoding());
    // set the maximum size for a single file (value is in bytes)
    long maxFileSizeBytes = OpenCms.getWorkplaceManager().getFileBytesMaxUploadSize(getCmsObject());
    if (maxFileSizeBytes > 0) {
        fu.setFileSizeMax(maxFileSizeBytes);
    }

    // try to parse the request
    try {
        return CmsCollectionsGenericWrapper.list(fu.parseRequest(getRequest()));
    } catch (SizeLimitExceededException e) {
        // request size is larger than maximum allowed request size, throw an error
        Integer actualSize = new Integer((int) (e.getActualSize() / 1024));
        Integer maxSize = new Integer((int) (e.getPermittedSize() / 1024));
        throw new CmsUploadException(m_bundle
                .key(org.opencms.ade.upload.Messages.ERR_UPLOAD_REQUEST_SIZE_LIMIT_2, actualSize, maxSize), e);
    } catch (FileSizeLimitExceededException e) {
        // file size is larger than maximum allowed file size, throw an error
        Integer actualSize = new Integer((int) (e.getActualSize() / 1024));
        Integer maxSize = new Integer((int) (e.getPermittedSize() / 1024));
        throw new CmsUploadException(m_bundle.key(org.opencms.ade.upload.Messages.ERR_UPLOAD_FILE_SIZE_LIMIT_3,
                actualSize, e.getFileName(), maxSize), e);
    }
}

From source file:org.opencms.util.CmsRequestUtil.java

/**
 * Parses a request of the form <code>multipart/form-data</code>.
 * /*w w  w.  j  a  v  a  2 s.c  o m*/
 * The result list will contain items of type <code>{@link FileItem}</code>.
 * If the request is not of type <code>multipart/form-data</code>, then <code>null</code> is returned.<p>
 * 
 * @param request the HTTP servlet request to parse
 * 
 * @return the list of <code>{@link FileItem}</code> extracted from the multipart request,
 *      or <code>null</code> if the request was not of type <code>multipart/form-data</code>
 */
public static List<FileItem> readMultipartFileItems(HttpServletRequest request) {

    if (!ServletFileUpload.isMultipartContent(request)) {
        return null;
    }
    DiskFileItemFactory factory = new DiskFileItemFactory();
    // maximum size that will be stored in memory
    factory.setSizeThreshold(4096);
    // the location for saving data that is larger than getSizeThreshold()
    factory.setRepository(new File(OpenCms.getSystemInfo().getPackagesRfsPath()));
    ServletFileUpload fu = new ServletFileUpload(factory);
    // set encoding to correctly handle special chars (e.g. in filenames)
    fu.setHeaderEncoding(request.getCharacterEncoding());
    List<FileItem> result = new ArrayList<FileItem>();
    try {
        List<FileItem> items = CmsCollectionsGenericWrapper.list(fu.parseRequest(request));
        if (items != null) {
            result = items;
        }
    } catch (FileUploadException e) {
        LOG.error(Messages.get().getBundle().key(Messages.LOG_PARSE_MULIPART_REQ_FAILED_0), e);
    }
    return result;
}