Example usage for org.apache.commons.fileupload.servlet ServletFileUpload ServletFileUpload

List of usage examples for org.apache.commons.fileupload.servlet ServletFileUpload ServletFileUpload

Introduction

In this page you can find the example usage for org.apache.commons.fileupload.servlet ServletFileUpload ServletFileUpload.

Prototype

public ServletFileUpload(FileItemFactory fileItemFactory) 

Source Link

Document

Constructs an instance of this class which uses the supplied factory to create FileItem instances.

Usage

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 {//from w  ww.  j a  v a 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:controllers.LinguagemController.java

private void adicionarOuEditarLinguagem() throws IOException, ServletException {
    String anoLancamento, nome, id, licenca, descricao, caminhoLogo;
    anoLancamento = nome = licenca = descricao = caminhoLogo = id = "";

    File file;//  w  w  w. j  a  va 2s  .c o  m
    int maxFileSize = 5000 * 1024;
    int maxMemSize = 5000 * 1024;
    ServletContext context = getServletContext();
    String filePath = context.getInitParameter("file-upload");

    String contentType = request.getContentType();

    if ((contentType.contains("multipart/form-data"))) {

        DiskFileItemFactory factory = new DiskFileItemFactory();

        factory.setSizeThreshold(maxMemSize);
        factory.setRepository(new File("c:\\temp"));

        ServletFileUpload upload = new ServletFileUpload(factory);

        upload.setSizeMax(maxFileSize);
        try {
            List fileItems = upload.parseRequest(request);

            Iterator i = fileItems.iterator();

            while (i.hasNext()) {
                FileItem fi = (FileItem) i.next();
                if (!fi.isFormField()) {
                    String fileName = fi.getName();
                    if (fileName != null) {
                        String name = UUID.randomUUID() + fileName.substring(fileName.lastIndexOf("."));
                        file = new File(filePath + name);

                        caminhoLogo = file.getName();
                        fi.write(file);
                    }
                } else {
                    String campo = fi.getFieldName();
                    String valor = fi.getString("UTF-8");

                    switch (campo) {
                    case "nome":
                        nome = valor;
                        break;
                    case "ano_lancamento":
                        anoLancamento = valor;
                        break;
                    case "licenca":
                        licenca = valor;
                        break;
                    case "descricao":
                        descricao = valor;
                        break;
                    case "id":
                        id = valor;
                        break;
                    default:
                        break;
                    }
                }
            }
        } catch (Exception ex) {
            System.out.println(ex);
        }
    }
    boolean atualizando = !id.isEmpty();

    if (atualizando) {
        Linguagem linguagem = dao.select(Integer.parseInt(id));

        linguagem.setAnoLancamento(anoLancamento);
        linguagem.setDescricao(descricao);
        linguagem.setLicenca(licenca);
        linguagem.setNome(nome);

        if (!caminhoLogo.isEmpty()) {
            File imagemAntiga = new File(filePath + linguagem.getCaminhoLogo());
            imagemAntiga.delete();

            linguagem.setCaminhoLogo(caminhoLogo);
        }

        dao.update(linguagem);

    } else {
        Linguagem linguagem = new Linguagem(nome, anoLancamento, licenca, descricao, caminhoLogo);

        dao.insert(linguagem);
    }

    response.sendRedirect("linguagens.jsp");
    //        response.getWriter().print("<script>setTimeout(function () {"
    //                    + "window.location.href='linguagens.jsp';"
    //                + "}"
    //            + ", 1500);</script>");

}

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

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from   w ww  .j  a  v  a  2 s .co m*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    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: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 .ja v a2  s.  c  o  m*/
    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: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.");
            }/*  w ww.j ava2 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: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);
    }//from  w ww . j  a  v a2 s  .com

    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;//from w  w  w  . j a  va 2  s .c o m
    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:com.orange.mmp.context.RequestContext.java

/**
 * Default constructor using httpServletRequest
 * /*  ww  w  .jav a 2  s  .  c  om*/
 * @param httpServletRequest The original httpServletRequest
 */
