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:com.googlecode.example.FileUploadServlet.java

@Override
@SuppressWarnings({ "unchecked" })
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    logger.debug("Processing request...");
    if (isMultipartContent(request)) {
        String storageRoot = request.getSession().getServletContext().getRealPath(STORAGE_ROOT);
        File dirPath = new File(storageRoot);
        if (!dirPath.exists()) {
            if (dirPath.mkdirs()) {
                logger.debug("Storage directories created successfully.");
            }//from  w ww  .j a v a 2  s  . co  m
        }
        PrintWriter writer = response.getWriter();
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(UPLOAD_SIZE);
        factory.setRepository(dirPath);
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(UPLOAD_SIZE);
        try {
            List<FileItem> items = upload.parseRequest(request);
            for (FileItem item : items) {
                if (!item.isFormField()) {
                    File file = new File(new StringBuilder(storageRoot).append("/")
                            .append(getName(item.getName())).toString());
                    logger.debug("Writing file to: {}", file.getCanonicalPath());
                    item.write(file);
                }
            }
            response.setStatus(SC_OK);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            response.setStatus(SC_INTERNAL_SERVER_ERROR);
        }
        writer.flush();
    }
}

From source file:kreidos.diamond.web.action.console.NewDocumentAction.java

@SuppressWarnings("rawtypes")
public WebView execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
    HttpSession session = request.getSession();
    User loggedInUser = (User) session.getAttribute(HTTPConstants.SESSION_KRYSTAL);
    String classId = request.getParameter("classid") != null ? request.getParameter("classid") : "0";

    if (request.getMethod().equalsIgnoreCase("POST")) {
        try {//from  w  ww  .  java 2  s .co  m
            String userName = loggedInUser.getUserName();
            String tempFilePath = System.getProperty("java.io.tmpdir");

            if (!(tempFilePath.endsWith("/") || tempFilePath.endsWith("\\"))) {
                tempFilePath += System.getProperty("file.separator");
            }

            //variables
            String fileName = "", comments = "";
            File file = null;
            // Create a factory for disk-based file items
            FileItemFactory factory = new DiskFileItemFactory();
            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);
            upload.setHeaderEncoding(HTTPConstants.CHARACTER_ENCODING);

            //Create a file upload progress listener
            FileUploadProgressListener listener = new FileUploadProgressListener();
            upload.setProgressListener(listener);
            //put the listener in session
            session.setAttribute("LISTENER", listener);
            session.setAttribute("UPLOAD_ERROR", null);
            session.setAttribute("UPLOAD_PERCENT_COMPLETE", new Long(0));

            DocumentClass documentClass = null;

            Hashtable<String, String> indexRecord = new Hashtable<String, String>();
            String name = "";
            String value = "";

            List listItems = upload.parseRequest((HttpServletRequest) request);

            Iterator iter = listItems.iterator();
            FileItem fileItem = null;
            while (iter.hasNext()) {
                fileItem = (FileItem) iter.next();
                if (fileItem.isFormField()) {
                    name = fileItem.getFieldName();
                    value = fileItem.getString(HTTPConstants.CHARACTER_ENCODING);
                    if (name.equals("classid")) {
                        classId = value;
                    }
                    if (name.equals("txtNote")) {
                        comments = value;
                    }
                } else {
                    try {
                        fileName = fileItem.getName();
                        file = new File(fileName);
                        fileName = file.getName();
                        file = new File(tempFilePath + fileName);
                        fileItem.write(file);
                    } catch (Exception ex) {
                        session.setAttribute("UPLOAD_ERROR", ex.getLocalizedMessage());
                        return null;
                    }
                }
            } //if

            if (file.length() <= 0) { //code for checking minimum size of file
                session.setAttribute("UPLOAD_ERROR", "Zero length document");
                return null;
            }
            documentClass = DocumentClassDAO.getInstance().readDocumentClassById(Integer.parseInt(classId));
            if (documentClass == null) {
                session.setAttribute("UPLOAD_ERROR", "Invalid document class");
                return null;
            }
            AccessControlManager aclManager = new AccessControlManager();
            ACL acl = aclManager.getACL(documentClass, loggedInUser);

            if (!acl.canCreate()) {
                session.setAttribute("UPLOAD_ERROR", "Access Denied");
                return null;
            }

            String indexValue = "";
            String indexName = "";
            session.setAttribute("UPLOAD_PERCENT_COMPLETE", new Long(50));

            for (IndexDefinition indexDefinition : documentClass.getIndexDefinitions()) {
                indexName = indexDefinition.getIndexColumnName();
                Iterator iter1 = listItems.iterator();
                while (iter1.hasNext()) {
                    FileItem item1 = (FileItem) iter1.next();
                    if (item1.isFormField()) {
                        name = item1.getFieldName();
                        value = item1.getString(HTTPConstants.CHARACTER_ENCODING);
                        if (name.equals(indexName)) {
                            indexValue = value;
                            String errorMessage = "";
                            if (indexValue != null) {
                                if (indexDefinition.isMandatory()) {
                                    if (indexValue.trim().length() <= 0) {
                                        errorMessage = "Invalid input for "
                                                + indexDefinition.getIndexDisplayName();
                                        session.setAttribute("UPLOAD_ERROR", errorMessage);
                                        return null;
                                    }
                                }
                                if (IndexDefinition.INDEXTYPE_NUMBER
                                        .equalsIgnoreCase(indexDefinition.getIndexType())) {
                                    if (indexValue.trim().length() > 0) {
                                        if (!GenericValidator.matchRegexp(indexValue,
                                                HTTPConstants.NUMERIC_REGEXP)) {
                                            errorMessage = "Invalid input for "
                                                    + indexDefinition.getIndexDisplayName();
                                            session.setAttribute("UPLOAD_ERROR", errorMessage);
                                            return null;
                                        }
                                    }
                                } else if (IndexDefinition.INDEXTYPE_DATE
                                        .equalsIgnoreCase(indexDefinition.getIndexType())) {
                                    if (indexValue.trim().length() > 0) {
                                        if (!GenericValidator.isDate(indexValue, "yyyy-MM-dd", true)) {
                                            errorMessage = "Invalid input for "
                                                    + indexDefinition.getIndexDisplayName();
                                            session.setAttribute("UPLOAD_ERROR", errorMessage);
                                            return null;
                                        }
                                    }
                                }
                                if (indexValue.trim().length() > indexDefinition.getIndexMaxLength()) { //code for checking index field length
                                    errorMessage = "Document index size exceeded for " + "Index Name : "
                                            + indexDefinition.getIndexDisplayName() + " [ " + "Index Length : "
                                            + indexDefinition.getIndexMaxLength() + " , " + "Actual Length : "
                                            + indexValue.length() + " ]";
                                    session.setAttribute("UPLOAD_ERROR", errorMessage);
                                    return null;
                                }
                            }
                            indexRecord.put(indexName, indexValue);
                        }
                    }
                } //while iter
            } //while indexCfgList
            session.setAttribute("UPLOAD_PERCENT_COMPLETE", new Long(70));

            DocumentRevision documentRevision = new DocumentRevision();
            documentRevision.setClassId(documentClass.getClassId());
            documentRevision.setDocumentId(0);
            documentRevision.setRevisionId("1.0");
            documentRevision.setDocumentFile(file);
            documentRevision.setUserName(loggedInUser.getUserName());
            documentRevision.setIndexRecord(indexRecord);
            documentRevision.setComments(comments);

            DocumentManager documentManager = new DocumentManager();
            documentManager.storeDocument(documentRevision, documentClass);

            //Log the entry to audit logs 
            AuditLogManager.log(new AuditLogRecord(documentRevision.getDocumentId(),
                    AuditLogRecord.OBJECT_DOCUMENT, AuditLogRecord.ACTION_CREATED, userName,
                    request.getRemoteAddr(), AuditLogRecord.LEVEL_INFO, "", "Document created"));

            session.setAttribute("UPLOAD_PERCENT_COMPLETE", new Long(100));
        } catch (Exception e) {
            e.printStackTrace(System.out);
        }
        return null;
    } else {
        try {
            ArrayList<DocumentClass> availableDocumentClasses = DocumentClassDAO.getInstance()
                    .readDocumentClasses(" ACTIVE = 'Y'");
            ArrayList<DocumentClass> documentClasses = new ArrayList<DocumentClass>();
            AccessControlManager aclManager = new AccessControlManager();
            for (DocumentClass documentClass : availableDocumentClasses) {
                ACL acl = aclManager.getACL(documentClass, loggedInUser);
                if (acl.canCreate()) {
                    documentClasses.add(documentClass);
                }
            }
            int documentClassId = 0;
            try {
                documentClassId = Integer.parseInt(classId);
            } catch (Exception ex) {
                request.setAttribute(HTTPConstants.REQUEST_ERROR, "Invalid input");
                return (new NewDocumentView(request, response));
            }
            if (documentClassId > 0) {
                DocumentClass selectedDocumentClass = DocumentClassDAO.getInstance()
                        .readDocumentClassById(documentClassId);
                request.setAttribute("DOCUMENTCLASS", selectedDocumentClass);
            }
            request.setAttribute("CLASSID", documentClassId);
            request.setAttribute("CLASSLIST", documentClasses);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    return (new NewDocumentView(request, response));
}

From source file:edu.byui.fb.AddImage.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*from w  w  w  .  j  a  va  2  s .  co  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 {
    // Get the DataBaseHandler
    DataBaseHandler dbh = DataBaseHandler.getInstance();

    // Get information about the user currently logged in
    boolean logged = (boolean) request.getSession().getAttribute("logged");
    String username = (String) request.getSession().getAttribute("username");
    User user = dbh.getUser(username);

    // Are we currently logged in
    if (username != null && user != null && logged) {
        // Check to make sure the request is multipart
        if (ServletFileUpload.isMultipartContent(request)) {
            try {
                // Parse the request into FileItems
                List<FileItem> multipart = new ServletFileUpload(new DiskFileItemFactory())
                        .parseRequest(request);
                String title = "";
                InputStream imageInputStream = null;

                // Loop through each item
                for (FileItem item : multipart) {
                    // Are we dealing with a file or something different
                    if (!item.isFormField()) {
                        if (item.getFieldName().equals("image")) {
                            imageInputStream = item.getInputStream();
                        }
                    } else if (item.isFormField()) {
                        if (item.getFieldName().equals("title")) {
                            title = item.getString();
                        }
                    }
                }

                // Was there a title? If not, give a fake title
                if (title.equals("")) {
                    title = "No title";
                }

                // Set up the image and add to the DataBase.
                Image image = new Image(title, imageInputStream);
                dbh.addImage(image, user);
                request.setAttribute("imageAdded", true);
            } catch (FileUploadException ex) {
                Logger.getLogger(AddImage.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    } else {
        // Was there an error?
        request.setAttribute("addedError", true);
    }

    // Go to admin.jsp
    request.getRequestDispatcher("LoadImages?dest=admin.jsp").forward(request, response);
}

From source file:fr.insalyon.creatis.vip.datamanager.server.rpc.FileUploadServiceImpl.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    User user = (User) request.getSession().getAttribute(CoreConstants.SESSION_USER);
    if (user != null && ServletFileUpload.isMultipartContent(request)) {

        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        try {//w  w  w.j ava 2  s. c  o  m
            List items = upload.parseRequest(request);
            Iterator iter = items.iterator();
            String fileName = null;
            FileItem fileItem = null;
            String path = null;
            String target = "uploadComplete";
            String operationID = "no-id";

            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();

                if (item.getFieldName().equals("path")) {
                    path = item.getString();
                } else if (item.getFieldName().equals("file")) {
                    fileName = item.getName();
                    fileItem = item;
                } else if (item.getFieldName().equals("target")) {
                    target = item.getString();
                }
            }
            if (fileName != null && !fileName.equals("")) {

                boolean local = path.equals("local") ? true : false;
                String rootDirectory = DataManagerUtil.getUploadRootDirectory(local);
                fileName = new File(fileName).getName().trim().replaceAll(" ", "_");
                fileName = Normalizer.normalize(fileName, Normalizer.Form.NFD)
                        .replaceAll("\\p{InCombiningDiacriticalMarks}+", "");
                File uploadedFile = new File(rootDirectory + fileName);

                try {
                    fileItem.write(uploadedFile);
                    response.getWriter().write(fileName);

                    if (!local) {
                        // GRIDA Pool Client
                        logger.info("(" + user.getEmail() + ") Uploading '" + uploadedFile.getAbsolutePath()
                                + "' to '" + path + "'.");
                        GRIDAPoolClient client = CoreUtil.getGRIDAPoolClient();
                        operationID = client.uploadFile(uploadedFile.getAbsolutePath(),
                                DataManagerUtil.parseBaseDir(user, path), user.getEmail());

                    } else {
                        operationID = fileName;
                        logger.info(
                                "(" + user.getEmail() + ") Uploaded '" + uploadedFile.getAbsolutePath() + "'.");
                    }
                } catch (Exception ex) {
                    logger.error(ex);
                }
            }

            response.setContentType("text/html");
            response.setHeader("Pragma", "No-cache");
            response.setDateHeader("Expires", 0);
            response.setHeader("Cache-Control", "no-cache");
            PrintWriter out = response.getWriter();
            out.println("<html>");
            out.println("<body>");
            out.println("<script type=\"text/javascript\">");
            out.println("if (parent." + target + ") parent." + target + "('" + operationID + "');");
            out.println("</script>");
            out.println("</body>");
            out.println("</html>");
            out.flush();

        } catch (FileUploadException ex) {
            logger.error(ex);
        }
    }
}

From source file:com.axway.ats.testexplorer.pages.testcase.attachments.AttachmentsServlet.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    Object checkContextAttribute = request.getSession().getServletContext()
            .getAttribute(ContextListener.getAttachedFilesDir());
    // check if ats-attached-files property is set
    if (checkContextAttribute == null) {
        LOG.error(//from ww  w  .  ja  va 2 s .c  o  m
                "No attached files could be attached. \nPossible reason could be Tomcat 'CATALINA_HOME' or 'CATALINA_BASE' is not set.");
    } else {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        // Check that we have a file upload request
        if (!ServletFileUpload.isMultipartContent(request)) {
            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;
        }

        repoFilesDir = checkContextAttribute.toString();
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);
        // fileitem containing information about the attached file
        FileItem fileItem = null;
        FileItem currentElement = null;
        String dbName = "";
        String attachedFile = "";
        int runId = 0;
        int suiteId = 0;
        int testcaseId = 0;

        try {
            // Parse the request to get file items.
            List<?> fileItems = upload.parseRequest(request);
            // Process the uploaded file items
            Iterator<?> i = fileItems.iterator();
            while (i.hasNext()) {
                currentElement = (FileItem) i.next();
                // check if this is the attached file
                if ("upfile".equals(currentElement.getFieldName())) {
                    fileItem = currentElement;
                    attachedFile = getFileSimpleName(fileItem.getName());
                    if (attachedFile == null) {
                        break;
                    }
                } else if ("dbName".equals(currentElement.getFieldName())) {
                    if (!StringUtils.isNullOrEmpty(currentElement.getString()))
                        dbName = currentElement.getString();
                } else if ("runId".equals(currentElement.getFieldName())) {
                    runId = getIntValue(currentElement.getString());
                } else if ("suiteId".equals(currentElement.getFieldName())) {
                    suiteId = getIntValue(currentElement.getString());
                } else if ("testcaseId".equals(currentElement.getFieldName())) {
                    testcaseId = getIntValue(currentElement.getString());
                }
            }
            // check if all values are valid
            if (!StringUtils.isNullOrEmpty(attachedFile) && !StringUtils.isNullOrEmpty(dbName) && runId > 0
                    && suiteId > 0 && testcaseId > 0) {
                // copy the attached file to the corresponding directory
                File file = createAttachedFileDir(attachedFile, dbName, runId, suiteId, testcaseId);
                fileItem.write(file);
                out.println("File uploaded to testcase " + testcaseId);
            } else {
                StringBuilder sb = new StringBuilder();
                if (StringUtils.isNullOrEmpty(attachedFile)) {
                    sb.append("Attached file name is null or empty!");
                    out.println(sb.toString());
                }
                if (StringUtils.isNullOrEmpty(dbName)) {
                    sb.append("Database name is null of empty!");
                    out.println(sb.toString());
                }
                if (runId <= 0) {
                    sb.append("RunId \"" + runId + "\" is not valid!");
                    out.println(sb.toString());
                }
                if (suiteId <= 0) {
                    sb.append("SuiteId \"" + suiteId + "\" is not valid!");
                    out.println(sb.toString());
                }
                if (testcaseId <= 0) {
                    sb.append("TestcaseId \"" + testcaseId + "\" is not valid!");
                    out.println(sb.toString());
                }
                response.sendError(HttpServletResponse.SC_CONFLICT, sb.toString());
                LOG.error("The file could not be attached to the test!");
            }
        } catch (Exception ex) {
            String errMsg = ex.getMessage();
            if (errMsg == null) {
                errMsg = ex.getClass().getSimpleName();
            }
            response.sendError(HttpServletResponse.SC_CONFLICT, ExceptionUtils.getExceptionMsg(ex));
            LOG.error("The file was unable to be attached to the testcase! ", ex);
        } finally {
            out.close();
        }
    }
}

