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

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

Introduction

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

Prototype

public DiskFileItemFactory() 

Source Link

Document

Constructs an unconfigured instance of this class.

Usage

From source file:ca.qc.cegepoutaouais.tge.pige.server.UserImportService.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    hasError = Boolean.FALSE;//from  ww w  .ja  v  a 2 s  .  c o  m
    writer = resp.getWriter();

    logger.info("Rception de la requte HTTP pour l'imporation d'usagers.");

    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(SIZE_THRESHOLD);

    ServletFileUpload uploadHandler = new ServletFileUpload(factory);
    try {
        List<FileItem> items = uploadHandler.parseRequest(req);
        if (items.size() == 0) {
            logger.error("Le message ne contient pas de fichier "
                    + "d'importation. Le processus ne pourra donc pas " + "continuer.");
            writer.println("Erreur: Aucun fichier prsent dans le message");
            return;
        }

        Charset cs = null;
        for (FileItem item : items) {
            if (item.getFieldName().equalsIgnoreCase("importFileEncoding-hidden")) {
                String encoding = item.getString();
                if (encoding == null || encoding.isEmpty()) {
                    logger.error("Le message ne contient pas l'encodage utilis "
                            + "dans le fichier d'importation. Le processus ne pourra " + "donc pas continuer.");
                    writer.println("Erreur: Aucun encodage trouv dans les " + "paramtres du message.");
                    return;
                }
                cs = Charset.forName(encoding);
                if (cs == null) {
                    logger.error("L'encodage spcifi n'existe pas (" + encoding + "). "
                            + "Le processus ne pourra donc pas continuer.");
                    writer.println("Erreur: Aucun encodage trouv portant le " + "nom '" + encoding + "'.");
                    return;
                }
            }
        }

        for (FileItem item : items) {
            if (item.getFieldName().equalsIgnoreCase("usersImportFile")) {
                logger.info("Extraction du fichier d'importation  partir " + "du message.");
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(new ByteArrayInputStream(item.get()), cs));
                doUsersImport(reader, req);
                break;
            }
        }

        if (!hasError) {
            logger.info("L'importation des usagers s'est termine avec succs.");
            writer.println("Importation russie!");
        } else {
            logger.info("L'importation des usagers s'est termine avec des erreurs.");
            writer.println("L'importation s'est termine avec des erreurs.");
        }

    } catch (FileUploadException fuex) {
        fuex.printStackTrace();
        logger.error(fuex);
    } catch (Exception ex) {
        ex.printStackTrace();
        logger.error(ex);
    }

}

