Example usage for org.apache.commons.fileupload FileItem getString

List of usage examples for org.apache.commons.fileupload FileItem getString

Introduction

In this page you can find the example usage for org.apache.commons.fileupload FileItem getString.

Prototype

String getString();

Source Link

Document

Returns the contents of the file item as a String, using the default character encoding.

Usage

From source file:manager.doCreateToy.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./* w w  w .jav  a  2 s  .c o 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");
    PrintWriter out = response.getWriter();
    String categoryList = "";
    String fileName = null;

    if (ServletFileUpload.isMultipartContent(request)) {
        try {
            List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);

            for (FileItem item : multiparts) {
                if (!item.isFormField()) {
                    String name = new File(item.getName()).getName();
                    imageFile = new File(item.getName());

                    fileName = name;
                } else {
                    if (item.getFieldName().equals("toyID")) {
                        toyID = Integer.parseInt(item.getString());
                    }
                    if (item.getFieldName().equals("toyName")) {
                        toyName = item.getString();
                    }
                    if (item.getFieldName().equals("description")) {
                        description = item.getString();
                    }

                    if (item.getFieldName().equals("category")) {
                        categoryList += item.getString();

                    }
                    if (item.getFieldName().equals("secondHand")) {
                        secondHand = item.getString();
                    }

                    if (item.getFieldName().equals("cashpoint")) {
                        cashpoint = Integer.parseInt(item.getString());
                    }
                    if (item.getFieldName().equals("qty")) {
                        qty = Integer.parseInt(item.getString());
                    }
                    if (item.getFieldName().equals("discount")) {
                        discount = Integer.parseInt(item.getString());
                    }

                    if (item.getFieldName().equals("uploadString")) {
                        base64String = item.getString();
                    }
                    //if(item.getFieldName().equals("desc"))
                    // desc= item.getString();
                }
            }
            category = categoryList.split(";");

            //File uploaded successfully
            //request.setAttribute("message", "File Uploaded Successfully" + desc);
        } catch (Exception ex) {

            request.setAttribute("message", "File Upload Failed due to " + ex);
        }

    }
    File file = imageFile;
    if (!(fileName == null)) {

        try {
            /*
            * Reading a Image file from file system
             */
            FileInputStream imageInFile = new FileInputStream(file);
            byte imageData[] = new byte[(int) file.length()];
            imageInFile.read(imageData);

            /*
            * Converting Image byte array into Base64 String 
             */
            String imageDataString = encodeImage(imageData);
            request.setAttribute("test", imageDataString);
            /*
            * Converting a Base64 String into Image byte array 
             */
            //byte[] imageByteArray = decodeImage(imageDataString);

            /*
            * Write a image byte array into file system  
             */
            //FileOutputStream imageOutFile = new FileOutputStream("C:\\Users\\Mesong\\Pictures\\Screenshots\\30.png");
            //imageOutFile.write(imageByteArray);
            //request.setAttribute("photo", imageDataString);
            // toyDB toydb = new toyDB();
            //Toy t = toydb.listToyByID(1);
            // toydb.updateToy(t.getToyID(), imageDataString, t.getCashpoint(), t.getQTY(), t.getDiscount());
            imageInFile.close();
            //request.getRequestDispatcher("managerPage/result.jsp").forward(request, response);
            //imageOutFile.close();

            imgString = imageDataString;
            System.out.println("Image Successfully Manipulated!");
        } catch (FileNotFoundException e) {
            out.println("Image not found" + e.getMessage());
        } catch (IOException ioe) {
            System.out.println("Exception while reading the Image " + ioe);
        }
    }
    try {
        toyDB toydb = new toyDB();
        // out.println("s");

        //           int toyID = Integer.parseInt(request.getParameter("toyID"));
        //           String toyName = request.getParameter("toyName");
        //           String description = request.getParameter("description");
        //          
        //           String toyIcon = request.getParameter("toyIcon");
        //           
        //           String[] category = request.getParameterValues("category");
        //           String secondHand = request.getParameter("secondHand");
        //           if(toyIcon==null) toyIcon = "";
        //           int cashpoint = Integer.parseInt(request.getParameter("cashpoint"));
        //           int qty = Integer.parseInt(request.getParameter("qty"));
        //           int discount = Integer.parseInt(request.getParameter("discount"));
        //toydb.updateToy(toyID, toyName,description, toyIcon, cashpoint, qty, discount);
        if (!base64String.equals(""))
            imgString = base64String;
        toydb.createToy(toyName, description, imgString, cashpoint, qty, discount);
        //for(String c : category)
        //   out.println(c);

        out.println(toyID);
        out.println(description);
        out.println(toyIcon);
        out.println(cashpoint);
        out.println(qty);
        out.println(discount);

        toyCategoryDB toyCatdb = new toyCategoryDB();

        // toyCatdb.deleteToyType(toyID);
        for (String c : category) {
            toyCatdb.createToyCategory(Integer.parseInt(c), toyID);
        }
        if (!secondHand.equals("")) {
            secondHandDB seconddb = new secondHandDB();
            SecondHand sh = seconddb.searchSecondHand(Integer.parseInt(secondHand));
            int secondHandCashpoint = sh.getCashpoint();
            toydb.updateToySecondHand(toyID, Integer.parseInt(secondHand));
            toydb.updateToy(toyID, imgString, secondHandCashpoint, qty, discount);
        } else {
            toydb.updateToySecondHand(toyID, -1);

        }
        //out.println(imgString);
        response.sendRedirect("doSearchToy");

    } catch (Exception e) {
        out.println(e.toString());
    } finally {
        out.close();
    }
}