From source file:com.liferay.faces.metal.component.inputfile.internal.InputFileDecoderCommonsImpl.java

@Override
public Map<String, List<UploadedFile>> decode(FacesContext facesContext, String location) {

    Map<String, List<UploadedFile>> uploadedFileMap = null;
    ExternalContext externalContext = facesContext.getExternalContext();
    String uploadedFilesFolder = getUploadedFilesFolder(externalContext, location);

    // Using the sessionId, determine a unique folder path and create the path if it does not exist.
    String sessionId = getSessionId(externalContext);

    // FACES-1452: Non-alpha-numeric characters must be removed order to ensure that the folder will be
    // created properly.
    sessionId = sessionId.replaceAll("[^A-Za-z0-9]", " ");

    File uploadedFilesPath = new File(uploadedFilesFolder, sessionId);

    if (!uploadedFilesPath.exists()) {
        uploadedFilesPath.mkdirs();/* w w w.  ja  v  a 2 s .  co m*/
    }

    // Initialize commons-fileupload with the file upload path.
    DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
    diskFileItemFactory.setRepository(uploadedFilesPath);

    // Initialize commons-fileupload so that uploaded temporary files are not automatically deleted.
    diskFileItemFactory.setFileCleaningTracker(null);

    // Initialize the commons-fileupload size threshold to zero, so that all files will be dumped to disk
    // instead of staying in memory.
    diskFileItemFactory.setSizeThreshold(0);

    // Determine the max file upload size threshold (in bytes).
    int uploadedFileMaxSize = WebConfigParam.UploadedFileMaxSize.getIntegerValue(externalContext);

    // Parse the request parameters and save all uploaded files in a map.
    ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
    servletFileUpload.setFileSizeMax(uploadedFileMaxSize);
    uploadedFileMap = new HashMap<String, List<UploadedFile>>();

    UploadedFileFactory uploadedFileFactory = (UploadedFileFactory) FactoryExtensionFinder
            .getFactory(UploadedFileFactory.class);

    // Begin parsing the request for file parts:
    try {
        FileItemIterator fileItemIterator = null;

        HttpServletRequest httpServletRequest = (HttpServletRequest) externalContext.getRequest();
        fileItemIterator = servletFileUpload.getItemIterator(httpServletRequest);

        if (fileItemIterator != null) {

            int totalFiles = 0;

            // For each field found in the request:
            while (fileItemIterator.hasNext()) {

                try {
                    totalFiles++;

                    // Get the stream of field data from the request.
                    FileItemStream fieldStream = (FileItemStream) fileItemIterator.next();

                    // Get field name from the field stream.
                    String fieldName = fieldStream.getFieldName();

                    // Get the content-type, and file-name from the field stream.
                    String contentType = fieldStream.getContentType();
                    boolean formField = fieldStream.isFormField();

                    String fileName = null;

                    try {
                        fileName = fieldStream.getName();
                    } catch (InvalidFileNameException e) {
                        fileName = e.getName();
                    }

                    // Copy the stream of file data to a temporary file. NOTE: This is necessary even if the
                    // current field is a simple form-field because the call below to diskFileItem.getString()
                    // will fail otherwise.
                    DiskFileItem diskFileItem = (DiskFileItem) diskFileItemFactory.createItem(fieldName,
                            contentType, formField, fileName);
                    Streams.copy(fieldStream.openStream(), diskFileItem.getOutputStream(), true);

                    // If the current field is a file, then
                    if (!diskFileItem.isFormField()) {

                        // Get the location of the temporary file that was copied from the request.
                        File tempFile = diskFileItem.getStoreLocation();

                        // If the copy was successful, then
                        if (tempFile.exists()) {

                            // Copy the commons-fileupload temporary file to a file in the same temporary
                            // location, but with the filename provided by the user in the upload. This has two
                            // benefits: 1) The temporary file will have a nice meaningful name. 2) By copying
                            // the file, the developer can have access to a semi-permanent file, because the
                            // commmons-fileupload DiskFileItem.finalize() method automatically deletes the
                            // temporary one.
                            String tempFileName = tempFile.getName();
                            String tempFileAbsolutePath = tempFile.getAbsolutePath();

                            String copiedFileName = stripIllegalCharacters(fileName);

                            String copiedFileAbsolutePath = tempFileAbsolutePath.replace(tempFileName,
                                    copiedFileName);
                            File copiedFile = new File(copiedFileAbsolutePath);
                            FileUtils.copyFile(tempFile, copiedFile);

                            // If present, build up a map of headers.
                            Map<String, List<String>> headersMap = new HashMap<String, List<String>>();
                            FileItemHeaders fileItemHeaders = fieldStream.getHeaders();

                            if (fileItemHeaders != null) {
                                Iterator<String> headerNameItr = fileItemHeaders.getHeaderNames();

                                if (headerNameItr != null) {

                                    while (headerNameItr.hasNext()) {
                                        String headerName = headerNameItr.next();
                                        Iterator<String> headerValuesItr = fileItemHeaders
                                                .getHeaders(headerName);
                                        List<String> headerValues = new ArrayList<String>();

                                        if (headerValuesItr != null) {

                                            while (headerValuesItr.hasNext()) {
                                                String headerValue = headerValuesItr.next();
                                                headerValues.add(headerValue);
                                            }
                                        }

                                        headersMap.put(headerName, headerValues);
                                    }
                                }
                            }

                            // Put a valid UploadedFile instance into the map that contains all of the
                            // uploaded file's attributes, along with a successful status.
                            Map<String, Object> attributeMap = new HashMap<String, Object>();
                            String id = Long.toString(((long) hashCode()) + System.currentTimeMillis());
                            String message = null;
                            UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(
                                    copiedFileAbsolutePath, attributeMap, diskFileItem.getCharSet(),
                                    diskFileItem.getContentType(), headersMap, id, message, fileName,
                                    diskFileItem.getSize(), UploadedFile.Status.FILE_SAVED);

                            addUploadedFile(uploadedFileMap, fieldName, uploadedFile);
                            logger.debug("Received uploaded file fieldName=[{0}] fileName=[{1}]", fieldName,
                                    fileName);
                        } else {

                            if ((fileName != null) && (fileName.trim().length() > 0)) {
                                Exception e = new IOException("Failed to copy the stream of uploaded file=["
                                        + fileName
                                        + "] to a temporary file (possibly a zero-length uploaded file)");
                                UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e);
                                addUploadedFile(uploadedFileMap, fieldName, uploadedFile);
                            }
                        }
                    }
                } catch (Exception e) {
                    logger.error(e);

                    UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e);
                    String fieldName = Integer.toString(totalFiles);
                    addUploadedFile(uploadedFileMap, fieldName, uploadedFile);
                }
            }
        }
    }

    // If there was an error in parsing the request for file parts, then put a bogus UploadedFile instance in
    // the map so that the developer can have some idea that something went wrong.
    catch (Exception e) {
        logger.error(e);

        UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e);
        addUploadedFile(uploadedFileMap, "unknown", uploadedFile);
    }

    return uploadedFileMap;
}

