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.footware.server.services.TrackUploadServlet.java

@SuppressWarnings("unchecked")
@Override/*from ww  w  . j a v  a2s  . co  m*/
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    logger = LoggerFactory.getLogger(TrackUploadServlet.class);

    // Check that we have a file upload request
    boolean isMultipart = ServletFileUpload.isMultipartContent(req);

    // Init fields of form
    String extension = "";
    File uploadedFile = null;
    String notes = "";
    String name = "";
    int privacy = 0;
    Boolean comments = false;
    String fileName = null;
    String email = null;
    FileItem file = null;

    if (isMultipart) {

        // Create a factory for disk-based file items
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setRepository(new File("tmp"));
        factory.setSizeThreshold(10000000);

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

        // Create a progress listener
        ProgressListener progressListener = new ProgressListener() {
            public void update(long pBytesRead, long pContentLength, int pItems) {
                logger.info("We are currently reading item " + pItems);
                if (pContentLength == -1) {
                    logger.info("So far, " + pBytesRead + " bytes have been read.");
                } else {
                    logger.info("So far, " + pBytesRead + " of " + pContentLength + " bytes have been read.");
                }
            }
        };
        upload.setProgressListener(progressListener);

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

            Iterator<FileItem> iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = iter.next();

                // Process a file upload
                if (!item.isFormField() && item.getFieldName().equals("file")) {

                    // Get file name
                    fileName = item.getName();

                    // If file is not set, we cancel import
                    if (fileName == null) {
                        logger.info("empty file name");
                        break;
                    }

                    // We have to parse the filename because of IE again
                    else {
                        logger.info("received file:" + fileName);
                        fileName = FilenameUtils.getName(fileName);

                        file = item;

                    }

                    // Read notes field
                } else if (item.isFormField() && item.getFieldName().equals("notes")) {
                    notes = item.getString();
                    logger.debug("notes" + ": " + item.getString());

                    // Read comments field
                } else if (item.isFormField() && item.getFieldName().equals("comments")) {

                    // Value can either be on or off
                    if (item.getString().equals("on")) {
                        comments = true;
                    } else {
                        comments = false;
                    }
                    logger.debug("comments" + ": " + item.getString());

                    // Read privacy field
                } else if (item.isFormField() && item.getFieldName().equals("privacy")) {
                    String priv = item.getString();

                    // Currently values can be either public or private.
                    // Default is private
                    if (priv.equals("public")) {
                        privacy = 5;
                    } else if (priv.equals("private")) {
                        privacy = 0;
                    } else {
                        privacy = 0;
                    }
                    logger.debug("privacy" + ": " + item.getString());

                    // Read name file
                } else if (item.isFormField() && item.getFieldName().equals("name")) {
                    name = item.getString();
                    logger.debug("name" + ": " + item.getString());
                } else if (item.isFormField() && item.getFieldName().equals("email")) {
                    email = item.getString();
                    logger.debug("email" + ": " + item.getString());
                }
            }
            User user = UserUtil.getByEmail(email);

            // If we read all fields, we can start the import
            if (file != null) {

                // Get UserDTO
                // User user = (User) req.getSession().getAttribute("user");

                // UserUtil.getByEmail(email);
                logger.info("User: " + user.getFullName() + " " + user.getEmail());
                String userDirectoryString = user.getEmail().replace("@", "_at_");

                File baseDirectory = initFileStructure(userDirectoryString);

                // If already a file exist with the same name, we have
                // to search for a new name
                extension = fileName.substring(fileName.length() - 3, fileName.length());
                uploadedFile = getSavePath(baseDirectory.getAbsolutePath(), fileName);
                logger.debug(uploadedFile.getAbsolutePath());

                // Finally write the file to disk
                try {
                    file.write(uploadedFile);
                } catch (Exception e) {
                    logger.error("File upload unsucessful", e);
                    e.printStackTrace();
                    return;
                }

                TrackImporter importer = importerMap.get(extension);
                importer.importTrack(uploadedFile);
                TrackVisualizationFactoryImpl speedFactory = new TrackVisualizationFactoryImpl(
                        new TrackVisualizationSpeedStrategy());
                TrackVisualizationFactoryImpl elevationFactory = new TrackVisualizationFactoryImpl(
                        new TrackVisualizationElevationStrategy());

                // Add meta information to track
                for (Track dbTrack : importer.getTracks()) {
                    dbTrack.setCommentsEnabled(comments);
                    dbTrack.setNotes(notes);
                    dbTrack.setPublicity(privacy);
                    dbTrack.setFilename(fileName);
                    dbTrack.setPath(uploadedFile.getAbsolutePath());

                    dbTrack.setUser(user);
                    //persist
                    dbTrack.store();

                    TrackVisualization ele = new TrackVisualization(speedFactory.create(dbTrack));
                    ele.store();
                    TrackVisualization spd = new TrackVisualization(elevationFactory.create(dbTrack));
                    spd.store();
                }

            } else {
                logger.error("error: file: " + (file != null));
            }
        } catch (FileUploadException e1) {
            logger.error("File upload unsucessful", e1);
            e1.printStackTrace();
        } catch (Exception e) {
            logger.error("File upload unsucessful", e);
            e.printStackTrace();
        }
    }
}