From source file:com.krawler.esp.servlets.ExportImportContactsServlet.java

public static String uploadDocument(HttpServletRequest request, String fileid, String userId)
        throws ServiceException {
    String result = "";
    try {/*from  w ww .  jav a2  s. co m*/
        String destinationDirectory = StorageHandler.GetDocStorePath() + StorageHandler.GetFileSeparator()
                + "importcontacts" + StorageHandler.GetFileSeparator() + userId;
        org.apache.commons.fileupload.DiskFileUpload fu = new org.apache.commons.fileupload.DiskFileUpload();
        org.apache.commons.fileupload.FileItem fi = null;
        org.apache.commons.fileupload.FileItem docTmpFI = null;

        List fileItems = null;
        try {
            fileItems = fu.parseRequest(request);
        } catch (FileUploadException e) {
            KrawlerLog.op.warn("Problem While Uploading file :" + e.toString());
        }

        long size = 0;
        String Ext = "";
        String fileName = null;
        boolean fileupload = false;
        java.io.File destDir = new java.io.File(destinationDirectory);
        fu.setSizeMax(-1);
        fu.setSizeThreshold(4096);
        fu.setRepositoryPath(destinationDirectory);
        java.util.HashMap arrParam = new java.util.HashMap();
        for (java.util.Iterator k = fileItems.iterator(); k.hasNext();) {
            fi = (org.apache.commons.fileupload.FileItem) k.next();
            arrParam.put(fi.getFieldName(), fi.getString());
            if (!fi.isFormField()) {
                size = fi.getSize();
                fileName = new String(fi.getName().getBytes(), "UTF8");

                docTmpFI = fi;
                fileupload = true;
            }
        }

        if (fileupload) {

            if (!destDir.exists()) {
                destDir.mkdirs();
            }
            if (fileName.contains(".")) {
                Ext = fileName.substring(fileName.lastIndexOf("."));
            }
            if (size != 0) {
                File uploadFile = new File(destinationDirectory + "/" + fileid + Ext);
                docTmpFI.write(uploadFile);
                //                    fildoc(fileid, fileName, fileid + Ext, AuthHandler.getUserid(request), size);
                result = fileid + Ext;
            }
        }
    } catch (ConfigurationException ex) {
        Logger.getLogger(importToDoTask.class.getName()).log(Level.SEVERE, null, ex);
        throw ServiceException.FAILURE("ExportImportContactServlet.uploadDocument", ex);
    } catch (Exception ex) {
        Logger.getLogger(importToDoTask.class.getName()).log(Level.SEVERE, null, ex);
        throw ServiceException.FAILURE("ExportImportContactServlet.uploadDocument", ex);
    }
    return result;
}

From source file:it.lufraproini.cms.servlet.Upload.java

private Map prendiInfo(HttpServletRequest request) throws FileUploadException {
    Map info = new HashMap();
    Map files = new HashMap();

    //riutilizzo codice prof. Della Penna per l'upload
    if (ServletFileUpload.isMultipartContent(request)) {
        // Funzioni delle librerie Apache per l'upload
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List<FileItem> items;
        items = upload.parseRequest(request);
        ///*from  w  ww .  j  a  va 2 s  . c o  m*/
        for (FileItem item : items) {
            String name = item.getFieldName();
            //le form che prevedono l'upload di un file devono avere il campo del file chiamato in questo modo
            if (name.startsWith("file_to_upload")) {
                files.put(name, item);
            } else {
                info.put(name, item.getString());
            }
        }
        info.put("files", files);
        return info;
    }
    return null;
}

From source file:com.cmart.PageControllers.SellItemImagesController.java

/**
 * This method checks the page for any input errors that may have come from Client generator error
 * These would need to be check in real life to stop users attempting to hack and mess with things
 * //from ww w  . ja  v  a  2  s.c  o m
 * @param request
 * @author Andy (andrewtu@cmu.edu, turner.andy@gmail.com)
 */
