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

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

Introduction

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

Prototype

public DiskFileItemFactory() 

Source Link

Document

Constructs an unconfigured instance of this class.

Usage

From source file:edu.lafayette.metadb.web.projectman.CreateProject.java

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
 *      response)/*from   ww  w. jav a2 s .  c o m*/
 */
@SuppressWarnings("unchecked")
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // TODO Auto-generated method stub
    PrintWriter out = response.getWriter();
    JSONObject output = new JSONObject();
    String delimiter = "";
    String projname = "";
    String projnotes = "";
    String template = "";
    boolean useTemplate = false;
    boolean disableQualifier = false;
    try {
        if (ServletFileUpload.isMultipartContent(request)) {
            ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory());
            List fileItemsList = servletFileUpload.parseRequest(request);
            DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
            diskFileItemFactory.setSizeThreshold(40960); /* the unit is bytes */

            Iterator it = fileItemsList.iterator();
            InputStream input = null;
            while (it.hasNext()) {
                FileItem fileItem = (FileItem) it.next();
                //MetaDbHelper.note("Field name: "+fileItem.getFieldName());
                //MetaDbHelper.note(fileItem.getString());
                if (fileItem.isFormField()) {
                    /*
                     * The file item contains a simple name-value pair of a
                     * form field
                     */
                    if (fileItem.getFieldName().equals("delimiter") && delimiter.equals(""))
                        delimiter = fileItem.getString();
                    else if (fileItem.getFieldName().equals("projname") && projname.equals(""))
                        projname = fileItem.getString().replace(" ", "_");
                    else if (fileItem.getFieldName().equals("projnotes") && projnotes.equals(""))
                        projnotes = fileItem.getString();
                    else if (fileItem.getFieldName().equals("project-template-checkbox"))
                        useTemplate = true;
                    else if (fileItem.getFieldName().equals("project-template"))
                        template = fileItem.getString().replace(" ", "_");
                    //else if (fileItem.getFieldName().equals("disable-qualifier-checkbox"))
                    //disableQualifier = true;
                } else
                    input = fileItem.getInputStream();

            }
            String userName = Global.METADB_USER;

            HttpSession session = request.getSession(false);
            if (session != null) {
                userName = (String) session.getAttribute(Global.SESSION_USERNAME);
            }

            //MetaDbHelper.note("Delimiter: "+delimiter+", projname: "+projname+", projnotes: "+projnotes+", use template or not? "+useTemplate+" template: "+template);
            if (useTemplate) {
                ProjectsDAO.createProject(template, projname, projnotes, "");
                output.put("projname", projname);
                output.put("success", true);
                output.put("message", "Project created successfully based on: " + template);
                SysLogDAO.log(userName, Global.SYSLOG_PROJECT,
                        "User created project " + projname + " with template from " + template);
            } else {
                if (ProjectsDAO.createProject(projname, projnotes)) {
                    output.put("projname", projname);
                    String delimiterType = "csv";
                    if (delimiter.equals("tab")) {
                        delimiterType = "tsv";
                        disableQualifier = true; // Disable text qualifiers for TSV files.
                    }
                    //MetaDbHelper.note("Delim: "+delimiterType+", projname: "+projname+", input: "+input);
                    if (input != null) {
                        Result res = DataImporter.importFile(delimiterType, projname, input, disableQualifier);
                        output.put("success", res.isSuccess());
                        if (res.isSuccess()) {
                            output.put("message", "Data import successfully");
                            SysLogDAO.log(userName, Global.SYSLOG_PROJECT,
                                    "User created project " + projname + " with file import");
                        } else {

                            output.put("message", "The following fields have been changed");
                            SysLogDAO.log(userName, Global.SYSLOG_PROJECT,
                                    "User created project " + projname + " with file import");
                            String fields = "";
                            ArrayList<String> data = (ArrayList<String>) res.getData();
                            for (String field : data)
                                fields += field + ',';
                            output.put("fields", fields);
                        }
                    } else {
                        output.put("success", true);
                        output.put("message",
                                "Project created successfully with default fields. No data imported");
                        SysLogDAO.log(userName, Global.SYSLOG_PROJECT, "User created project " + projname);
                    }
                } else {
                    output.put("success", false);
                    output.put("message", "Cannot create project");
                    SysLogDAO.log(userName, Global.SYSLOG_PROJECT, "User failed to create project " + projname);
                }
            }
        } else {
            output.put("success", false);
            output.put("message", "Form is not multi-part");
        }
    } catch (NullPointerException e) {
        try {
            output.put("success", true);
            output.put("message", "Project created successfully");
        } catch (JSONException e1) {
            MetaDbHelper.logEvent(e1);
        }

    } catch (Exception e) {
        MetaDbHelper.logEvent(e);
        try {
            output.put("success", false);
            output.put("message", "Project was not created");
        } catch (JSONException e1) {
            MetaDbHelper.logEvent(e1);
        }
    }
    out.print(output);
    out.flush();

}