From source file:org.j2eeframework.commons.struts2.multipart.JakartaMultiPartRequest.java

/**
 * Creates a new request wrapper to handle multi-part data using methods adapted from Jason Pell's
 * multipart classes (see class description).
 *
 * @param saveDir        the directory to save off the file
 * @param servletRequest the request containing the multipart
 * @throws java.io.IOException  is thrown if encoding fails.
 *//*from   w w w .j  a va 2s  .  com*/
public void parse(HttpServletRequest servletRequest, String saveDir) throws IOException {
    DiskFileItemFactory fac = new DiskFileItemFactory();
    // Make sure that the data is written to file
    fac.setSizeThreshold(0);
    if (saveDir != null) {
        fac.setRepository(new File(saveDir));
    }

    // Parse the request
    try {
        ServletFileUpload upload = new ServletFileUpload(fac);
        upload.setSizeMax(maxSize);

        @SuppressWarnings("unchecked")
        List<FileItem> items = upload.parseRequest(createRequestContext(servletRequest));

        for (Object item1 : items) {
            FileItem item = (FileItem) item1;
            if (LOG.isDebugEnabled())
                LOG.debug("Found item " + item.getFieldName());
            if (item.isFormField()) {
                LOG.debug("Item is a normal form field");
                List<String> values;
                if (params.get(item.getFieldName()) != null) {
                    values = params.get(item.getFieldName());
                } else {
                    values = new ArrayList<String>();
                }

                // note: see http://jira.opensymphony.com/browse/WW-633
                // basically, in some cases the charset may be null, so
                // we're just going to try to "other" method (no idea if this
                // will work)
                String charset = servletRequest.getCharacterEncoding();
                if (charset != null) {
                    values.add(item.getString(charset));
                } else {
                    values.add(item.getString());
                }
                params.put(item.getFieldName(), values);
            } else {
                LOG.debug("Item is a file upload");

                // Skip file uploads that don't have a file name - meaning that no file was selected.
                if (item.getName() == null || item.getName().trim().length() < 1) {
                    LOG.debug("No file has been uploaded for the field: " + item.getFieldName());
                    continue;
                }

                List<FileItem> values;
                if (files.get(item.getFieldName()) != null) {
                    values = files.get(item.getFieldName());
                } else {
                    values = new ArrayList<FileItem>();
                }

                values.add(item);
                files.put(item.getFieldName(), values);
            }
        }
    } catch (SizeLimitExceededException e) {
        ArrayList<String> values = new ArrayList<String>();
        values.add("SizeLimitExceededException");
        params.put("exception", values);//?
    } catch (FileUploadException e) {
        LOG.error("Unable to parse request", e);
        ArrayList<String> values = new ArrayList<String>();
        values.add("FileUploadException");
        params.put("exception", values);
        errors.add(e.getMessage());
    }
}

From source file:org.jahia.tools.files.FileUpload.java