From source file:ai.h2o.servicebuilder.CompilePojoServlet.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    File tmp = null;/*from w ww.  j  ava  2  s  .com*/
    try {
        //create temp directory
        tmp = createTempDirectory("compilePojo");
        logger.info("tmp dir {}", tmp);

        // get input files
        List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
        List<String> pojofiles = new ArrayList<String>();
        String jarfile = null;
        for (FileItem i : items) {
            String field = i.getFieldName();
            String filename = i.getName();
            if (filename != null && filename.length() > 0) {
                if (field.equals("pojo")) {
                    pojofiles.add(filename);
                }
                if (field.equals("jar")) {
                    jarfile = filename;
                }
                FileUtils.copyInputStreamToFile(i.getInputStream(), new File(tmp, filename));
            }
        }
        if (pojofiles.isEmpty() || jarfile == null)
            throw new Exception("need pojofile(s) and jarfile");

        //  create output directory
        File out = new File(tmp.getPath(), "out");
        boolean mkDirResult = out.mkdir();
        if (!mkDirResult)
            throw new Exception("Can't create output directory (out)");

        if (servletPath == null)
            throw new Exception("servletPath is null");

        copyExtraFile(servletPath, "extra" + File.separator, tmp, "H2OPredictor.java", "H2OPredictor.java");
        FileUtils.copyDirectoryToDirectory(
                new File(servletPath, "extra" + File.separator + "WEB-INF" + File.separator + "lib"), tmp);
        copyExtraFile(servletPath, "extra" + File.separator, new File(out, "META-INF"), "MANIFEST.txt",
                "MANIFEST.txt");

        // Compile the pojo(s)
        for (String pojofile : pojofiles) {
            runCmd(tmp,
                    Arrays.asList("javac", "-target", JAVA_TARGET_VERSION, "-source", JAVA_TARGET_VERSION,
                            "-J-Xmx" + MEMORY_FOR_JAVA_PROCESSES, "-cp", jarfile + ":lib/*", "-d", "out",
                            pojofile, "H2OPredictor.java"),
                    "Compilation of pojo failed: " + pojofile);
        }

        // create jar result file
        runCmd(out, Arrays.asList("jar", "xf", tmp + File.separator + jarfile),
                "jar extraction of h2o-genmodel failed");

        runCmd(out,
                Arrays.asList("jar", "xf", tmp + File.separator + "lib" + File.separator + "gson-2.6.2.jar"),
                "jar extraction of gson failed");

        runCmd(out, Arrays.asList("jar", "cfm", tmp + File.separator + "result.jar",
                "META-INF" + File.separator + "MANIFEST.txt", "."), "jar creation failed");

        byte[] resjar = IOUtils.toByteArray(new FileInputStream(tmp + File.separator + "result.jar"));
        if (resjar == null)
            throw new Exception("Can't create jar of compiler output");

        logger.info("jar created, size {}", resjar.length);

        // send jar back
        ServletOutputStream sout = response.getOutputStream();
        response.setContentType("application/octet-stream");
        String outputFilename = pojofiles.get(0).replace(".java", "");
        response.setHeader("Content-disposition", "attachment; filename=" + outputFilename + ".jar");
        response.setContentLength(resjar.length);
        sout.write(resjar);
        sout.close();
        response.setStatus(HttpServletResponse.SC_OK);
    } catch (Exception e) {
        logger.error("post failed", e);
        // send the error message back
        String message = e.getMessage();
        if (message == null)
            message = "no message";
        logger.error(message);
        response.getWriter().write(message);
        response.getWriter().write(Arrays.toString(e.getStackTrace()));
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
    } finally {
        // if the temp directory is still there we delete it
        try {
            if (tmp != null && tmp.exists())
                FileUtils.deleteDirectory(tmp);
        } catch (IOException e) {
            logger.error("Can't delete tmp directory");
        }
    }
}