public void checkInputs(HttpServletRequest request) {
    super.startTimer();

    if (request != null) {
        // If there is a multiform there are probably pictures
        if (ServletFileUpload.isMultipartContent(request)) {
            // Get the parameters
            try {
                // Create the objects needed to read the parameters
                factory = new DiskFileItemFactory();
                factory.setRepository(GV.LOCAL_TEMP_DIR);
                upload = new ServletFileUpload(factory);
                items = upload.parseRequest(request);
                Iterator<FileItem> iter = items.iterator();
                TreeMap<String, String> params = new TreeMap<String, String>();

                // Go through all the parameters and get the ones that are form fields
                while (iter.hasNext()) {
                    FileItem item = iter.next();

                    // If the item is a parameter, read it
                    if (item.isFormField()) {
                        params.put(item.getFieldName(), item.getString());
                    } else {
                        this.images.add(item);
                    }
                }

                /*
                 *  Get the parameters
                 */
                // Get the userID
                if (params.containsKey("userID")) {
                    try {
                        this.userID = Long.parseLong(params.get("userID"));

                        if (this.userID < 0)
                            if (!errors.contains(GlobalErrors.userIDLessThanZero))
                                errors.add(GlobalErrors.userIDLessThanZero);
                    } catch (NumberFormatException e) {
                        if (!errors.contains(GlobalErrors.userIDNotAnInteger))
                            errors.add(GlobalErrors.userIDNotAnInteger);

                    }
                } else {
                    if (!errors.contains(GlobalErrors.userIDNotPresent))
                        errors.add(GlobalErrors.userIDNotPresent);
                }

                // We nned to get the html5 tag as the parent cannot do the normal parsing
                if (params.containsKey("useHTML5")) {
                    try {
                        int u5 = Integer.parseInt(params.get("useHTML5"));
                        if (u5 == 1)
                            this.useHTML5 = true;
                        else
                            this.useHTML5 = false;
                    } catch (Exception e) {
                        this.useHTML5 = false;
                    }
                }

                // Get the authToken
                if (params.containsKey("authToken")) {
                    this.authToken = params.get("authToken");

                    if (this.authToken.equals(EMPTY))
                        if (!errors.contains(GlobalErrors.authTokenEmpty))
                            errors.add(GlobalErrors.authTokenEmpty);
                } else {
                    if (!errors.contains(GlobalErrors.authTokenNotPresent))
                        errors.add(GlobalErrors.authTokenNotPresent);
                }

                // Get the itemID
                if (params.containsKey("itemID")) {
                    try {
                        this.itemID = Long.parseLong(params.get("itemID"));

                        if (this.itemID <= 0)
                            if (!errors.contains(GlobalErrors.itemIDLessThanZero))
                                errors.add(GlobalErrors.itemIDLessThanZero);
                    } catch (NumberFormatException e) {
                        if (!errors.contains(GlobalErrors.itemIDNotAnInteger))
                            errors.add(GlobalErrors.itemIDNotAnInteger);
                    }
                } else {
                    if (!errors.contains(GlobalErrors.itemIDNotPresent))
                        errors.add(GlobalErrors.itemIDNotPresent);
                }
            } catch (FileUploadException e1) {
                // TODO Auto-generated catch block
                //System.out.println("SellItemImageController (checkInputs): There was an error in the multi-form");
                e1.printStackTrace();
            }
        }
        // Do normal request processing
        else {
            super.checkInputs(request);

            // Get the userID (if exists), we will pass it along to the next pages
            try {
                this.userID = CheckInputs.checkUserID(request);
            } catch (Error e) {
                // The user must be logged in to upload the images
                if (!errors.contains(e))
                    errors.add(e);
            }

            // Get the authToken (if exists), we will pass it along to the next pages
            try {
                this.authToken = CheckInputs.checkAuthToken(request);
            } catch (Error e) {
                if (!errors.contains(e))
                    errors.add(e);
            }

            // Get the itemID 
            try {
                this.itemID = CheckInputs.checkItemID(request);

                if (this.itemID <= 0)
                    if (!errors.contains(GlobalErrors.itemIDLessThanZero))
                        errors.add(GlobalErrors.itemIDLessThanZero);
            } catch (Error e) {
                if (!errors.contains(e))
                    errors.add(e);

                this.itemID = -1;
            }
        }
    }

    // Calculate how long that took
    super.stopTimerAddParam();
}

From source file:com.wordpress.metaphorm.authProxy.httpClient.impl.OAuthProxyConnectionApacheHttpCommonsClientImpl.java

/**
 * Sets up the given {@link PostMethod} to send the same multipart POST
 * data as was sent in the given {@link HttpServletRequest}
 * @param postMethodProxyRequest The {@link PostMethod} that we are
 *                                configuring to send a multipart POST request
 * @param httpServletRequest The {@link HttpServletRequest} that contains
 *                            the mutlipart POST data to be sent via the {@link PostMethod}
 *///from   w  w  w .j a v  a  2  s  .  c  o  m