From source file:com.finedo.base.utils.upload.FileUploadUtils.java

public static final List<FileInfo> saveLicense(String uploadDir, List<FileItem> list) {

    List<FileInfo> filelist = new ArrayList<FileInfo>();

    if (list == null) {
        return filelist;
    }/*  w w w  .j a va2 s .  c  om*/

    //?
    //??
    logger.info("saveFiles uploadDir=============" + uploadDir);
    File dir = new File(uploadDir);
    if (!dir.isDirectory()) {
        dir.mkdirs();
    } else {

    }

    String uploadPath = uploadDir;

    DiskFileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setHeaderEncoding("utf-8");
    Iterator<FileItem> it = list.iterator();
    String name = "";
    String extName = "";

    while (it.hasNext()) {
        FileItem item = it.next();
        if (!item.isFormField()) {
            name = item.getName();
            if (name == null || name.trim().equals("")) {
                continue;
            }
            long l = item.getSize();
            logger.info("file size=" + l);
            if (10 * 1024 * 1024 < l) {
                logger.info("File size is greater than 10M!");
                continue;
            }
            name = name.replace("\\", "/");
            if (name.lastIndexOf("/") >= 0) {
                name = name.substring(name.lastIndexOf("/"));
            }
            logger.info("saveFiles name=============" + name);
            File saveFile = new File(uploadPath + name);
            try {
                item.write(saveFile);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {

            }

            String fileName = item.getName().replace("\\", "/");

            String[] ss = fileName.split("/");
            fileName = trimExtension(ss[ss.length - 1]);
            FileInfo fileinfo = new FileInfo();
            fileinfo.setName(fileName);
            fileinfo.setUname(name);
            fileinfo.setFilePath(uploadDir);
            fileinfo.setFileExt(extName);
            fileinfo.setSize(String.valueOf(item.getSize()));
            fileinfo.setContentType(item.getContentType());
            fileinfo.setFieldname(item.getFieldName());
            filelist.add(fileinfo);
        }
    }
    return filelist;
}

From source file:com.mirth.connect.server.servlets.ExtensionServlet.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // MIRTH-1745
    response.setCharacterEncoding("UTF-8");

    if (!isUserLoggedIn(request)) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
    } else {/*w ww. ja v a  2s  . c om*/
        try {
            ExtensionController extensionController = ControllerFactory.getFactory()
                    .createExtensionController();
            ObjectXMLSerializer serializer = new ObjectXMLSerializer();
            PrintWriter out = response.getWriter();
            FileItem multiPartFileItem = null;
            Operation operation = null;
            Map<String, Object> parameterMap = new HashMap<String, Object>();

            if (ServletFileUpload.isMultipartContent(request)) {
                Map<String, String> multipartParameters = new HashMap<String, String>();
                File installTempDir = new File(ExtensionController.getExtensionsPath(), "install_temp");

                if (!installTempDir.exists()) {
                    installTempDir.mkdir();
                }

                // we need to load properties from the multipart data
                DiskFileItemFactory factory = new DiskFileItemFactory();
                factory.setRepository(installTempDir);
                ServletFileUpload upload = new ServletFileUpload(factory);
                List<FileItem> items = upload.parseRequest(request);

                for (FileItem item : items) {
                    if (item.isFormField()) {
                        multipartParameters.put(item.getFieldName(), item.getString());
                    } else {
                        // only supports a single file
                        multiPartFileItem = item;
                    }
                }

                operation = Operations.getOperation(multipartParameters.get("op"));
            } else {
                operation = Operations.getOperation(request.getParameter("op"));
            }

            if (operation.equals(Operations.PLUGIN_PROPERTIES_GET)) {
                String pluginName = request.getParameter("name");

                if (isUserAuthorizedForExtension(request, pluginName, operation.getName(), null)) {
                    response.setContentType(APPLICATION_XML);
                    serializer.toXML(extensionController.getPluginProperties(pluginName), out);
                } else {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                }
            } else if (operation.equals(Operations.PLUGIN_PROPERTIES_SET)) {
                String pluginName = request.getParameter("name");

                if (isUserAuthorizedForExtension(request, pluginName, operation.getName(), null)) {
                    Properties properties = (Properties) serializer.fromXML(request.getParameter("properties"));
                    extensionController.setPluginProperties(pluginName, properties);
                    extensionController.updatePluginProperties(pluginName, properties);
                } else {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                }
            } else if (operation.equals(Operations.PLUGIN_METADATA_GET)) {
                response.setContentType(APPLICATION_XML);
                serializer.toXML(extensionController.getPluginMetaData(), out);
            } else if (operation.equals(Operations.EXTENSION_SET_ENABLED)) {
                String pluginName = request.getParameter("name");
                boolean enabled = BooleanUtils.toBoolean(request.getParameter("enabled"));
                parameterMap.put("extension", pluginName);
                parameterMap.put("enabled", enabled);

                if (isUserAuthorized(request, parameterMap)) {
                    extensionController.setExtensionEnabled(pluginName, enabled);
                } else {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                }
            } else if (operation.equals(Operations.CONNECTOR_METADATA_GET)) {
                response.setContentType(APPLICATION_XML);
                serializer.toXML(extensionController.getConnectorMetaData(), out);
            } else if (operation.equals(Operations.EXTENSION_IS_ENABLED)) {
                String extensionName = request.getParameter("name");
                response.setContentType(TEXT_PLAIN);
                out.print(extensionController.isExtensionEnabled(extensionName));
            } else if (operation.equals(Operations.PLUGIN_SERVICE_INVOKE)) {
                String pluginName = request.getParameter("name");
                String method = request.getParameter("method");
                Object object = serializer.fromXML(request.getParameter("object"));
                String sessionId = request.getSession().getId();

                if (isUserAuthorizedForExtension(request, pluginName, method, null)) {
                    serializer.toXML(
                            extensionController.invokePluginService(pluginName, method, object, sessionId),
                            out);
                } else {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                }
            } else if (operation.equals(Operations.CONNECTOR_SERVICE_INVOKE)) {
                String name = request.getParameter("name");
                String method = request.getParameter("method");
                Object object = serializer.fromXML(request.getParameter("object"));
                String sessionId = request.getSession().getId();
                response.setContentType(APPLICATION_XML);
                serializer.toXML(extensionController.invokeConnectorService(name, method, object, sessionId),
                        out);
            } else if (operation.equals(Operations.EXTENSION_UNINSTALL)) {
                String packageName = request.getParameter("packageName");
                parameterMap.put("packageName", packageName);

                if (isUserAuthorized(request, parameterMap)) {
                    extensionController.prepareExtensionForUninstallation(packageName);
                } else {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                }
            } else if (operation.equals(Operations.EXTENSION_INSTALL)) {
                if (isUserAuthorized(request, null)) {
                    /*
                     * This is a multi-part method, so we need our
                     * parameters from the new map
                     */
                    extensionController.extractExtension(multiPartFileItem);
                } else {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                }
            }
        } catch (RuntimeIOException rio) {
            logger.debug(rio);
        } catch (Throwable t) {
            logger.error(ExceptionUtils.getStackTrace(t));
            throw new ServletException(t);
        }
    }
}