/**
 * Init the MultiPartReq object if it's actually null
 *
 * @exception IOException//  w ww. j a v  a  2s . c om
 */
protected void init() throws IOException {

    params = new HashMap<String, List<String>>();
    paramsContentType = new HashMap<String, String>();
    files = new HashMap<String, DiskFileItem>();
    filesByFieldName = new HashMap<String, DiskFileItem>();

    parseQueryString();

    if (checkSavePath(savePath)) {
        try {
            final ServletFileUpload upload = new ServletFileUpload();
            FileItemIterator iter = upload.getItemIterator(req);
            DiskFileItemFactory factory = null;
            while (iter.hasNext()) {
                FileItemStream item = iter.next();
                InputStream stream = item.openStream();
                if (item.isFormField()) {
                    final String name = item.getFieldName();
                    final List<String> v;
                    if (params.containsKey(name)) {
                        v = params.get(name);
                    } else {
                        v = new ArrayList<String>();
                        params.put(name, v);
                    }
                    v.add(Streams.asString(stream, encoding));
                    paramsContentType.put(name, item.getContentType());
                } else {
                    if (factory == null) {
                        factory = new DiskFileItemFactory();
                        factory.setSizeThreshold(1);
                        factory.setRepository(new File(savePath));
                    }
                    DiskFileItem fileItem = (DiskFileItem) factory.createItem(item.getFieldName(),
                            item.getContentType(), item.isFormField(), item.getName());
                    try {
                        Streams.copy(item.openStream(), fileItem.getOutputStream(), true);
                    } catch (FileUploadIOException e) {
                        throw (FileUploadException) e.getCause();
                    } catch (IOException e) {
                        throw new IOFileUploadException("Processing of " + FileUploadBase.MULTIPART_FORM_DATA
                                + " request failed. " + e.getMessage(), e);
                    }
                    final FileItemHeaders fih = item.getHeaders();
                    fileItem.setHeaders(fih);
                    if (fileItem.getSize() > 0) {
                        files.put(fileItem.getStoreLocation().getName(), fileItem);
                        filesByFieldName.put(fileItem.getFieldName(), fileItem);
                    }
                }
            }
        } catch (FileUploadException ioe) {
            logger.error("Error while initializing FileUpload class:", ioe);
            throw new IOException(ioe.getMessage());
        }
    } else {
        logger.error("FileUpload::init storage path does not exists or can write");
        throw new IOException("FileUpload::init storage path does not exists or cannot write");
    }
}

From source file:org.javalite.activeweb.HttpSupport.java

/**
 * Returns a collection of uploaded files and form fields from a multi-part request.
 * This method uses <a href="http://commons.apache.org/proper/commons-fileupload/apidocs/org/apache/commons/fileupload/disk/DiskFileItemFactory.html">DiskFileItemFactory</a>.
 * As a result, it is recommended to add the following to your web.xml file:
 *
 * <pre>//from  ww  w .j  a va 2  s .  c om
 *   &lt;listener&gt;
 *      &lt;listener-class&gt;
 *         org.apache.commons.fileupload.servlet.FileCleanerCleanup
 *      &lt;/listener-class&gt;
 *   &lt;/listener&gt;
 *</pre>
 *
 * For more information, see: <a href="http://commons.apache.org/proper/commons-fileupload/using.html">Using FileUpload</a>
 *
 * The size of upload defaults to max of 20mb. Files greater than that will be rejected. If you want to accept files
 * smaller of larger, create a file called <code>activeweb.properties</code>, add it to your classpath and
 * place this property to the file:
 *
 * <pre>
 * #max upload size
 * maxUploadSize = 20000000
 * </pre>
 *
 * @param encoding specifies the character encoding to be used when reading the headers of individual part.
 * When not specified, or null, the request encoding is used. If that is also not specified, or null,
 * the platform default encoding is used.
 *
 * @return a collection of uploaded files from a multi-part request.
 */