From source file:com.intbit.ServletModel.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from  w  w w.ja v  a2s . com
 *
 * @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();
    File file;
    int maxFileSize = 5000 * 1024;
    int maxMemSize = 5000 * 1024;
    try {

        look = new Looks();
        //            uploadXmlPath = getServletContext().getRealPath("") + "/model";
        uploadPath = AppConstants.BASE_MODEL_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("organization")) {
                        lookName = fi.getString();
                    }
                    if (fieldName.equals("users")) {
                        lookName = fi.getString();
                    }
                    if (fieldName.equals("categories")) {
                        lookName = fi.getString();
                    }
                    if (fieldName.equals("mapper")) {
                        lookName = fi.getString();
                    }
                    if (fieldName.equals("layout")) {
                        lookName = fi.getString();
                    }
                    if (fieldName.equals("mail")) {
                        lookName = fi.getString();
                    }
                    if (fieldName.equals("socialmedia")) {
                        lookName = fi.getString();
                    }

                    if (fieldName.equals("textstyle")) {
                        lookName = fi.getString();
                    }

                    if (fieldName.equals("containerstyle")) {
                        lookName = fi.getString();
                    }

                    if (fieldName.equals("element")) {
                        lookName = fi.getString();
                    }

                    String textstyleinfo = request.getParameter("textstyle");
                    String containerstyle = request.getParameter("containerstyle");
                    String mapfiledata = request.getParameter("element");
                    String textstylearray[] = textstyleinfo.split(",");
                    String containerstylearray[] = containerstyle.split(" ");
                    String mapfiledataarray[] = mapfiledata.split(",");
                    //        String image = request.getParameter("image");
                    logger.log(Level.INFO, containerstyle);

                    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
                    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

                    // root elements
                    Document doc = docBuilder.newDocument();
                    Element rootElement = doc.createElement("layout");
                    doc.appendChild(rootElement);

                    Document doc1 = docBuilder.newDocument();
                    Element rootElement1 = doc1.createElement("models");
                    doc1.appendChild(rootElement1);

                    Element container = doc.createElement("container");
                    rootElement.appendChild(container);

                    //                        for (int i = 0; i <= containerstylearray.length - 1; i++) {
                    //                            String v[] = containerstylearray[i].split(":");
                    //                            Attr attr = doc.createAttribute(v[0]);
                    //                            attr.setValue("" + v[1]);
                    //                            container.setAttributeNode(attr);
                    //                        }
                    //
                    //                        // staff elements
                    //                        for (int i = 0; i <= textstylearray.length - 1; i++) {
                    //                            Element element = doc.createElement("element");
                    //                            rootElement.appendChild(element);
                    //                            String field1[] = textstylearray[i].split(" ");
                    //                            for (int j = 0; j <= field1.length - 1; j++) {
                    //                                String field2[] = field1[j].split(":");
                    //                                for (int k = 0; k < field2.length - 1; k++) {
                    //                                    Attr attr = doc.createAttribute(field2[0]);
                    //                                    attr.setValue("" + field2[1]);
                    //                                    element.setAttributeNode(attr);
                    //                                }
                    //                            }
                    //                        }
                    //
                    //            //            for mapper xml file
                    //                        for (int i = 0; i <= mapfiledataarray.length - 1; i++) {
                    //                            Element element1 = doc1.createElement("model");
                    //                            rootElement1.appendChild(element1);
                    //                            String field1[] = mapfiledataarray[i].split(" ");
                    //                            for (int j = 0; j <= field1.length - 1; j++) {
                    //                                String field2[] = field1[j].split(":");
                    //                                for (int k = 0; k < field2.length - 1; k++) {
                    //                                    Attr attr = doc1.createAttribute(field2[k]);
                    //                                    attr.setValue("" + field2[1]);
                    //                                    element1.setAttributeNode(attr);
                    //                                }
                    //                            }
                    //                        }

                    // write the content into xml file
                    //                        TransformerFactory transformerFactory = TransformerFactory.newInstance();
                    //                        Transformer transformer = transformerFactory.newTransformer();
                    //                        DOMSource source = new DOMSource(doc);
                    //                        StreamResult result = new StreamResult(new File(uploadPath +File.separator + layoutfilename + ".xml"));
                    //
                    //                        TransformerFactory transformerFactory1 = TransformerFactory.newInstance();
                    //                        Transformer transformer1 = transformerFactory1.newTransformer();
                    //                        DOMSource source1 = new DOMSource(doc1);
                    //                        StreamResult result1 = new StreamResult(new File(uploadPath +File.separator + mapperfilename + ".xml"));

                    // Output to console for testing
                    // StreamResult result = new StreamResult(System.out);
                    //                        transformer.transform(source, result);
                    //                        transformer1.transform(source1, result1);
                    //                        layout.addLayouts(organization_id , user_id, category_id, layoutfilename, mapperfilename, type_email, type_social);

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

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

                    int inStr = fileName.indexOf(".");
                    String Str = fileName.substring(0, inStr);

                    fileName = lookName + "_" + Str + ".png";
                    boolean isInMemory = fi.isInMemory();
                    long sizeInBytes = fi.getSize();

                    String filePath = uploadPath + File.separator + fileName;
                    File storeFile = new File(filePath);

                    fi.write(storeFile);

                    out.println("Uploaded Filename: " + filePath + "<br>");
                }
            }
            //                look.addLooks(lookName, fileName);
            response.sendRedirect(request.getContextPath() + "/admin/looks.jsp");
            //                        request_dispatcher = request.getRequestDispatcher("/admin/looks.jsp");
            //                        request_dispatcher.forward(request, response);
            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, util.Utility.logMessage(ex, "Exception while updating org name:",
                getSqlMethodsInstance().error));
        out.println(getSqlMethodsInstance().error);
    } finally {
        out.close();
    }

}