From source file:dk.clarin.tools.rest.upload.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    response.setContentType("text/xml");
    response.setStatus(200);//from   w w  w  .j a va 2  s . com
    if (!BracMat.loaded()) {
        response.setStatus(500);
        throw new ServletException("Bracmat is not loaded. Reason:" + BracMat.reason());
    }

    DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
    /*
    *Set the size threshold, above which content will be stored on disk.
    */
    fileItemFactory.setSizeThreshold(1 * 1024 * 1024); //1 MB
    /*
    * Set the temporary directory to store the uploaded files of size above threshold.
    */
    fileItemFactory.setRepository(tmpDir);

    String arg = "(method.POST)"; // bj 20120801 "(action.POST)";

    ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
    try {
        /*
        * Parse the request
        */
        @SuppressWarnings("unchecked")
        List<FileItem> items = (List<FileItem>) uploadHandler.parseRequest(request);
        Iterator<FileItem> itr = items.iterator();
        FileItem theFile = null;
        while (itr.hasNext()) {
            FileItem item = (FileItem) itr.next();
            /*
            * Handle Form Fields.
            */
            if (item.isFormField()) {
                // We need the job parameter that indirectly tells us what local file name to give to the uploaded file.
                arg = arg + " (\"" + workflow.escape(item.getFieldName()) + "\".\""
                        + workflow.escape(item.getString()) + "\")";
            } else if (item.getName() != "") {
                //Handle Uploaded file.
                if (theFile != null) {
                    response.setStatus(400);
                    /**
                     * getStatusCode$
                     *
                     * Given a HTTP status code and an informatory text, return an HTML-file
                     * with a heading containing the status code and the official short description
                     * of the status code, a paragraph containing the informatory text and a 
                     * paragraph displaying a longer text explaining the code (From wikipedia).
                     * 
                     * This function could just as well have been written in Java.
                     */
                    String messagetext = BracMat.Eval("getStatusCode$(\"400\".\"Too many files uploaded\")");
                    out.println(messagetext);
                    return;
                }
                theFile = item;
            }
        }
        if (theFile != null) {
            /*
            * Write file to the ultimate location.
            */
            /**
             * upload$
             *
             * Make a waiting job non-waiting upon receipt of a result from an 
             * asynchronous tool.
             *
             * Analyze the job parameter. It tells to which job the sent file belongs.
             * The jobs table knows the file name and location for the uploaded file.
             *              (Last field)
             * Input:
             *      List of HTTP request parameters.
             *      One of the parameters must be (job.<jobNr>-<jobID>)
             *
             * Output:
             *      The file name that must be given to the received file when saved in
             *      the staging area.
             *
             * Status codes:
             *      200     ok
             *      400     'job' parameter does not contain hyphen '-' or
             *              'job' parameter missing altogether.
             *      404     Job is not expecting a result (job is not waiting)
             *              Job is unknown
             *      500     Job list could not be read
             *
             * Affected tables:
             *      jobs.table
             */
            String LocalFileName = BracMat.Eval("upload$(" + arg + ")");
            if (LocalFileName == null) {
                response.setStatus(404);
                String messagetext = BracMat
                        .Eval("getStatusCode$(\"404\".\"doPost:" + workflow.escape(LocalFileName) + "\")");
                out.println(messagetext);
            } else if (LocalFileName.startsWith("HTTP-status-code")) {
                /**
                 * parseStatusCode$
                 *
                 * Find the number greater than 100 immediately following the string 
                 * 'HTTP-status-code'
                 */
                String statusCode = BracMat
                        .Eval("parseStatusCode$(\"" + workflow.escape(LocalFileName) + "\")");
                response.setStatus(Integer.parseInt(statusCode));
                /**
                 * parsemessage$
                 *
                 * Find the text following the number greater than 100 immediately following the string 
                 * 'HTTP-status-code'
                 */
                String messagetext = BracMat.Eval("parsemessage$(\"" + workflow.escape(LocalFileName) + "\")");
                messagetext = BracMat.Eval("getStatusCode$(\"" + workflow.escape(statusCode) + "\".\""
                        + workflow.escape(messagetext) + "\")");
                out.println(messagetext);
            } else {
                File file = new File(destinationDir, LocalFileName);
                try {
                    theFile.write(file);
                } catch (Exception ex) {
                    response.setStatus(500);
                    String messagetext = BracMat
                            .Eval("getStatusCode$(\"500\".\"Tools cannot save uploaded file to "
                                    + workflow.escape(destinationDir + LocalFileName) + "\")");
                    out.println(messagetext);
                    return;
                }
                /**
                 * uploadJobNr$
                 *
                 * Return the string preceding the hyphen in the input.
                 *
                 * Input: <jobNr>-<jobID>
                 */
                String JobNr = BracMat.Eval("uploadJobNr$(" + arg + ")");
                Runnable runnable = new workflow(JobNr, destinationDir);
                Thread thread = new Thread(runnable);
                thread.start();
                response.setStatus(201);
                String messagetext = BracMat.Eval("getStatusCode$(\"201\".\"\")");
                out.println(messagetext);
            }
        } else {
            response.setStatus(400);
            String messagetext = BracMat.Eval("getStatusCode$(\"400\".\"No file uploaded\")");
            out.println(messagetext);
        }
    } catch (FileUploadException ex) {
        response.setStatus(500);
        String messagetext = BracMat.Eval("getStatusCode$(\"500\".\"doPost: FileUploadException "
                + workflow.escape(ex.toString()) + "\")");
        out.println(messagetext);
    } catch (Exception ex) {
        response.setStatus(500);
        String messagetext = BracMat
                .Eval("getStatusCode$(\"500\".\"doPost: Exception " + workflow.escape(ex.toString()) + "\")");
        out.println(messagetext);
    }
}