protected List<FormItem> multipartFormItems(String encoding) {
    //we are thread safe, because controllers are pinned to a thread and discarded after each request.
    if (formItems != null) {
        return formItems;
    }

    HttpServletRequest req = Context.getHttpRequest();

    if (req instanceof AWMockMultipartHttpServletRequest) {//running inside a test, and simulating upload.
        formItems = ((AWMockMultipartHttpServletRequest) req).getFormItems();
    } else {

        if (!ServletFileUpload.isMultipartContent(req))
            throw new ControllerException(
                    "this is not a multipart request, be sure to add this attribute to the form: ... enctype=\"multipart/form-data\" ...");

        DiskFileItemFactory factory = new DiskFileItemFactory();

        factory.setSizeThreshold(Configuration.getMaxUploadSize());
        factory.setRepository(Configuration.getTmpDir());

        ServletFileUpload upload = new ServletFileUpload(factory);
        if (encoding != null)
            upload.setHeaderEncoding(encoding);
        upload.setFileSizeMax(Configuration.getMaxUploadSize());
        try {
            List<org.apache.commons.fileupload.FileItem> apacheFileItems = upload
                    .parseRequest(Context.getHttpRequest());
            formItems = new ArrayList<>();
            for (FileItem apacheItem : apacheFileItems) {
                ApacheFileItemFacade f = new ApacheFileItemFacade(apacheItem);
                if (f.isFormField()) {
                    formItems.add(new FormItem(f));
                } else {
                    formItems.add(new org.javalite.activeweb.FileItem(f));
                }
            }
            return formItems;
        } catch (Exception e) {
            throw new ControllerException(e);
        }
    }
    return formItems;
}

From source file:org.jboss.dashboard.ui.controller.RequestMultipartWrapper.java

/**
 * Constructs a new MultipartRequest to handle the specified request,
 * saving any uploaded files to the given directory, and limiting the
 * upload size to the specified length.//from ww w. j  ava  2  s  .  c o m
 *
 * @param request       the servlet request.
 * @param saveDirectory the directory in which to save any uploaded files.
 * @param maxPostSize   the maximum size of the POST content.
 * @throws IOException if the uploaded content is larger than
 *                     <tt>maxPostSize</tt> or there's a problem reading or parsing the request.
 */
public RequestMultipartWrapper(HttpServletRequest request, String saveDirectory, int maxPostSize,
        String encoding) throws IOException {
    super(request);
    this.privateDir = saveDirectory;
    this.encoding = encoding;

    DiskFileItemFactory factory = new DiskFileItemFactory();

    // factory.setSizeThreshold(yourMaxMemorySize);

    if (privateDir != null) {
        File dir = new File(privateDir);
        if (dir.isDirectory() && dir.canWrite()) {
            factory.setRepository(dir);
        } else {
            log.warn("Directory " + privateDir + " is not valid or permissions to write not granted");
        }
    }

    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setSizeMax(maxPostSize);

    List<FileItem> items = null;
    try {
        items = upload.parseRequest(request);
    } catch (FileUploadException e) {
        throw new IOException("Error parsing multipart in URI" + request.getRequestURI(), e);
    }

    if (items != null) {
        for (FileItem item : items) {
            if (item.isFormField()) {
                addFormField(item);
            } else {
                try {
                    addUploadedFile(item);
                } catch (Exception e) {
                    throw new IOException("Error parsing multipart item " + item.getName(), e);
                }
            }
        }
    }

    Enumeration<String> paramNames = request.getParameterNames();
    while (paramNames.hasMoreElements()) {
        String paramName = paramNames.nextElement();
        List<String> paramValues = Arrays.asList(request.getParameter(paramName));
        requestParameters.put(paramName, paramValues);
    }
}

From source file:org.jbpm.formModeler.service.bb.mvc.controller.RequestMultipartWrapper.java

/**
 * Constructs a new MultipartRequest to handle the specified request,
 * saving any uploaded files to the given directory, and limiting the
 * upload size to the specified length./*from  w w  w .java 2s  .c om*/
 *
 * @param request       the servlet request.
 * @param saveDirectory the directory in which to save any uploaded files.
 * @param maxPostSize   the maximum size of the POST content.
 * @throws java.io.IOException if the uploaded content is larger than
 *                     <tt>maxPostSize</tt> or there's a problem reading or parsing the request.
 */
