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

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

Introduction

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

Prototype

public void setRepository(File repository) 

Source Link

Document

Sets the directory used to temporarily store files that are larger than the configured size threshold.

Usage

From source file:org.martin.cloudWebClient.servlets.UploadFileServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from   w  w  w . ja  v  a 2s .co  m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    HttpSession session = request.getSession();

    if (session.getAttribute("cliPackage") == null || session.getAttribute("connector") == null) {
        response.sendRedirect("index.jsp");
        return;
    }

    ClientPackage cp = (ClientPackage) session.getAttribute("cliPackage");
    Connector con = (Connector) session.getAttribute("connector");

    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(1024);
    factory.setRepository(new File(SysInfo.TEMP_FOLDER_NAME));

    ServletFileUpload upload = new ServletFileUpload(factory);

    try {
        List<FileItem> partes = upload.parseRequest(request);
        Archive toUpload;
        Command cmdUpload;
        File file;

        for (FileItem item : partes) {
            if (!item.isFormField()) {
                file = new File(SysInfo.TEMP_FOLDER_NAME, item.getName());
                item.write(file);
                toUpload = new Archive(cp.getCurrentDir(), item.getName());
                toUpload.writeBytesFrom(file);
                cmdUpload = new Command(Command.uplF.getOrder(), file.getCanonicalPath(),
                        cp.getCurrentDirPath());
                con.sendTransferPackage(new TransferPackage(cmdUpload, toUpload));
                file.delete();
            }
        }

        con.sendUpdateRequest(cp.getCurrentDirPath(), cp.getUserNick());
        cp.update(con.getUpdatesReceived());

        session.setAttribute("cliPackage", cp);
        response.sendRedirect("management.jsp");
    } catch (FileUploadException ex) {
        JOptionPane.showMessageDialog(null, "FileUploadException");
        Logger.getLogger(UploadFileServlet.class.getName()).log(Level.SEVERE, null, ex);
    } catch (Exception ex) {
        JOptionPane.showMessageDialog(null, "Exception");
        Logger.getLogger(UploadFileServlet.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:org.megatome.frame2.front.FileUploadSupport.java

@SuppressWarnings("unchecked")
public static Map<String, Object> processMultipartRequest(final HttpServletRequest request)
        throws Frame2Exception {
    Map<String, Object> parameters = new HashMap<String, Object>();

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

    // Set factory constraints
    factory.setSizeThreshold(FileUploadConfig.getBufferSize());
    factory.setRepository(new File(FileUploadConfig.getFileTempDir()));

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

    // Set overall request size constraint
    upload.setSizeMax(FileUploadConfig.getMaxFileSize());

    List<FileItem> fileItems = null;
    try {/*from  www  .j av a  2 s  . co m*/
        fileItems = upload.parseRequest(request);
    } catch (FileUploadException fue) {
        LOGGER.severe("File Upload Error", fue); //$NON-NLS-1$
        throw new Frame2Exception("File Upload Exception", fue); //$NON-NLS-1$
    }

    for (FileItem fi : fileItems) {
        String fieldName = fi.getFieldName();

        if (fi.isFormField()) {
            if (parameters.containsKey(fieldName)) {
                List<Object> tmpArray = new ArrayList<Object>();
                if (parameters.get(fieldName) instanceof String[]) {
                    String[] origValues = (String[]) parameters.get(fieldName);
                    for (int idx = 0; idx < origValues.length; idx++) {
                        tmpArray.add(origValues[idx]);
                    }
                    tmpArray.add(fi.getString());
                } else {
                    tmpArray.add(parameters.get(fieldName));
                    tmpArray.add(fi.getString());
                }
                String[] newValues = new String[tmpArray.size()];
                newValues = tmpArray.toArray(newValues);
                parameters.put(fieldName, newValues);
            } else {
                parameters.put(fieldName, fi.getString());
            }
        } else {
            if (parameters.containsKey(fieldName)) {
                List<Object> tmpArray = new ArrayList<Object>();
                if (parameters.get(fieldName) instanceof FileItem[]) {
                    FileItem[] origValues = (FileItem[]) parameters.get(fieldName);
                    for (int idx = 0; idx < origValues.length; idx++) {
                        tmpArray.add(origValues[idx]);
                    }
                    tmpArray.add(fi);
                } else {
                    tmpArray.add(parameters.get(fieldName));
                    tmpArray.add(fi);
                }
                FileItem[] newValues = new FileItem[tmpArray.size()];
                newValues = tmpArray.toArray(newValues);
                parameters.put(fieldName, newValues);
            } else {
                parameters.put(fieldName, fi);
            }
        }
    }

    return parameters;
}

From source file:org.mifos.dmt.ui.DMTExcelUpload.java

@SuppressWarnings("rawtypes")
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    DMTLock migrationLock = DMTLock.getInstance();
    if (!migrationLock.isLocked()) {
        migrationLock.getLock();//from  w  ww .j  av a  2 s .  co  m

        clearLogs();
        response.setContentType("text/plain");

        DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
        fileItemFactory.setSizeThreshold(5 * 1024 * 1024);
        fileItemFactory.setRepository(tmpDir);
        ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);

        try {
            List items = uploadHandler.parseRequest(request);
            Iterator itr = items.iterator();
            while (itr.hasNext()) {
                FileItem item = (FileItem) itr.next();

                File file = new File(destinationDir, "MigrationTemplate.xlsx");
                /*System.out.println("i got here " + destinationDir.toString());*/
                Workbook workbook = WorkbookFactory.create(item.getInputStream());

                SheetStructure sheetStructure = new SheetStructure(workbook);
                if (!sheetStructure.processWorkbook()) {
                    logger.error(
                            "Excel upload failed!!Please check if necessary sheets are present in the excel");
                    throw new DMTException(
                            "Excel upload failed!!Please check if necessary sheets are present in the excel");
                }

                String baseTemplate = DMTConfig.DMT_CONFIG_DIR + "\\DMTMigrationTemplateBase.xlsx";
                ColumnStructure columnstructure = new ColumnStructure(workbook, baseTemplate);
                workbook = columnstructure.processSheetStructure();

                PurgeEmptyRows excessrows = new PurgeEmptyRows(workbook);
                workbook = excessrows.processEmptyRows();

                FileOutputStream fileoutputstream = new FileOutputStream(file);
                workbook.write(fileoutputstream);
                logger.info("Uploading of Excel has been successful!!");
                migrationLock.releaseLock();
            }
        } catch (FileUploadException ex) {
            logger.error("Error encountered while parsing the request", ex);
            logger.error("Uploading of Excel has not been successful!!");
            migrationLock.releaseLock();
            ex.printStackTrace();
        } catch (Exception ex) {
            logger.error("Error encountered while uploading file", ex);
            logger.error("Uploading of Excel has not been successful!!");
            migrationLock.releaseLock();
            ex.printStackTrace();
        }

    } else {
        request.setAttribute("action", "info");
        RequestDispatcher requestDispatcher = getServletContext().getRequestDispatcher("/x");
        requestDispatcher.forward(request, response);
    }
}

From source file:org.modeshape.web.BackupUploadServlet.java

@Override
public void init() {
    DiskFileItemFactory diskFactory = new DiskFileItemFactory();

    // Configure a repository (to ensure a secure temp location is used)
    ServletContext servletContext = this.getServletConfig().getServletContext();

    tempDir = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
    diskFactory.setRepository(tempDir);

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

From source file:org.modeshape.web.BinaryContentUploadServlet.java

@Override
public void init() {
    DiskFileItemFactory diskFactory = new DiskFileItemFactory();

    // Configure a repository (to ensure a secure temp location is used)
    ServletContext servletContext = this.getServletConfig().getServletContext();
    File tempDir = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
    diskFactory.setRepository(tempDir);

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

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 {/*  w  w  w .  j a  va  2  s.c o  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.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(/*from   www .ja  va  2  s  . c o  m*/
                "<!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.nordapp.web.servlet.DEVServlet.java

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

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

        //@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  w  ww  .ja v  a2s  . 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 {//w w w .  ja  va  2s  .  com

        //@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);
    }
}