From source file:it.unisa.tirocinio.servlet.studentUploadFiles.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//  ww w.j  a  v  a 2s  . c  om
 *
 * @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");
    response.setHeader("Access-Control-Allow-Origin", "*");
    PrintWriter out = response.getWriter();
    HttpSession aSession = request.getSession();
    try {
        Person pers = (Person) aSession.getAttribute("person");
        String primaryKey = pers.getAccount().getEmail();
        PersonManager aPerson = PersonManager.getInstance();
        Person person = aPerson.getStudent(primaryKey);
        ConcreteStudentInformation aStudentInformation = ConcreteStudentInformation.getInstance();
        out = response.getWriter();

        String studentSubfolderPath = filePath + "/" + reverseSerialNumber(person.getMatricula());
        File subfolderFile = new File(studentSubfolderPath);
        if (!subfolderFile.exists()) {
            subfolderFile.mkdir();
        }

        isMultipart = ServletFileUpload.isMultipartContent(request);
        String serialNumber = null;
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List fileItems = upload.parseRequest(request);
        Iterator i = fileItems.iterator();
        File fileToStore = null;
        String CVPath = "", ATPath = "";

        while (i.hasNext()) {

            FileItem fi = (FileItem) i.next();
            if (!fi.isFormField()) {
                // Get the uploaded file parameters
                String fieldName = fi.getFieldName();
                String fileName = fi.getName();
                if (fieldName.equals("cv")) {
                    fileToStore = new File(studentSubfolderPath + "/" + "CV.pdf");
                    CVPath = fileToStore.getAbsolutePath();
                } else if (fieldName.equals("doc")) {
                    fileToStore = new File(studentSubfolderPath + "/" + "ES.pdf");
                    ATPath = fileToStore.getAbsolutePath();
                }
                fi.write(fileToStore);

                // out.println("Uploaded Filename: " + fieldName + "<br>");
            } else {
                //out.println("It's not formfield");
                //out.println(fi.getString());

            }

        }

        if (aStudentInformation.startTrainingRequest(person.getSsn(), CVPath, ATPath)) {
            message.setMessage("status", 1);
        } else {
            message.setMessage("status", 0);
        }
        aSession.setAttribute("message", message);
        response.sendRedirect(request.getContextPath() + "/tirocinio/studente/tprichiestatirocinio.jsp");
        //RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/tirocinio/studente/tprichiestatirocinio.jsp");
        //dispatcher.forward(request,response);
    } catch (Exception ex) {
        Logger.getLogger(studentUploadFiles.class.getName()).log(Level.SEVERE, null, ex);
        message.setMessage("status", -1);
        aSession.setAttribute("message", message);
    } finally {
        out.close();
    }
}