@SuppressWarnings("unchecked")
private void handleMultipartPost(PostMethod postMethodProxyRequest, HttpServletRequest httpServletRequest)
        throws IOException {

    _log.debug("handleMultipartPost()");

    // Create a factory for disk-based file items
    DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
    // Set factory constraints
    diskFileItemFactory.setSizeThreshold(this.getMaxFileUploadSize());
    diskFileItemFactory.setRepository(FILE_UPLOAD_TEMP_DIRECTORY);
    // Create a new file upload handler
    ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
    // Parse the request
    try {
        // Get the multipart items as a list
        List<FileItem> listFileItems = (List<FileItem>) servletFileUpload.parseRequest(httpServletRequest);
        // Create a list to hold all of the parts
        List<Part> listParts = new ArrayList<Part>();
        // Iterate the multipart items list
        for (FileItem fileItemCurrent : listFileItems) {
            // If the current item is a form field, then create a string part
            if (fileItemCurrent.isFormField()) {
                StringPart stringPart = new StringPart(fileItemCurrent.getFieldName(), // The field name
                        fileItemCurrent.getString() // The field value
                );
                // Add the part to the list
                listParts.add(stringPart);
            } else {
                // The item is a file upload, so we create a FilePart
                FilePart filePart = new FilePart(fileItemCurrent.getFieldName(), // The field name
                        new ByteArrayPartSource(fileItemCurrent.getName(), // The uploaded file name
                                fileItemCurrent.get() // The uploaded file contents
                        ));
                // Add the part to the list
                listParts.add(filePart);
            }
        }
        MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity(
                listParts.toArray(new Part[] {}), postMethodProxyRequest.getParams());
        postMethodProxyRequest.setRequestEntity(multipartRequestEntity);
        // The current content-type header (received from the client) IS of
        // type "multipart/form-data", but the content-type header also
        // contains the chunk boundary string of the chunks. Currently, this
        // header is using the boundary of the client request, since we
        // blindly copied all headers from the client request to the proxy
        // request. However, we are creating a new request with a new chunk
        // boundary string, so it is necessary that we re-set the
        // content-type string to reflect the new chunk boundary string
        postMethodProxyRequest.setRequestHeader(HttpConstants.STRING_CONTENT_TYPE_HEADER_NAME,
                multipartRequestEntity.getContentType());
    } catch (FileUploadException fileUploadException) {
        throw new IOException(fileUploadException);
    }
}

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

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

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

            }
            String userName = Global.METADB_USER;

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

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

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

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

}

From source file:com.thejustdo.servlet.CargaMasivaServlet.java