public RequestMultipartWrapper(HttpServletRequest request, String saveDirectory, int maxPostSize,
        String encoding) throws IOException {
    super(request);
    this.privateDir = saveDirectory;
    this.encoding = encoding;

    DiskFileItemFactory factory = new DiskFileItemFactory();

    // factory.setSizeThreshold(yourMaxMemorySize);

    if (privateDir != null) {
        File dir = new File(privateDir);
        if (dir.isDirectory() && dir.canWrite()) {
            factory.setRepository(dir);
        } else {
            log.warn("Directory " + privateDir + " is not valid or permissions to write not granted");
        }
    }

    ServletFileUpload upload = new ServletFileUpload(factory);

    upload.setSizeMax(maxPostSize);

    List items = null;
    try {
        items = upload.parseRequest(request);
    } catch (FileUploadException e) {
        throw new IOException("Error parsing multipart in URI" + request.getRequestURI(), e);
    }

    if (items != null) {
        Iterator iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();

            if (item.isFormField()) {
                addFormField(item);
            } else {
                try {
                    addUploadedFile(item);
                } catch (Exception e) {
                    throw new IOException("Error parsing multipart item " + item.getName(), e);
                }
            }
        }
    }
}

From source file:org.jessma.util.http.FileUploader.java

private ServletFileUpload getFileUploadComponent() {
    DiskFileItemFactory dif = new DiskFileItemFactory();

    if (factorySizeThreshold != DEFAULT_SIZE_THRESHOLD)
        dif.setSizeThreshold(factorySizeThreshold);
    if (factoryRepository != null)
        dif.setRepository(new File(factoryRepository));
    if (factoryCleaningTracker != null)
        dif.setFileCleaningTracker(factoryCleaningTracker);

    ServletFileUpload sfu = new ServletFileUpload(dif);

    if (sizeMax != NO_LIMIT_SIZE_MAX)
        sfu.setSizeMax(sizeMax);/*from   w  w w .  ja  v a  2  s .  c  om*/
    if (fileSizeMax != NO_LIMIT_FILE_SIZE_MAX)
        sfu.setFileSizeMax(fileSizeMax);
    if (servletHeaderencoding != null)
        sfu.setHeaderEncoding(servletHeaderencoding);
    if (servletProgressListener != null)
        sfu.setProgressListener(servletProgressListener);

    return sfu;
}

From source file:org.kawanfw.file.servlet.ServerFileUploadAction.java

/**
 * //w ww.  j a va 2  s .  com
 * Execute the dispatched request
 * 
 * @param request
 *            the http request
 * @param response
 *            the http response
 * @param servletContextTempDir
 *            The temp dir used by Servlets
 * @param commonsConfigurator
 *            the client login specific class
 * @throws IOException
 */