From source file:com.manning.cmis.theblend.servlets.AddVersionServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response, Session session)
        throws ServletException, IOException, TheBlendException {

    // check for multipart content
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (!isMultipart) {
        // show add version page
        dispatch("addversion.jsp", "Add new version. The Blend.", request, response);
    }//  w w w.j  ava2s.  c  o  m

    Map<String, Object> properties = new HashMap<String, Object>();
    File uploadedFile = null;
    String docId = null;
    boolean major = true;
    ObjectId newId = null;

    // process the request
    try {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(50 * 1024 * 1024);

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

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

            if (item.isFormField()) {
                String name = item.getFieldName();

                if (PARAM_DOC_ID.equalsIgnoreCase(name)) {
                    docId = item.getString();
                } else if (PARAM_MAJOR.equalsIgnoreCase(name)) {
                    major = Boolean.parseBoolean(item.getString());
                }
            } else {
                properties.put(PropertyIds.NAME, item.getName());

                uploadedFile = File.createTempFile("blend", "tmp");
                item.write(uploadedFile);
            }
        }
    } catch (Exception e) {
        throw new TheBlendException("Upload failed: " + e, e);
    }

    if (uploadedFile == null) {
        throw new TheBlendException("No content!", null);
    }

    try {
        // find the document
        Document doc = CMISHelper.getDocumet(session, docId, CMISHelper.LIGHT_OPERATION_CONTEXT, "document");

        // check out document and get Private Working Copy
        Document pwc = null;
        try {
            // check out
            ObjectId pwcId = doc.checkOut();

            // the PWC must be a document object
            pwc = (Document) session.getObject(pwcId, CMISHelper.LIGHT_OPERATION_CONTEXT);
        } catch (CmisBaseException cbe) {
            throw new TheBlendException("Checkout failed!", cbe);
        }

        // prepare the content stream
        ContentStream contentStream = null;
        try {
            contentStream = prepareContentStream(session, uploadedFile, doc.getType().getId(), properties);
        } catch (Exception e) {
            throw new TheBlendException("Upload failed: " + e, e);
        }

        // create new version
        try {
            newId = pwc.checkIn(major, properties, contentStream, null);
        } catch (CmisBaseException cbe) {
            throw new TheBlendException("Could not create new version: " + cbe.getMessage(), cbe);
        } finally {
            try {
                contentStream.getStream().close();
            } catch (IOException ioe) {
                // ignore
            }
        }
    } finally {
        // delete temp file
        uploadedFile.delete();
    }

    // show the newly created document
    redirect(HTMLHelper.encodeUrlWithId(request, "show", newId.getId()), request, response);
}