/**
 * Processes requests for both HTTP/*from ww  w .j  a v a  2  s  .  com*/
 * <code>GET</code> and
 * <code>POST</code> methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    log.info(String.format("Welcome to the MULTI-PART!!!"));
    ResourceBundle messages = ResourceBundle.getBundle("com.thejustdo.resources.messages");
    // 0. If no user logged, nothing can be done.
    if (!SecureValidator.checkUserLogged(request, response)) {
        return;
    }

    // 1. Check that we have a file upload request.
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    log.info(String.format("Is multipart?: %s", isMultipart));

    // 2. Getting all the parameters.
    String social_reason = request.getParameter("razon_social");
    String nit = request.getParameter("nit");
    String name = request.getParameter("name");
    String phone = request.getParameter("phone");
    String email = request.getParameter("email");
    String office = (String) request.getSession().getAttribute("actualOffice");
    String open_amount = (String) request.getParameter("valor_tarjeta");
    String open_user = (String) request.getSession().getAttribute("actualUser");

    List<String> errors = new ArrayList<String>();

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

    // 7. Configure a repository (to ensure a secure temp location is used)
    ServletContext servletContext = this.getServletConfig().getServletContext();
    File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
    log.info(String.format("Temporal repository: %s", repository.getAbsolutePath()));
    factory.setRepository(repository);

    // 8. Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    try {
        utx.begin();
        EntityManager em = emf.createEntityManager();
        // Parse the request
        List<FileItem> items = upload.parseRequest(request);
        // 8.0 A set of generated box codes must be maintained.
        Map<String, String> matrix = new HashMap<String, String>();
        // ADDED: Validation 'o file extension.
        String filename = null;

        // Runing through the parameters.
        for (FileItem fi : items) {
            if (fi.isFormField()) {
                if ("razon_social".equalsIgnoreCase(fi.getFieldName())) {
                    social_reason = fi.getString();
                    continue;
                }

                if ("nit".equalsIgnoreCase(fi.getFieldName())) {
                    nit = fi.getString();
                    continue;
                }

                if ("name".equalsIgnoreCase(fi.getFieldName())) {
                    name = fi.getString();
                    continue;
                }

                if ("phone".equalsIgnoreCase(fi.getFieldName())) {
                    phone = fi.getString();
                    continue;
                }

                if ("email".equalsIgnoreCase(fi.getFieldName())) {
                    email = fi.getString();
                    continue;
                }

                if ("valor_tarjeta".equalsIgnoreCase(fi.getFieldName())) {
                    open_amount = fi.getString();
                    continue;
                }
            } else {
                filename = fi.getName();
            }
        }

        // 3. If we got no file, then a error is generated and re-directed to the exact same page.
        if (!isMultipart) {
            errors.add(messages.getString("error.massive.no_file"));
            log.log(Level.SEVERE, errors.toString());
        }

        // 4. If any of the others paramaeters are missing, then a error must be issued.
        if ((social_reason == null) || ("".equalsIgnoreCase(social_reason.trim()))) {
            errors.add(messages.getString("error.massive.no_social_reason"));
            log.log(Level.SEVERE, errors.toString());
        }

        if ((nit == null) || ("".equalsIgnoreCase(nit.trim()))) {
            errors.add(messages.getString("error.massive.no_nit"));
            log.log(Level.SEVERE, errors.toString());
        }

        if ((name == null) || ("".equalsIgnoreCase(name.trim()))) {
            errors.add(messages.getString("error.massive.no_name"));
            log.log(Level.SEVERE, errors.toString());
        }

        if ((phone == null) || ("".equalsIgnoreCase(phone.trim()))) {
            errors.add(messages.getString("error.massive.no_phone"));
            log.log(Level.SEVERE, errors.toString());
        }

        if ((email == null) || ("".equalsIgnoreCase(email.trim()))) {
            errors.add(messages.getString("error.massive.no_email"));
            log.log(Level.SEVERE, errors.toString());
        }

        // If no filename or incorrect extension.
        if ((filename == null) || (!(filename.endsWith(Constants.MASSIVE_EXT.toLowerCase(Locale.FRENCH)))
                && !(filename.endsWith(Constants.MASSIVE_EXT.toUpperCase())))) {
            errors.add(messages.getString("error.massive.invalid_ext"));
            log.log(Level.SEVERE, errors.toString());
        }

        // 5. If any errors found, we must break the flow.
        if (errors.size() > 0) {
            request.setAttribute(Constants.ERROR, errors);
            //Redirect the response
            request.getRequestDispatcher("/WEB-INF/jsp/carga_masiva.jsp").forward(request, response);
        }

        for (FileItem fi : items) {
            if (!fi.isFormField()) {
                // 8.1 Processing the file and building the Beneficiaries.
                List<Beneficiary> beneficiaries = processFile(fi);
                log.info(String.format("Beneficiaries built: %d", beneficiaries.size()));

                // 8.2 If any beneficiaries, then an error is generated.
                if ((beneficiaries == null) || (beneficiaries.size() < 0)) {
                    errors.add(messages.getString("error.massive.empty_file"));
                    log.log(Level.SEVERE, errors.toString());
                    request.setAttribute(Constants.ERROR, errors);
                    //Redirect the response
                    request.getRequestDispatcher("/WEB-INF/jsp/carga_masiva.jsp").forward(request, response);
                }

                // 8.3 Building main parts.
                Buyer b = buildGeneralBuyer(em, social_reason, nit, name, phone, email);
                // 8.3.1 The DreamBox has to be re-newed per beneficiary.
                DreamBox db;
                for (Beneficiary _b : beneficiaries) {
                    // 8.3.2 Completing each beneficiary.
                    log.info(String.format("Completying the beneficiary: %d", _b.getIdNumber()));
                    db = buildDreamBox(em, b, office, open_amount, open_user);
                    matrix.put(db.getNumber() + "", _b.getGivenNames() + " " + _b.getLastName());
                    _b.setOwner(b);
                    _b.setBox(db);
                    em.merge(_b);
                }

            }
        }

        // 8.4 Commiting to persistence layer.
        utx.commit();

        // 8.5 Re-directing to the right jsp.
        request.getSession().setAttribute("boxes", matrix);
        request.getSession().setAttribute("boxamount", open_amount + "");
        //Redirect the response
        generateZIP(request, response);
    } catch (Exception ex) {
        errors.add(messages.getString("error.massive.couldnot_process"));
        log.log(Level.SEVERE, errors.toString());
        request.setAttribute(Constants.ERROR, errors);
        request.getRequestDispatcher("/WEB-INF/jsp/carga_masiva.jsp").forward(request, response);
    }
}