public void executeAction(HttpServletRequest request, HttpServletResponse response, File servletContextTempDir,
        CommonsConfigurator commonsConfigurator, FileConfigurator fileConfigurator) throws IOException {
    PrintWriter out = response.getWriter();

    try {
        String username = null;
        String token = null;
        String filename = null;
        long chunkLength = 0;

        response.setContentType("text/html");
        // Prepare the response

        // Check that we have a file upload request
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        debug("isMultipart: " + isMultipart);

        if (!isMultipart) {
            return;
        }

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

        debug("servletContextTempDir: " + servletContextTempDir);

        // Create a new file upload handler using the factory
        // that define the secure temp dir
        ServletFileUpload upload = new ServletFileUpload(factory);

        // Parse the request
        FileItemIterator iter = upload.getItemIterator(request);

        // Parse the request
        // List /* FileItem */ items = upload.parseRequest(request);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            String name = item.getFieldName();
            debug("name: " + name);

            // The input Stream for the File
            InputStream stream = item.openStream();

            if (item.isFormField()) {
                if (name.equals(Parameter.USERNAME)) {
                    // username = Streams.asString(stream);
                    username = StreamsEncrypted.asString(stream, commonsConfigurator);

                    // Not sure it's necessary:
                    username = HtmlConverter.fromHtml(username);

                    debug("username: " + username);
                } else if (name.equals(Parameter.TOKEN)) {
                    // token = Streams.asString(stream);
                    token = StreamsEncrypted.asString(stream, commonsConfigurator);
                    debug("token: " + token);
                } else if (name.equals(Parameter.FILENAME)) {
                    // filename = Streams.asString(stream);
                    filename = StreamsEncrypted.asString(stream, commonsConfigurator);
                    debug("filename: " + filename);
                } else if (name.equals(Parameter.CHUNKLENGTH)) {
                    String chunklengthStr = StreamsEncrypted.asString(stream, commonsConfigurator);
                    chunkLength = Long.parseLong(chunklengthStr);
                    debug("chunklengthStr: " + chunklengthStr);
                }
            } else {

                if (!isTokenValid(out, username, token, commonsConfigurator)) // Security
                // check
                {
                    return;
                }

                // Not sure it's necessary:
                filename = HtmlConverter.fromHtml(filename);

                debug("");
                debug("File field " + name + " with file name " + item.getName() + " detected.");
                debug("filename: " + filename);

                new FileTransferManager().upload(fileConfigurator, stream, username, filename, chunkLength);

                out.println(TransferStatus.SEND_OK);
                out.println("OK");

                return;
            }
        }
    } catch (Throwable throwable) {

        Throwable finalThrowable = ServerFileDispatch.getFinalThrowable(throwable);

        out.println(TransferStatus.SEND_FAILED);
        out.println(finalThrowable.getClass().getName());
        out.println(ServerUserThrowable.getMessage(finalThrowable));
        out.println(ExceptionUtils.getStackTrace(finalThrowable)); // stack trace

        try {
            ServerLogger.getLogger().log(Level.WARNING,
                    Tag.PRODUCT_EXCEPTION_RAISED + " " + ServerUserThrowable.getMessage(finalThrowable));
            ServerLogger.getLogger().log(Level.WARNING,
                    Tag.PRODUCT_EXCEPTION_RAISED + " " + ExceptionUtils.getStackTrace(finalThrowable));
        } catch (Exception e1) {
            e1.printStackTrace();
            e1.printStackTrace(System.out);
        }

    }

}

From source file:org.kimios.controller.UploadManager.java