From source file:com.openkm.extension.servlet.ZohoFileUploadServlet.java

@SuppressWarnings("unchecked")
protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    log.info("service({}, {})", request, response);
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    InputStream is = null;//  w w  w  .ja v a2  s. com
    String id = "";

    if (isMultipart) {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setHeaderEncoding("UTF-8");

        // Parse the request and get all parameters and the uploaded file
        List<FileItem> items;

        try {
            items = upload.parseRequest(request);
            for (Iterator<FileItem> it = items.iterator(); it.hasNext();) {
                FileItem item = it.next();
                if (item.isFormField()) {
                    // if (item.getFieldName().equals("format")) { format =
                    // item.getString("UTF-8"); }
                    if (item.getFieldName().equals("id")) {
                        id = item.getString("UTF-8");
                    }
                    // if (item.getFieldName().equals("filename")) {
                    // filename = item.getString("UTF-8"); }
                } else {
                    is = item.getInputStream();
                }
            }

            // Retrieve token
            ZohoToken zot = ZohoTokenDAO.findByPk(id);

            // Save document
            if (Config.REPOSITORY_NATIVE) {
                String sysToken = DbSessionManager.getInstance().getSystemToken();
                String path = OKMRepository.getInstance().getNodePath(sysToken, zot.getNode());
                new DbDocumentModule().checkout(sysToken, path, zot.getUser());
                new DbDocumentModule().checkin(sysToken, path, is, "Modified from Zoho", zot.getUser());
            } else {
                String sysToken = JcrSessionManager.getInstance().getSystemToken();
                String path = OKMRepository.getInstance().getNodePath(sysToken, zot.getNode());
                new JcrDocumentModule().checkout(sysToken, path, zot.getUser());
                new JcrDocumentModule().checkin(sysToken, path, is, "Modified from Zoho", zot.getUser());
            }
        } catch (FileUploadException e) {
            log.error(e.getMessage(), e);
        } catch (PathNotFoundException e) {
            log.error(e.getMessage(), e);
        } catch (RepositoryException e) {
            log.error(e.getMessage(), e);
        } catch (DatabaseException e) {
            log.error(e.getMessage(), e);
        } catch (FileSizeExceededException e) {
            log.error(e.getMessage(), e);
        } catch (UserQuotaExceededException e) {
            log.error(e.getMessage(), e);
        } catch (VirusDetectedException e) {
            log.error(e.getMessage(), e);
        } catch (VersionException e) {
            log.error(e.getMessage(), e);
        } catch (LockException e) {
            log.error(e.getMessage(), e);
        } catch (AccessDeniedException e) {
            log.error(e.getMessage(), e);
        } catch (ExtensionException e) {
            log.error(e.getMessage(), e);
        } catch (AutomationException e) {
            log.error(e.getMessage(), e);
        } finally {
            IOUtils.closeQuietly(is);
        }
    }
}