From source file:ke.co.tawi.babblesms.server.servlet.upload.ContactUpload.java

/**
 *
 * @param config/*from  w ww.ja va  2  s  .co  m*/
 * @throws ServletException
 */
@Override
public void init(ServletConfig config) throws ServletException {
    super.init(config);

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

    File repository = FileUtils.getTempDirectory();
    factory.setRepository(repository);

    uploadUtil = new UploadUtil();

    contactDAO = ContactDAO.getInstance();
    phoneDAO = PhoneDAO.getInstance();
    contactGroupDAO = ContactGroupDAO.getInstance();

    CacheManager mgr = CacheManager.getInstance();
    accountsCache = mgr.getCache(CacheVariables.CACHE_ACCOUNTS_BY_USERNAME);
}

From source file:fr.gael.dhus.server.http.webapp.api.controller.UploadController.java

@PreAuthorize("hasRole('ROLE_UPLOAD')")
@RequestMapping(value = "/upload", method = { RequestMethod.POST })
public void upload(Principal principal, HttpServletRequest req, HttpServletResponse res) throws IOException {
    // process only multipart requests
    if (ServletFileUpload.isMultipartContent(req)) {
        // Create a factory for disk-based file items
        FileItemFactory factory = new DiskFileItemFactory();
        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);

        // Parse the request
        try {/*w w  w .j a  va  2s .  co m*/
            ArrayList<String> collectionIds = new ArrayList<>();
            FileItem product = null;

            List<FileItem> items = upload.parseRequest(req);
            for (FileItem item : items) {
                if (COLLECTIONSKEY.equals(item.getFieldName())) {
                    if (item.getString() != null && !item.getString().isEmpty()) {
                        for (String cid : item.getString().split(",")) {
                            collectionIds.add(cid);
                        }
                    }
                } else if (PRODUCTKEY.equals(item.getFieldName())) {
                    product = item;
                }
            }
            if (product == null) {
                res.sendError(HttpServletResponse.SC_BAD_REQUEST,
                        "Your request is missing a product file to upload.");
                return;
            }
            productUploadService.upload(product, collectionIds);
            res.setStatus(HttpServletResponse.SC_CREATED);
            res.getWriter().print("The file was created successfully.");
            res.flushBuffer();
        } catch (FileUploadException e) {
            LOGGER.error("An error occurred while parsing request.", e);
            res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "An error occurred while parsing request : " + e.getMessage());
        } catch (UserNotExistingException e) {
            LOGGER.error("You need to be connected to upload a product.", e);
            res.sendError(HttpServletResponse.SC_UNAUTHORIZED, "You need to be connected to upload a product.");
        } catch (UploadingException e) {
            LOGGER.error("An error occurred while uploading the product.", e);
            res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "An error occurred while uploading the product : " + e.getMessage());
        } catch (RootNotModifiableException e) {
            LOGGER.error("An error occurred while uploading the product.", e);
            res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "An error occurred while uploading the product : " + e.getMessage());
        } catch (ProductNotAddedException e) {
            LOGGER.error("Your product can not be read by the system.", e);
            res.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE, "Your product can not be read by the system.");
        }
    } else {
        res.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE,
                "Request contents type is not supported by the servlet.");
    }
}