From source file:com.sun.faban.harness.webclient.Deployer.java

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

    try {/*from w  w  w .  j  av a  2s  .  com*/
        List<String> deployNames = new ArrayList<String>();
        List<String> cantDeployNames = new ArrayList<String>();
        List<String> errDeployNames = new ArrayList<String>();
        List<String> invalidNames = new ArrayList<String>();
        List<String> errHeaders = new ArrayList<String>();
        List<String> errDetails = new ArrayList<String>();

        String user = null;
        String password = null;
        boolean clearConfig = false;
        boolean hasPermission = true;

        // Check whether we have to return text or html
        boolean acceptHtml = false;
        String acceptHeader = request.getHeader("Accept");
        if (acceptHeader != null && acceptHeader.indexOf("text/html") >= 0)
            acceptHtml = true;

        DiskFileUpload fu = new DiskFileUpload();
        // No maximum size
        fu.setSizeMax(-1);
        // maximum size that will be stored in memory
        fu.setSizeThreshold(4096);
        // the location for saving data that is larger than getSizeThreshold()
        fu.setRepositoryPath(Config.TMP_DIR);

        StringWriter messageBuffer = new StringWriter();
        PrintWriter messageWriter = new PrintWriter(messageBuffer);

        List fileItems = null;
        try {
            fileItems = fu.parseRequest(request);
        } catch (FileUploadException e) {
            throw new ServletException(e);
        }
        // assume we know there are two files. The first file is a small
        // text file, the second is unknown and is written to a file on
        // the server
        for (Iterator i = fileItems.iterator(); i.hasNext();) {
            FileItem item = (FileItem) i.next();
            String fieldName = item.getFieldName();
            if (item.isFormField()) {
                if ("user".equals(fieldName)) {
                    user = item.getString();
                } else if ("password".equals(fieldName)) {
                    password = item.getString();
                } else if ("clearconfig".equals(fieldName)) {
                    String value = item.getString();
                    clearConfig = Boolean.parseBoolean(value);
                }
                continue;
            }

            if (!"jarfile".equals(fieldName))
                continue;

            String fileName = item.getName();

            if (fileName == null) // We don't process files without names
                continue;

            if (Config.SECURITY_ENABLED) {
                if (Config.DEPLOY_USER == null || Config.DEPLOY_USER.length() == 0
                        || !Config.DEPLOY_USER.equals(user)) {
                    hasPermission = false;
                    break;
                }
                if (Config.DEPLOY_PASSWORD == null || Config.DEPLOY_PASSWORD.length() == 0
                        || !Config.DEPLOY_PASSWORD.equals(password)) {
                    hasPermission = false;
                    break;
                }
            }
            // Now, this name may have a path attached, dependent on the
            // source browser. We need to cover all possible clients...

            char[] pathSeparators = { '/', '\\' };
            // Well, if there is another separator we did not account for,
            // just add it above.

            for (int j = 0; j < pathSeparators.length; j++) {
                int idx = fileName.lastIndexOf(pathSeparators[j]);
                if (idx != -1) {
                    fileName = fileName.substring(idx + 1);
                    break;
                }
            }

            // Ignore all non-jarfiles.
            if (!fileName.toLowerCase().endsWith(".jar")) {
                invalidNames.add(fileName);
                continue;
            }

            String deployName = fileName.substring(0, fileName.length() - 4);

            if (deployName.indexOf('.') > -1) {
                invalidNames.add(deployName);
                continue;
            }

            // Check if we can deploy benchmark or service.
            // If running or queued, we won't deploy benchmark.
            // If service being used by current run,we won't deploy service.
            if (!DeployUtil.canDeployBenchmark(deployName) || !DeployUtil.canDeployService(deployName)) {
                cantDeployNames.add(deployName);
                continue;
            }

            File uploadFile = new File(Config.BENCHMARK_DIR, fileName);
            if (uploadFile.exists())
                FileHelper.recursiveDelete(uploadFile);

            try {
                item.write(uploadFile);
            } catch (Exception e) {
                throw new ServletException(e);
            }

            try {
                DeployUtil.processUploadedJar(uploadFile, deployName);
            } catch (Exception e) {
                messageWriter.println("\nError deploying " + deployName + ".\n");
                e.printStackTrace(messageWriter);
                errDeployNames.add(deployName);
                continue;
            }
            deployNames.add(deployName);
        }

        if (clearConfig)
            for (String benchName : deployNames)
                DeployUtil.clearConfig(benchName);

        if (!hasPermission)
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        else if (cantDeployNames.size() > 0)
            response.setStatus(HttpServletResponse.SC_CONFLICT);
        else if (errDeployNames.size() > 0)
            response.setStatus(HttpServletResponse.SC_NOT_ACCEPTABLE);
        else if (invalidNames.size() > 0)
            response.setStatus(HttpServletResponse.SC_NOT_ACCEPTABLE);
        else if (deployNames.size() > 0)
            response.setStatus(HttpServletResponse.SC_CREATED);
        else
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);

        StringBuilder b = new StringBuilder();

        if (deployNames.size() > 0) {
            if (deployNames.size() > 1)
                b.append("Benchmarks/services ");
            else
                b.append("Benchmark/service ");

            for (int i = 0; i < deployNames.size(); i++) {
                if (i > 0)
                    b.append(", ");
                b.append((String) deployNames.get(i));
            }

            b.append(" deployed.");
            errHeaders.add(b.toString());
            b.setLength(0);
        }

        if (invalidNames.size() > 0) {
            if (invalidNames.size() > 1)
                b.append("Invalid deploy files ");
            else
                b.append("Invalid deploy file ");
            for (int i = 0; i < invalidNames.size(); i++) {
                if (i > 0)
                    b.append(", ");
                b.append((String) invalidNames.get(i));
            }
            b.append(". Deploy files must have .jar extension.");
            errHeaders.add(b.toString());
            b.setLength(0);
        }

        if (cantDeployNames.size() > 0) {
            if (cantDeployNames.size() > 1)
                b.append("Cannot deploy benchmarks/services ");
            else
                b.append("Cannot deploy benchmark/services ");
            for (int i = 0; i < cantDeployNames.size(); i++) {
                if (i > 0)
                    b.append(", ");
                b.append((String) cantDeployNames.get(i));
            }
            b.append(". Benchmark/services being used or " + "queued up for run.");
            errHeaders.add(b.toString());
            b.setLength(0);
        }

        if (errDeployNames.size() > 0) {
            if (errDeployNames.size() > 1) {
                b.append("Error deploying benchmarks/services ");
                for (int i = 0; i < errDeployNames.size(); i++) {
                    if (i > 0)
                        b.append(", ");
                    b.append((String) errDeployNames.get(i));
                }
            }

            errDetails.add(messageBuffer.toString());
            errHeaders.add(b.toString());
            b.setLength(0);
        }

        if (!hasPermission)
            errHeaders.add("Permission denied!");

        Writer writer = response.getWriter();
        if (acceptHtml)
            writeHtml(request, writer, errHeaders, errDetails);
        else
            writeText(writer, errHeaders, errDetails);
        writer.flush();
        writer.close();
    } catch (ServletException e) {
        logger.log(Level.SEVERE, e.getMessage(), e);
        throw e;
    } catch (IOException e) {
        logger.log(Level.SEVERE, e.getMessage(), e);
        throw e;
    } catch (Exception e) {
        logger.log(Level.SEVERE, e.getMessage(), e);
        throw new ServletException(e);
    }
}