From source file:adminServlets.AddProductServlet.java

private void uploadImage(HttpServletRequest request, HttpServletResponse response) {
    PrintWriter out = null;// w w w  .jav  a 2s  . c om
    try {

        out = response.getWriter();
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List<FileItem> items = upload.parseRequest(request);
        Iterator<FileItem> iter = items.iterator();

        while (iter.hasNext()) {

            FileItem item = (FileItem) iter.next();

            if (item.isFormField()) {
                String name = item.getFieldName();
                String value = item.getString();
                paramaters.put(name, value);

            } else // processUploadedFile(item);
            {
                if (item.getSize() != 0) {
                    String itemName = item.getName();
                    Random generator = new Random();
                    int r = Math.abs(generator.nextInt());

                    String reg = "[.*]";
                    String replacingtext = "";

                    Pattern pattern = Pattern.compile(reg);
                    Matcher matcher = pattern.matcher(itemName);
                    StringBuffer buffer = new StringBuffer();

                    while (matcher.find()) {
                        matcher.appendReplacement(buffer, replacingtext);
                    }
                    int IndexOf = itemName.indexOf(".");
                    String domainName = itemName.substring(IndexOf);

                    String finalimage = buffer.toString() + "_" + r + domainName;

                    String path = "assets\\img\\bouques\\" + finalimage;
                    imgPaths.add(path);
                    File savedFile = new File(getServletContext().getRealPath("/") + path);

                    try {
                        item.write(savedFile);
                    } catch (Exception ex) {
                        Logger.getLogger(AddProductServlet.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            }
        }
    } catch (IOException | FileUploadException ex) {
        Logger.getLogger(AddProductServlet.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
    }

}

From source file:corpixmgr.handler.CorpixPostHandler.java

/**
 * Parse the import params from the request
 * @param request the http request/*from  w ww.  ja v a  2s.  c o m*/
 */
protected void parseImportParams(HttpServletRequest request) throws CorpixException {
    try {
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        //System.out.println("Parsing import params");
        if (isMultipart) {
            FileItemFactory factory = new DiskFileItemFactory();
            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);
            // Parse the request
            List items = upload.parseRequest(request);
            for (int i = 0; i < items.size(); i++) {
                FileItem item = (FileItem) items.get(i);
                if (item.isFormField()) {
                    String fieldName = item.getFieldName();
                    if (fieldName != null) {
                        String contents = item.getString("UTF-8");
                        processField(fieldName, contents);
                    }
                } else if (item.getName().length() > 0) {
                    fileName = item.getName();
                    InputStream is = item.getInputStream();
                    ByteArrayOutputStream bh = new ByteArrayOutputStream();
                    while (is.available() > 0) {
                        byte[] b = new byte[is.available()];
                        is.read(b);
                        bh.write(b);
                    }
                    fileData = bh.toByteArray();
                }
            }
        } else {
            Map tbl = request.getParameterMap();
            Set<String> keys = tbl.keySet();
            Iterator<String> iter = keys.iterator();
            while (iter.hasNext()) {
                String key = iter.next();
                String[] values = (String[]) tbl.get(key);
                for (int i = 0; i < values.length; i++)
                    processField(key, values[i]);
            }
        }
    } catch (Exception e) {
        throw new CorpixException(e);
    }
}

From source file:gov.nist.appvet.tool.SynchronousService.java

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

    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    List items = null;//from  ww w  .j av  a2  s  . c om
    FileItem fileItem = null;

    try {
        items = upload.parseRequest(request);
    } catch (FileUploadException e) {
        e.printStackTrace();
    }

    // Get form fields
    Iterator iter = items.iterator();
    FileItem item = null;
    while (iter.hasNext()) {
        item = (FileItem) iter.next();
        if (item.isFormField()) {
            //String incomingParameter = item.getFieldName();
            //String incomingValue = item.getString();
            // For this service, we do not expect any input parameters 
            // except for the app file.
            //log.debug("Ignoring " + incomingParameter + " = " + incomingValue);
        } else {
            // item should now hold the received file
            if (item != null) {
                fileItem = item;
                log.debug("Received file: " + fileItem.getName());
            }
        }
    }

    String appFilePath = null;
    String fileName = null;
    Random rand = new Random(new Date().getTime());
    final int randInt = rand.nextInt(9999999);
    String id = new Integer(randInt).toString();

    if (fileItem != null) {
        fileName = getFileName(fileItem.getName());
        if (!fileName.endsWith(".apk")) {
            sendHttp400(response, "Invalid app file: " + fileItem.getName());
            return;
        }

        appFilePath = Properties.TEMP_DIR + "/" + id + fileName;
        log.debug("App file path: " + appFilePath);

        if (!saveFileUpload(fileItem, appFilePath)) {
            sendHttp500(response, "Could not save uploaded file");
            return;
        }
    } else {
        sendHttp400(response, "No app was received.");
        return;
    }

    String command = Properties.command + " " + appFilePath;

    StringBuffer reportBuffer = new StringBuffer();
    boolean succeeded = runTool(command, reportBuffer);
    if (!succeeded) {
        if (reportBuffer.toString().contains("java.lang.SecurityException")) {
            returnReport(response, fileName, ToolStatus.FAIL, reportBuffer.toString());
        } else {
            log.error("Error detected: " + reportBuffer.toString());
            returnReport(response, fileName, ToolStatus.ERROR, reportBuffer.toString());
        }
    } else {
        log.debug("Analyzing report for " + appFilePath);
        ToolStatus reportStatus = analyzeReport(reportBuffer.toString());
        log.debug("Result: " + reportStatus.name());
        returnReport(response, fileName, reportStatus, reportBuffer.toString());
    }

    boolean deleted = deleteFile(appFilePath);
    if (deleted) {
        log.debug("Deleted " + appFilePath);
    } else {
        log.error("Could not delete file " + appFilePath);
    }

    // Clean up
    reportBuffer = null;
    System.gc();
}

From source file:controller.uploadProductController.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*from   ww w.  j  a  v a 2 s .  c o  m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    HttpSession session = request.getSession(true);
    String userPath = request.getServletPath();
    if (userPath.equals("/uploadProduct")) {
        boolean success = true;
        // 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().getInitParameter("upload.location");
        //creates a HashMap of all inputs
        HashMap hashMap = new HashMap();
        String productId = UUID.randomUUID().toString();
        try {
            @SuppressWarnings("unchecked")
            List<FileItem> formItems = upload.parseRequest(request);
            for (FileItem item : formItems) {
                // processes only fields that are not form fields
                if (!item.isFormField()) {
                    File file = new File(item.getName());
                    File file2 = new File(productId + ".jpg");
                    String filePath = uploadPath + File.separator + file.getName();
                    // saves the file on disk
                    File storeFile = new File(filePath);
                    item.write(storeFile);
                    File rename = new File(filePath);
                    boolean flag = rename.renameTo(file2);
                } else {
                    hashMap.put(item.getFieldName(), item.getString());
                }
            }
        } catch (FileUploadException ex) {
            Logger.getLogger(uploadProductController.class.getName()).log(Level.SEVERE, null, ex);
            request.setAttribute("error", true);
            request.setAttribute("errorMessage", ex.getMessage());
            success = false;
        } catch (Exception ex) {
            Logger.getLogger(uploadProductController.class.getName()).log(Level.SEVERE, null, ex);
            request.setAttribute("error", true);
            request.setAttribute("errorMessage", ex.getMessage());
            success = false;
        }
        String owner = (String) session.getAttribute("customerEmail");
        if (owner == null) {
            owner = "shop";
        }

        String pName = hashMap.get("pName").toString();
        String mNo = hashMap.get("mNo").toString();
        String brand = hashMap.get("brand").toString();
        String description = hashMap.get("description").toString();
        String quantity = hashMap.get("quantity").toString();
        String price = hashMap.get("price").toString();
        String addInfo = hashMap.get("addInfo").toString();
        int categoryId = Integer.parseInt(hashMap.get("category").toString());

        ProductDAO productDAO = new ProductDAOImpl();
        Product product;

        try {
            double priceDouble = Double.parseDouble(price);
            int quantityInt = Integer.parseInt(quantity);
            Category category = (new CategoryDAOImpl()).getCategoryFromID(categoryId);
            if (owner.equals("shop")) {
                product = new Product(productId, pName, mNo, category, quantityInt, priceDouble, brand,
                        description, addInfo, true, true, owner);
            } else {
                product = new Product(productId, pName, mNo, category, quantityInt, priceDouble, brand,
                        description, addInfo, false, false, owner);
            }

            if (!(productDAO.addProduct(product, category.getName()))) {
                throw new Exception("update unsuccessful");
            }
        } catch (Exception e) {
            request.setAttribute("error", true);
            request.setAttribute("errorMessage", e.getMessage());
            success = false;
        }

        request.setAttribute("pName", pName);
        request.setAttribute("mNo", mNo);
        request.setAttribute("brand", brand);
        request.setAttribute("description", description);
        request.setAttribute("quantity", quantity);
        request.setAttribute("price", price);
        request.setAttribute("addInfo", addInfo);
        request.setAttribute("categoryId", categoryId);
        request.setAttribute("success", success);
        if (success == true) {
            request.setAttribute("error", false);
            request.setAttribute("errorMessage", null);
        }
        String url;
        if (owner.equals("shop")) {
            url = "/WEB-INF/view/adminAddProducts.jsp";
        } else {
            url = "/WEB-INF/view/clientSideView/addRecycleProduct.jsp";
        }
        try {
            request.getRequestDispatcher(url).forward(request, response);
        } catch (ServletException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }

    }

}

From source file:fr.paris.lutece.util.http.MultipartUtil.java

/**
 * Convert a HTTP request to a {@link MultipartHttpServletRequest}
 * @param nSizeThreshold the size threshold
 * @param nRequestSizeMax the request size max
 * @param bActivateNormalizeFileName true if the file name must be normalized, false otherwise
 * @param request the HTTP request//from  ww w  . j  a  v  a 2s  .c o  m
 * @return a {@link MultipartHttpServletRequest}, null if the request does not have a multipart content
 * @throws SizeLimitExceededException exception if the file size is too big
 * @throws FileUploadException exception if an unknown error has occurred
 */
public static MultipartHttpServletRequest convert(int nSizeThreshold, long nRequestSizeMax,
        boolean bActivateNormalizeFileName, HttpServletRequest request)
        throws SizeLimitExceededException, FileUploadException {
    if (isMultipart(request)) {
        // Create a factory for disk-based file items
        DiskFileItemFactory factory = new DiskFileItemFactory();

        // Set factory constraints
        factory.setSizeThreshold(nSizeThreshold);

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

        // Set overall request size constraint
        upload.setSizeMax(nRequestSizeMax);

        // get encoding to be used
        String strEncoding = request.getCharacterEncoding();

        if (strEncoding == null) {
            strEncoding = EncodingService.getEncoding();
        }

        Map<String, FileItem> mapFiles = new HashMap<String, FileItem>();
        Map<String, String[]> mapParameters = new HashMap<String, String[]>();

        List<FileItem> listItems = upload.parseRequest(request);

        // Process the uploaded items
        for (FileItem item : listItems) {
            if (item.isFormField()) {
                String strValue = StringUtils.EMPTY;

                try {
                    if (item.getSize() > 0) {
                        strValue = item.getString(strEncoding);
                    }
                } catch (UnsupportedEncodingException ex) {
                    if (item.getSize() > 0) {
                        // if encoding problem, try with system encoding
                        strValue = item.getString();
                    }
                }

                // check if item of same name already in map
                String[] curParam = mapParameters.get(item.getFieldName());

                if (curParam == null) {
                    // simple form field
                    mapParameters.put(item.getFieldName(), new String[] { strValue });
                } else {
                    // array of simple form fields
                    String[] newArray = new String[curParam.length + 1];
                    System.arraycopy(curParam, 0, newArray, 0, curParam.length);
                    newArray[curParam.length] = strValue;
                    mapParameters.put(item.getFieldName(), newArray);
                }
            } else {
                // multipart file field, if the parameter filter ActivateNormalizeFileName is set to true
                //all file name will be normalize
                mapFiles.put(item.getFieldName(),
                        bActivateNormalizeFileName ? new NormalizeFileItem(item) : item);
            }
        }

        return new MultipartHttpServletRequest(request, mapFiles, mapParameters);
    }

    return null;
}

From source file:com.kunal.NewServlet2.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//  www.ja  v  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 {
    if (ServletFileUpload.isMultipartContent(request)) {

        try {
            HttpSession session = request.getSession();
            String V_Str_Id = (String) session.getAttribute("VSID");
            String containerName = V_Str_Id;
            //String fileName = "Ad2";
            String userId = "7f7a82c6a2464a45b0ea5b7c65c90f38";
            String password = "lM_EC#0a7U})SE-.";
            String auth_url = "https://lon-identity.open.softlayer.com" + "/v3";
            String domain = "1090141";
            String project = "object_storage_e32c650b_e512_4e44_aeb8_c49fdf1de69f";
            Identifier domainIdent = Identifier.byName(domain);
            Identifier projectIdent = Identifier.byName(project);

            OSClient os = OSFactory.builderV3().endpoint(auth_url).credentials(userId, password)
                    .scopeToProject(projectIdent, domainIdent).authenticate();

            SwiftAccount account = os.objectStorage().account().get();
            ObjectStorageService objectStorage = os.objectStorage();
            List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);

            for (FileItem item : multiparts) {
                if (!item.isFormField()) {
                    String name = new File(item.getName()).getName();
                    System.out.println(name);
                    // item.write( new File(UPLOAD_DIRECTORY + File.separator + name));
                    String etag = os.objectStorage().objects().put(containerName, name,
                            Payloads.create(item.getInputStream()));
                    System.out.println(etag);
                }
            }

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

    } else {
        request.setAttribute("message", "Sorry this Servlet only handles file upload request");
    }

    request.getRequestDispatcher("/Pre_Installation.jsp").forward(request, response);

}

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

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    response.setContentType("text/html");
    log("Content-Type: " + request.getContentType());

    DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
    /*/*from  w  ww  .j a  v a  2 s  .c o m*/
     *Set the size threshold, above which content will be stored on disk.
     */
    fileItemFactory.setSizeThreshold(10 * 1024 * 1024); //10 MB
    /*
    * Set the temporary directory to store the uploaded files of size above threshold.
    */
    fileItemFactory.setRepository(tmpDir);

    ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
    try {
        /*
         * Parse the request
         */
        List items = uploadHandler.parseRequest(request);
        log("FileItems: " + items.toString());
        Iterator itr = items.iterator();
        while (itr.hasNext()) {

            FileItem item = (FileItem) itr.next();
            /*
             * Handle Form Fields.
             */
            if (item.isFormField()) {
                out.println("File Name = " + item.getFieldName() + ", Value = " + item.getString());
            } else {
                //Handle Uploaded files.
                out.println("<html><head><title>CommonsFileUploadServlet</title></head><body><p>");
                out.println("Field Name = " + item.getFieldName() + "\nFile Name = " + item.getName()
                        + "\nContent type = " + item.getContentType() + "\nFile Size = " + item.getSize());
                out.println("</p>");
                out.println("<img src=\"" + request.getContextPath() + "/files/" + item.getName() + "\"/>");
                out.println("</body></html>");
                /*
                 * Write file to the ultimate location.
                 */
                File file = new File(destinationDir, item.getName());
                item.write(file);
            }
            out.close();
        }
    } catch (FileUploadException ex) {
        log("Error encountered while parsing the request", ex);
    } catch (Exception ex) {
        log("Error encountered while uploading file", ex);
    }
}