From source file:com.bluelotussoftware.apache.commons.fileupload.example.FileUploadServlet.java

/**
 * Processes requests for both HTTP/*from w ww.j  a v a2  s . co  m*/
 * <code>GET</code> and
 * <code>POST</code> methods.
 *
 * @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 {
    response.setContentType("text/html;charset=UTF-8");
    boolean isMultiPart = ServletFileUpload.isMultipartContent(request);
    log("isMultipartContent: " + isMultiPart);
    log("Content-Type: " + request.getContentType());
    if (isMultiPart) {

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

        /*
         * Set the file size limit in bytes. This should be set as an
         * initialization parameter
         */
        diskFileItemFactory.setSizeThreshold(1024 * 1024 * 10); //10MB.

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

        // Parse the request
        List items = null;
        try {
            items = upload.parseRequest(request);
        } catch (FileUploadException ex) {
            log("Could not parse request", ex);
        }

        PrintWriter out = response.getWriter();
        out.print("<html><head><title>SUCCESS</title></head><body><h1>DONE!</h1>");

        ListIterator li = items.listIterator();
        while (li.hasNext()) {
            FileItem fileItem = (FileItem) li.next();
            if (fileItem.isFormField()) {
                processFormField(fileItem);
            } else {
                out.append(processUploadedFile(fileItem));
            }
        }
        out.print("</body></html>");
        out.flush();
        out.close();

    }
}