From source file:controller.productServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    request.setCharacterEncoding("utf-8");
    response.setCharacterEncoding("utf-8");
    String proimage = "";
    String nameProduct = "";
    double priceProduct = 0;
    String desProduct = "";
    String colorProduct = "";
    int years = 0;
    int catId = 0;
    int proid = 0;
    String command = "";

    if (!ServletFileUpload.isMultipartContent(request)) {
        // if not, we stop here
        PrintWriter writer = response.getWriter();
        writer.println("Error: Form must has enctype=multipart/form-data.");
        writer.flush();// w  w w . j  a va2s . c o m
        return;
    }

    // configures upload settings
    DiskFileItemFactory factory = new DiskFileItemFactory();
    // sets memory threshold - beyond which files are stored in disk 
    factory.setSizeThreshold(MEMORY_THRESHOLD);
    // sets temporary location to store files
    factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

    ServletFileUpload upload = new ServletFileUpload(factory);

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

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

    // constructs the directory path to store upload file
    // this path is relative to application's directory
    String uploadPath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY;

    // creates the directory if it does not exist
    File uploadDir = new File(uploadPath);
    if (!uploadDir.exists()) {
        uploadDir.mkdir();
    }

    try {
        // parses the request's content to extract file data
        @SuppressWarnings("unchecked")
        List<FileItem> formItems = upload.parseRequest(request);

        if (formItems != null && formItems.size() > 0) {
            // iterates over form's fields
            for (FileItem item : formItems) {
                // processes only fields that are not form fields
                if (!item.isFormField()) {
                    proimage = new File(item.getName()).getName();
                    String filePath = uploadPath + File.separator + proimage;
                    File storeFile = new File(filePath);
                    System.out.println(proimage);
                    item.write(storeFile);
                } else if (item.getFieldName().equals("name")) {
                    nameProduct = item.getString();
                } else if (item.getFieldName().equals("price")) {
                    priceProduct = Double.parseDouble(item.getString());
                } else if (item.getFieldName().equals("description")) {
                    desProduct = item.getString();
                    System.out.println(desProduct);
                } else if (item.getFieldName().equals("color")) {
                    colorProduct = item.getString();
                } else if (item.getFieldName().equals("years")) {
                    years = Integer.parseInt(item.getString());
                } else if (item.getFieldName().equals("catogory_name")) {
                    catId = Integer.parseInt(item.getString());
                } else if (item.getFieldName().equals("command")) {
                    command = item.getString();
                } else if (item.getFieldName().equals("proid")) {
                    proid = Integer.parseInt(item.getString());
                }
            }
        }
    } catch (Exception ex) {
        request.setAttribute("message", "There was an error: " + ex.getMessage());
    }

    String url = "", error = "";
    if (nameProduct.equals("")) {
        error = "Vui lng nhp tn danh mc!";
        request.setAttribute("error", error);
    }

    try {
        if (error.length() == 0) {
            ProductEntity p = new ProductEntity(catId, nameProduct, priceProduct, proimage, desProduct,
                    colorProduct, years);
            switch (command) {
            case "insert":
                prod.insertProduct(p);
                url = "/java/admin/ql-product.jsp";
                break;
            case "update":
                prod.updateProduct(catId, nameProduct, priceProduct, proimage, desProduct, colorProduct, years,
                        proid);
                url = "/java/admin/ql-product.jsp";
                break;
            }
        } else {
            url = "/java/admin/add-product.jsp";
        }
    } catch (Exception e) {

    }
    response.sendRedirect(url);
}

From source file:com.idr.servlets.UploadServlet.java

/**
 * Uploading the file to the sever and complete the conversion
 * @param request/* ww  w  .  j a  v  a2 s.com*/
 * @param response 
 */