From source file:Controller.ProsesRegis.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    try {/*w w w.jav a  2s .co m*/
        /* TODO output your page here. You may use following sample code. */
        boolean isMultiPart = ServletFileUpload.isMultipartContent(request);
        if (isMultiPart) {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List items = upload.parseRequest(request);
            Iterator<FileItem> iter = items.iterator();
            while (iter.hasNext()) {
                FileItem fileItem = iter.next();
                if (fileItem.isFormField()) {
                    processFormField(fileItem);
                } else {
                    flItem = fileItem;
                }
            }
            try {
                Photo = flItem.getName();
                File savedFile = new File(
                        "D:\\Latihan Java\\web\\AplikasiPMB\\web\\backend\\images_student\\" + Photo);
                flItem.write(savedFile);
            } catch (Exception e) {
                out.println(e);
                System.out.println(e.getMessage());
            }

            KoneksiDatabase obj_con = new KoneksiDatabase();

            Code b = new Code();
            b.setIdStudent(IdStudent);
            b.setFullname(Fullname);
            b.setIdMajor(IdMajor);
            b.setGender(Gender);
            b.setBirth(Birth);
            b.setSchool(School);
            b.setmajor(Major);
            b.setAddress(Address);
            b.setPhone(Phone);
            b.setEmail(Email);
            b.setGraduation(Grayear);
            b.setPhoto(Photo);

            int i = b.Registration();
            int g = b.doUpdate(IdMajor);
            if (i > 0) {
                RequestDispatcher rd = request.getRequestDispatcher("frontend/index.jsp");
                request.setAttribute("return", "Regristration Successfully!");
                rd.forward(request, response);
                //response.sendRedirect("frontend/index.jsp");
            } else {
                RequestDispatcher rd = request.getRequestDispatcher("frontend/index.jsp");
                request.setAttribute("return", "Registration Failed!");
                rd.forward(request, response);
            }
        }
    } catch (Exception ex) {
        out.println(ex.getCause());
        System.out.println(ex.getMessage());
    }
    /* TODO output your page here. You may use following sample code. */

}