From source file:at.ac.dbisinformatik.snowprofile.web.ListSnowProfileResource.java

/**
 * store new Snowprofile in Database/*  w w  w  . ja v  a  2 s  .  c o  m*/
 * 
 * @param entity
 * @return
 * @throws Exception
 */
@Post
public String storeJson(Representation entity) throws Exception {
    String rep = "";
    if (entity != null) {
        if (MediaType.MULTIPART_FORM_DATA.equals(entity.getMediaType(), true)) {
            DiskFileItemFactory factory = new DiskFileItemFactory();
            factory.setSizeThreshold(1000240);

            RestletFileUpload upload = new RestletFileUpload(factory);
            List<FileItem> items;

            items = upload.parseRequest(getRequest());

            boolean found = false;
            for (final Iterator<FileItem> it = items.iterator(); it.hasNext() && !found;) {
                FileItem fi = it.next();
                String snowprofile = "";
                if (fi.getFieldName().equals("import")) {
                    snowprofile = IOUtils.toString(fi.getInputStream());
                    JSONObject snowprofileJSON = XML.toJSONObject(snowprofile);

                    snowprofile = snowprofileJSON.toString().replace("caaml:", "");
                    snowprofile = snowprofile.replace("gml:", "gml_");
                    snowprofile = snowprofile.replace("xmlns:", "xmlns_");
                    snowprofile = snowprofile.replace("xsi:", "xsi_");

                    snowprofileJSON = new JSONObject(snowprofile);

                    snowprofile = db.store("SnowProfile",
                            new JSONObject(snowprofileJSON.get("SnowProfile").toString()));
                    rep = "{\"success\": \"true\", \"id\": \"" + snowprofile + "\"}";
                } else {
                    rep = new StringRepresentation("no file uploaded", MediaType.TEXT_PLAIN).toString();
                }
            }
        } else {
            rep = db.store("SnowProfile", new JSONObject(entity.getText()));
        }
    }

    return rep;
}