@SuppressWarnings("unchecked")
public RequestContext(HttpServletRequest httpServletRequest) throws MMPException {
    this.httpServletRequest = httpServletRequest;
    this.isMultipart = ServletFileUpload.isMultipartContent(httpServletRequest);
    if (this.isMultipart) {
        DiskFileItemFactory factory = new DiskFileItemFactory(MAX_UPLOAD_FILESIZE,
                new File(System.getProperty("java.io.tmpdir")));
        servletFileUpload = new ServletFileUpload(factory);
        try {
            this.multipartItems = servletFileUpload.parseRequest(httpServletRequest);
        } catch (FileUploadException fue) {
            throw new MMPApiException("Failed to parse multipart request", fue);
        }
    }
}

From source file:admin.controller.ServletUpdateFonts.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from  w w w  .j  a  v a2s.  co m*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
public void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    super.processRequest(request, response);
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    String filePath = null;
    String fileName = null, fieldName = null, uploadPath = null, deletePath = null, file_name_to_delete = "";
    RequestDispatcher request_dispatcher;
    String fontname = null, fontid = null, lookid;

    File file;
    int maxFileSize = 5000 * 1024;
    int maxMemSize = 5000 * 1024;
    try {

        uploadPath = AppConstants.BASE_FONT_UPLOAD_PATH;
        deletePath = AppConstants.BASE_FONT_UPLOAD_PATH;
        // Verify the content type
        String contentType = request.getContentType();
        if ((contentType.indexOf("multipart/form-data") >= 0)) {

            DiskFileItemFactory factory = new DiskFileItemFactory();
            // maximum size that will be stored in memory
            factory.setSizeThreshold(maxMemSize);
            // Location to save data that is larger than maxMemSize.
            factory.setRepository(new File(AppConstants.TMP_FOLDER));

            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);
            // maximum file size to be uploaded.
            upload.setSizeMax(maxFileSize);

            // Parse the request to get file items.
            List fileItems = upload.parseRequest(request);

            // Process the uploaded file items
            Iterator i = fileItems.iterator();

            out.println("<html>");
            out.println("<head>");
            out.println("<title>JSP File upload</title>");
            out.println("</head>");
            out.println("<body>");

            while (i.hasNext()) {
                FileItem fi = (FileItem) i.next();
                if (fi.isFormField()) {
                    // Get the uploaded file parameters
                    fieldName = fi.getFieldName();
                    if (fieldName.equals("fontname")) {
                        fontname = fi.getString();
                    }
                    if (fieldName.equals("fontid")) {
                        fontid = fi.getString();
                        file_name_to_delete = font.getFileName(Integer.parseInt(fontid));
                    }

                } else {
                    fieldName = fi.getFieldName();
                    fileName = fi.getName();
                    if (fileName != "") {

                        File uploadDir = new File(uploadPath);
                        if (!uploadDir.exists()) {
                            uploadDir.mkdirs();
                        }

                        boolean isInMemory = fi.isInMemory();
                        long sizeInBytes = fi.getSize();

                        String file_path = uploadPath + File.separator + fileName;
                        String delete_path = deletePath + File.separator + file_name_to_delete;
                        File deleteFile = new File(delete_path);
                        deleteFile.delete();
                        File storeFile = new File(file_path);
                        fi.write(storeFile);
                        out.println("Uploaded Filename: " + filePath + "<br>");
                    }
                }
            }
            font.changeFont(Integer.parseInt(fontid), fontname, fileName);
            response.sendRedirect(request.getContextPath() + "/admin/fontsfamily.jsp");
            out.println("</body>");
            out.println("</html>");
        } else {
            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>");
        }
    } catch (Exception ex) {
        logger.log(Level.SEVERE, "Exception while Updating fonts", ex);
    } finally {
        try {
            out.close();
        } catch (Exception e) {
        }
    }

}

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  w  w  .j  a  v a 2 s.c o 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));
}