private String startUploadFile(HttpServletRequest req) throws Exception {
    DiskFileItemFactory fp = new DiskFileItemFactory();
    fp.setRepository(new File(ConfigurationManager.getValue(Config.DM_TMP_FILES_PATH)));
    ServletFileUpload sfu = new ServletFileUpload(fp);
    QProgressListener pp = new QProgressListener(uploads);
    sfu.setProgressListener(pp);/*from  ww  w  .ja  va 2s  . c o  m*/
    String uploadId = "";
    String name = "";
    String sec = "";
    String metaValues = "";
    String docTypeUid = "";
    String action = "";
    String documentUid = ""; //used for import
    String newVersion = "";
    boolean isSecurityInherited = false;
    long folderUid = 0;
    String mimeType = "";
    String extension = "";
    FileItemIterator t = sfu.getItemIterator(req);
    while (t.hasNext()) {

        FileItemStream st = t.next();
        if (st.isFormField()) {
            String tmpVal = Streams.asString(st.openStream(), "UTF-8");
            log.debug(st.getFieldName() + " --> " + tmpVal);
            if (st.getFieldName().equalsIgnoreCase("actionUpload")) {
                action = tmpVal;
            }
            if (st.getFieldName().equalsIgnoreCase("newVersion")) {
                newVersion = tmpVal;
            }
            if (st.getFieldName().equalsIgnoreCase("documentUid")) {
                documentUid = tmpVal;
            }
            if (st.getFieldName().equalsIgnoreCase("UPLOAD_ID")) {
                uploadId = tmpVal;
                pp.setUploadId(uploadId);
            }
            if (st.getFieldName().equalsIgnoreCase("name")) {
                name = tmpVal;
            }
            if (st.getFieldName().equalsIgnoreCase("sec")) {
                sec = StringEscapeUtils.unescapeHtml(tmpVal);
            }
            if (st.getFieldName().equalsIgnoreCase("documentTypeUid")) {
                docTypeUid = tmpVal;
            }
            if (st.getFieldName().equalsIgnoreCase("metaValues")) {
                metaValues = StringEscapeUtils.unescapeHtml(tmpVal);
            }
            if (st.getFieldName().equalsIgnoreCase("folderUid")) {
                folderUid = Long.parseLong(tmpVal);
            }
            if (st.getFieldName().equalsIgnoreCase("inheritedPermissions")) {
                isSecurityInherited = (tmpVal != null && tmpVal.equalsIgnoreCase("on"));
            }
        } else {
            InputStream in = st.openStream();
            mimeType = st.getContentType();
            extension = st.getName().substring(st.getName().lastIndexOf('.') + 1);
            int transferChunkSize = Integer.parseInt(ConfigurationManager.getValue(Config.DM_CHUNK_SIZE));

            if (action.equalsIgnoreCase("AddDocument")) {
                Document d = new Document();
                d.setCreationDate(Calendar.getInstance());
                d.setExtension(extension);
                d.setFolderUid(folderUid);
                d.setCheckedOut(false);
                d.setMimeType(mimeType);
                d.setName(name);
                d.setOwner("");
                d.setUid(-1);
                long docUid = documentController.createDocument(sessionUid, d, isSecurityInherited);
                if (!isSecurityInherited) {
                    securityController.updateDMEntitySecurities(sessionUid, docUid, 3, false,
                            DMEntitySecuritiesParser.parseFromJson(sec, docUid, 3));
                }

                fileTransferController.uploadFileFirstVersion(sessionUid, docUid, in, false);
                long documentTypeUid = -1;
                try {
                    documentTypeUid = Long.parseLong(docTypeUid);
                } catch (Exception e) {
                }
                if (documentTypeUid > 0) {
                    Map<Meta, String> mMetasValues = DMEntitySecuritiesParser
                            .parseMetasValuesFromJson(sessionUid, metaValues, documentVersionController);
                    String xmlMeta = XMLGenerators.getMetaDatasDocumentXMLDescriptor(mMetasValues,
                            "MM/dd/yyyy");
                    documentVersionController.updateDocumentVersion(sessionUid, docUid, documentTypeUid,
                            xmlMeta);
                }
            } else {

                if (action.equalsIgnoreCase("Import")) {
                    documentController.checkoutDocument(sessionUid, Long.parseLong(documentUid));
                    fileTransferController.uploadFileNewVersion(sessionUid, Long.parseLong(documentUid), in,
                            false);
                    documentController.checkinDocument(sessionUid, Long.parseLong(documentUid));
                } else if (action.equalsIgnoreCase("UpdateCurrent")) {
                    documentController.checkoutDocument(sessionUid, Long.parseLong(documentUid));
                    fileTransferController.uploadFileUpdateVersion(sessionUid, Long.parseLong(documentUid), in,
                            false);
                    documentController.checkinDocument(sessionUid, Long.parseLong(documentUid));
                }
            }

        }
    }
    return "{success: true}";
}

From source file:org.ldp4j.apps.ldp4ro.servlets.FileUploaderServlet.java

private ServletFileUpload getFileItemFactory() {

    Config config = ConfigManager.getAppConfig();

    // configures upload settings
    DiskFileItemFactory factory = new DiskFileItemFactory();
    // sets memory threshold - beyond which files are stored in disk
    factory.setSizeThreshold(config.getInt(MEMORY_THRESHOULD));

    // sets temporary location to store files
    File tempUploadDir = new File(System.getProperty("java.io.tmpdir"));
    if (!tempUploadDir.exists()) {
        tempUploadDir.mkdir();//from ww w.ja  v  a  2  s.  c om
    }
    factory.setRepository(tempUploadDir);

    ServletFileUpload upload = new ServletFileUpload(factory);

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

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

    return upload;

}