From source file:com.colegiocefas.cefasrrhh.servlets.subirCurriculo.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*from  w w  w  . j  a va 2s  .  c o  m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String dui = request.getParameter("dui");
    String nombre = request.getParameter("nombre");
    String especialidad = request.getParameter("especialidad");
    String url = request.getParameter("url");

    //Cdigo para subir pdf del curriculum al servidor
    try {
        List items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
        for (int i = 0; i < items.size(); i++) {
            FileItem item = (FileItem) items.get(i);
            if (item.isFormField()) {
                if (item.getFieldName().equals("dui"))
                    dui = item.getString("UTF-8");
                if (item.getFieldName().equals("especialidad"))
                    especialidad = item.getString("UTF-8");
                if (item.getFieldName().equals("nombre"))
                    nombre = item.getString("UTF-8");
            } else {
                Date fecha = Calendar.getInstance().getTime();
                SimpleDateFormat formato = new SimpleDateFormat("yyyyMMdd-hhmmss-");
                String nombreImagen = formato.format(fecha);
                nombreImagen += dui;
                //String fileName = item.getName();
                response.setContentType("text/plain");
                response.setCharacterEncoding("UTF-8");
                String realPath = request.getSession().getServletContext().getRealPath("/");
                File fichero = new File(realPath + "documentos/candidatos/", nombreImagen + ".pdf");
                item.write(fichero);
                url = "documentos/candidatos/" + fichero.getName();
            }
        }
        CtrlCEFAS_Candidato ctrlcandidato = new CtrlCEFAS_Candidato();
        ctrlcandidato.guardarCurriculum(dui, nombre, Integer.parseInt(especialidad), url);
        String mensaje = "<div class='alert alert-success' role='alert'>Guardado</div>";
        response.sendRedirect("ingresarcurriculum.jsp");
    } catch (Exception e) {
        //out.write(e.getMessage());
        //JOptionPane.showMessageDialog(null, e.getMessage());
        throw new ServletException("Parsing file upload failed.", e);
    }
}

From source file:jm.web.Archivo.java

/**
 * Sube un archivo del cliente al servidor Web. Si el archivo ya existe en el
 * servidor Web lo sobrescribe.//from w  w  w.  jav a  2 s  .  c  om
 * @param request. Variable que contiene el request de un formulario.
 * @param tamanioMax. Tamao mximo del archivo en megas.
 * @return Retorna true o false si se subi o no el archivo.
 */
public boolean subir(HttpServletRequest request, double tamanioMax, String[] formato) {
    boolean res = false;
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (isMultipart) {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        try {
            List items = upload.parseRequest(request);
            Iterator iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                if (!item.isFormField()) {
                    String tipo = item.getContentType();
                    double tamanio = (double) item.getSize() / 1024 / 1024; // para tamao en megas
                    this._archivoNombre = item.getName().replace(" ", "_");
                    this._error = "Se ha excedido el tamao mximo del archivo";
                    if (tamanio <= tamanioMax) {
                        this._error = "El formato del archivo es incorrecto. " + tipo;
                        boolean estaFormato = false;
                        for (int i = 0; i < formato.length; i++) {
                            if (tipo.compareTo(formato[i]) == 0) {
                                estaFormato = true;
                                break;
                            }
                        }
                        if (estaFormato) {
                            this._archivo = new File(this._directorio, this._archivoNombre);
                            item.write(this._archivo);
                            this._error = "";
                            res = true;
                        }
                    }
                }
            }
        } catch (Exception e) {
            this._error = e.getMessage();
            e.printStackTrace();
        }
    }
    return res;
}