private void doFileUpload(HttpServletRequest request, HttpServletResponse response) {

    //        System.out.println("Doing upload"+System.currentTimeMillis());
    HttpSession session = request.getSession();

    session.setAttribute("href", null);
    session.setAttribute("FILE_UPLOAD_STATS", null);
    session.setAttribute("pageCount", 0);
    session.setAttribute("pageReached", 0);
    session.setAttribute("isUploading", "true");
    session.setAttribute("isConverting", "false");
    session.setAttribute("convertType", "html");
    session.setAttribute("isZipping", "false");
    con = new Converter();
    byte[] fileBytes = null;

    String sessionId = session.getId();
    String userFileName = "";
    HashMap<String, String> paramMap = new HashMap<String, String>();
    int conType = Converter.getConversionType(request.getRequestURI());

    int startPageNumber = 1;
    int pageCount = 0;

    try {

        if (ServletFileUpload.isMultipartContent(request)) {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            UploadListener listener = new UploadListener();//listens file uploads                  
            upload.setProgressListener(listener);
            session.setAttribute("FILE_UPLOAD_STATS", listener);
            List<FileItem> fields = upload.parseRequest(request);
            Iterator<FileItem> it = fields.iterator();
            FileItem fileItem = null;
            if (!it.hasNext()) {
                return;//("No fields found");
            }
            while (it.hasNext()) {
                FileItem field = it.next();
                if (field.isFormField()) {
                    String fieldName = field.getFieldName();
                    Flag.updateParameterMap(fieldName, field.getString(), paramMap);
                    field.delete();
                } else {
                    fileItem = field;
                }
            }
            //Flags whether the file is a .zip or a .pdf
            if (fileItem.getName().contains(".pdf")) {
                isPDF = true;
                isZip = false;
            } else if (fileItem.getName().contains(".zip")) {
                isZip = true;
                isPDF = false;
            }
            //removes the last 4 chars and replaces odd chars with underscore
            userFileName = fileItem.getName().substring(0, fileItem.getName().length() - 4)
                    .replaceAll("[^a-zA-Z0-9]", "_");
            fileBytes = fileItem.get();
            fileItem.delete();
        }

        // Delete existing editor files if any exist. 
        if (isEditorLinkOutput) {
            File editorFolder = new File(Converter.EDITORPATH + "/" + sessionId + "/");
            if (editorFolder.exists()) {
                FileUtils.deleteDirectory(editorFolder);
            }
        }
        con.initializeConversion(sessionId, userFileName, fileBytes, isZip);
        PdfDecoderServer decoder = new PdfDecoderServer(false);
        decoder.openPdfFile(con.getUserPdfFilePath());
        pageCount = decoder.getPageCount();
        //Check whether or not the PDF contains forms
        if (decoder.isForm()) {
            session.setAttribute("isForm", "true"); //set an attrib for extraction.jps to use
            response.getWriter().println("<div id='isForm'></div>");
        } else if (!decoder.isForm()) {
            session.setAttribute("isForm", "false"); //set an attrib for extraction.jps to use
        }
        //Check whther or not the PDF is XFA
        if (decoder.getFormRenderer().isXFA()) {
            session.setAttribute("isXFA", "true");
            //                response.getWriter().println("<div id='isXFA'></div>");
        } else if (!decoder.getFormRenderer().isXFA()) {
            session.setAttribute("isXFA", "false");
        }
        decoder.closePdfFile(); //closes file

        if (paramMap.containsKey("org.jpedal.pdf2html.realPageRange")) {
            String tokensCSV = (String) paramMap.get("org.jpedal.pdf2html.realPageRange");
            PageRanges range = new PageRanges(tokensCSV);
            ArrayList<Integer> rangeList = new ArrayList<Integer>();
            for (int z = 0; z < pageCount; z++) {
                if (range.contains(z)) {
                    rangeList.add(z);
                }
            }
            int userPageCount = rangeList.size();
            if (rangeList.size() > 0) {
                session.setAttribute("pageCount", userPageCount);
            } else {
                throw new Exception("invalid Page Range");
            }
        } else {
            session.setAttribute("pageCount", pageCount);
        }

        session.setAttribute("isUploading", "false");
        session.setAttribute("isConverting", "true");

        String scales = paramMap.get("org.jpedal.pdf2html.scaling");
        String[] scaleArr = null;
        String userOutput = con.getUserFileDirName();
        if (scales != null && scales.contains(",")) {
            scaleArr = scales.split(",");
        }

        String reference = UploadServlet.getConvertedFileHref(sessionId, userFileName, conType, pageCount,
                startPageNumber, paramMap, scaleArr, isZip) + "<br/><br/>";

        if (isZipLinkOutput) {
            reference = reference + con.getZipFileHref(userOutput, scaleArr);
        }

        if (isEditorLinkOutput && conType != Converter.PDF2ANDROID && conType != Converter.PDF2IMAGE) {
            reference = reference + "<br/><br/>" + con.getEditorHref(userOutput, scaleArr); // editor link
        }
        String typeString = Converter.getConversionTypeAsString(conType);

        converterThread(userFileName, scaleArr, fileBytes, typeString, paramMap, session, pageCount, reference);

    } catch (Exception ex) {
        session.setAttribute("href", "<end></end><div class='errorMsg'>Error: " + ex.getMessage() + "</div>");
        Logger.getLogger(UploadServlet.class.getName()).log(Level.SEVERE, null, ex);
        cancelUpload(request, response);
    }
}