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

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

Introduction

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

Prototype

public static final boolean isMultipartContent(HttpServletRequest request) 

Source Link

Document

Utility method that determines whether the request contains multipart content.

Usage

From source file:com.gwtcx.server.servlet.FileUploadServlet.java

private void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    Log.debug("FileDownloadServlet - processRequest()");

    // check that we have a file upload request
    if (ServletFileUpload.isMultipartContent(request)) {
        processFiles(request, response);
    } else {/*from   w  w w .  j a v a 2 s  .  c  om*/
        processQuery(request, response);
    }
}

From source file:com.mkmeier.quickerbooks.LoadAccounts.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
 *
 * @param request servlet request/*  w  w w  . j av  a2 s  .  c  o m*/
 * @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 form hasn't been submitted, load the form.
    if (!ServletFileUpload.isMultipartContent(request)) {
        redirect(request, response);
        return;
    }

    //Extract files from form submission.
    ServletFileUploader up = new ServletFileUploader();
    up.parseRequest(request);

    File file = up.getFileMap().get("accountsIIF");

    //Parse the file
    try {
        IifParser parser = new IifParser(file);
        IifData iifData = parser.parse();

        AccountParser ap = new AccountParser(iifData);
        List<QbAccount> accounts = ap.parse();

        saveAccounts(accounts);
        response.sendRedirect("/QuickerBooks");
    } catch (IifException ex) {
        logger.error("Parsing Error", ex);
    }
}

From source file:com.mycom.products.mywebsite.backend.util.UploadHandler.java

@Override
@ResponseBody//from w w w  .ja v  a2 s. c  o  m
@RequestMapping(method = RequestMethod.POST)
protected final void doPost(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException, IOException {
    ServletFileUpload uploadHandler = new ServletFileUpload(new DiskFileItemFactory());
    PrintWriter writer = response.getWriter();
    // checks if the request actually contains upload file
    if (!ServletFileUpload.isMultipartContent(request)) {
        // if not, we stop here
        writer.println("Error: Form must has enctype=multipart/form-data.");
        writer.flush();
        return;
    }
    JSONObject json = new JSONObject();
    SimpleDateFormat fmtYMD = new SimpleDateFormat("/" + "yyyyMMdd");
    Date today = new Date();
    String uploadPath = EntryPoint.getUploadPath() + "/";

    try {
        List<FileItem> items = uploadHandler.parseRequest(request);
        if (items != null && items.size() > 0) {
            String saveDir = "", fileCategory = "";
            for (FileItem item : items) {
                if (item.isFormField()) {
                    fileCategory = item.getString();
                }
            }
            saveDir = fileCategory + fmtYMD.format(today);
            // creates the directory if it does not exist
            File uploadDir = new File(uploadPath + saveDir);
            if (!uploadDir.exists()) {
                uploadDir.mkdirs();
            }
            List<HashMap<String, String>> uploadFiles = new ArrayList<>();
            for (FileItem item : items) {
                // processes only fields that are not form fields
                if (!item.isFormField()) {
                    if (saveDir.length() == 0) {
                        json.put("messageCode", "V1001");
                        json.put("messageParams", "File upload type");
                        json.put("status", HttpStatus.BAD_REQUEST);
                        response.setContentType("application/json");
                        writer.write(json.toString());
                        writer.flush();
                    }
                    String originalFileName = "", saveFileName = "", format = "", fileSize = "";
                    // set the default format to png when it is profileImage
                    if (fileCategory.equals("profilePicture")) {
                        format = ".png";
                    }
                    // can't predict fileName and format would be included.
                    // For instance, blob won't be.
                    try {
                        originalFileName = item.getName().substring(0, item.getName().lastIndexOf("."));
                    } catch (Exception e) {
                        // Nothing to do. Skip
                    }
                    try {
                        format = item.getName().substring(item.getName().lastIndexOf("."),
                                item.getName().length());
                    } catch (Exception e) {
                        // Nothing to do. Skip
                    }

                    fileSize = getReadableFileSize(item.getSize());
                    UUID uuid = UUID.randomUUID();
                    saveFileName = new File(uuid.toString() + format).getName();
                    String filePath = uploadPath + saveDir + "/" + saveFileName;
                    if (fileCategory.equals("profilePicture")) {
                        saveProfileImage(item, filePath);
                    }
                    // Time to save in DB
                    LoggedUserBean loginUser;
                    Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
                    if (principal instanceof LoggedUserBean) {
                        loginUser = (LoggedUserBean) principal;
                    } else {
                        throw new SecurityException("Unauthorize File Upload process was attempted.");
                    }
                    StaticContentBean content = new StaticContentBean();
                    content.setFileName(originalFileName + format);
                    content.setFilePath(filePath);
                    content.setFileSize(fileSize);
                    content.setFileType(FileType.valueOf(getFileType(format)));
                    long lastInsertedId = contentService.insert(content, loginUser.getId());
                    // else .... other file types go here

                    HashMap<String, String> fileItem = new HashMap<>();
                    fileItem.put("contentId", "" + lastInsertedId);
                    uploadFiles.add(fileItem);

                }
            }
            json.put("uploadFiles", uploadFiles);
            json.put("status", HttpStatus.OK);
            response.setContentType("application/json");
            writer.write(json.toString());
            writer.flush();
        }
    } catch (FileUploadException e) {
        throw new RuntimeException("File upload Error !", e);
    } catch (Exception e) {
        throw new RuntimeException("File upload Error !", e);
    } finally {
        writer.close();
    }
}

From source file:Control.FrontControl.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from   w w  w. j  a v a  2 s .c om*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    request.setCharacterEncoding("UTF-8"); //Characterencoding for special characters

    //This part of the code, checks if there might be files for upload, and seperates them, if that is the case
    Collection<Part> parts = null;
    if (ServletFileUpload.isMultipartContent(request)) {
        parts = request.getParts(); //Extracts the part of the form that has files and parameters
    }

    HttpSession sessionObj = request.getSession(); //Get the session
    DomainFacade df = (DomainFacade) sessionObj.getAttribute("Controller"); //Get the DomainFacede
    //If it is a new session, create a new DomainFacade Object and put it in the session.
    sessionObj.setAttribute("testing", testing);
    if (df == null) {
        df = DomainFacade.getInstance();
        sessionObj.setAttribute("Controller", df);
    }

    //Set base url
    String url = "/index.jsp";
    String action = request.getParameter("action");
    if (action == null) {
        action = "";
    }

    String page = request.getParameter("page");
    if (testing) {
        System.out.println("Redirect parameter (page) set to:");
    }
    if (testing) {
        System.out.println(page);
    }
    try {
        if (page == null) {
            page = "";
        }
        //For creating a new report
        if (page.equalsIgnoreCase("newreport")) {
            url = "/reportJSPs/choosebuilding.jsp";
            sessionObj.setAttribute("customerSelcted", false);
            cuh.chooseCustomer(sessionObj, df);
        }
        //For choosing the customer //TODO split redirect and action
        if (page.equalsIgnoreCase("report_cus_choosen")) {
            url = "/reportJSPs/choosebuilding.jsp";
            bh.loadCustomersBuildings(request, sessionObj, df);
        }
        //When building has been chosen, it sets up the report object
        if (page.equalsIgnoreCase("report_start")) {
            url = "/reportJSPs/report_start.jsp";
            rh.createReport(request, sessionObj, df);
        }

        //For choosing room when setting up report, after exterior has been added
        if (page.equalsIgnoreCase("ChooseRoom")) {
            url = "/reportJSPs/chooseroom.jsp";
            rh.saveReportExterior(request, sessionObj, parts, this);
        }

        //For inspecting the chosen room.
        if (page.equalsIgnoreCase("inspectRoom")) {
            url = "/reportJSPs/reportaddaroom.jsp";
            rh.setUpForRoomInspection(request, sessionObj, df, parts);
        }

        //For submitting what is written about the room
        if (page.equalsIgnoreCase("submittedRoom")) {
            url = "/reportJSPs/chooseroom.jsp";
            rh.createReportRoomElements(request, sessionObj, parts, this);
        }

        //Saving finished report and redirection to report view. 
        if (page.equalsIgnoreCase("saveFinishedReport")) {
            url = "/viewreport.jsp";
            rh.finishReportObject(request, sessionObj);
            int reportId = rh.saveFinishedReport(sessionObj, df);
            request.getSession().setAttribute("report", df.getReport(reportId));
        }

        if (page.equalsIgnoreCase("toFinishReport")) {
            url = "/reportJSPs/finishreport.jsp";
        }
        if (page.equalsIgnoreCase("backToChooseRoom")) {
            url = "/reportJSPs/chooseroom.jsp";
        }

        //For inspecting a room you just added to the building
        if (page.equalsIgnoreCase("inspectRoomjustCreated")) {
            url = "/reportJSPs/reportaddaroom.jsp";
            bh.createNewRoom(request, sessionObj, df);
            rh.setUpForRoomInspection(request, sessionObj, df, parts);
        }

        //List all reports for all customers
        if (page.equalsIgnoreCase("listreports")) {
            sessionObj.setAttribute("reports", df.getListOfReports(1));
            response.sendRedirect("viewreports.jsp");
            return;
        }
        if (page.equalsIgnoreCase("addbuilding")) {
            url = "/addbuilding.jsp";
        }
        if (page.equalsIgnoreCase("addcustomer")) {
            url = "/addcustomer.jsp";
        }

        //Viewing the list of all the 
        if (page.equalsIgnoreCase("viewmybuildings")) {
            bh.findListOfBuilding(request, df, sessionObj);
            User tempUser = (User) request.getSession().getAttribute("user");
            List<Building> buildings = df.getListOfBuildings(tempUser.getCustomerid());
            url = "/viewcustomer.jsp";
            sessionObj.setAttribute("buildings", buildings);
        }

        //Edit a building
        if (page.equalsIgnoreCase("editBuilding")) {
            bh.findBuildingToBeEdit(request, sessionObj, df);
            response.sendRedirect("editBuilding.jsp");
            return;
        }

        if (page.equalsIgnoreCase("viewreport")) {
            int reportId = Integer.parseInt(request.getParameter("reportid"));
            Report report = df.getReport(reportId);
            sessionObj.setAttribute("report", report);
            response.sendRedirect("viewreport.jsp");
            return;
        }

        if (page.equalsIgnoreCase("viewcustomers")) {
            List<Customer> customers = df.loadAllCustomers();
            sessionObj.setAttribute("customers", customers);
            response.sendRedirect("viewcustomers.jsp");
            return;
        }

        if (page.equalsIgnoreCase("viewcustomer")) {
            int custId = Integer.parseInt(request.getParameter("customerid"));
            sessionObj.setAttribute("customer_id", custId);
            List<Building> buildings = df.getListOfBuildings(custId);
            List<Customer> customers = df.loadAllCustomers();
            for (Customer customer : customers) {
                if (customer.getCustomerId() == custId) {
                    sessionObj.setAttribute("customer", customer);
                }
            }
            sessionObj.setAttribute("buildings", buildings);
            response.sendRedirect("viewcustomer.jsp");
            return;
        }

        //This gets a Dashboard for a building
        if (page.equalsIgnoreCase("viewbuildingadmin")) {
            System.out.println("Did it go here?");
            int buildId = Integer.parseInt(request.getParameter("buildingid"));
            Building b = df.getBuilding(buildId);
            sessionObj.setAttribute("building", b);
            response.sendRedirect("viewbuildingadmin.jsp");
            return;
        }

        //TODO seperate redirect and action
        if (page.equalsIgnoreCase("newbuilding")) {

            Building b = bh.createBuilding(request, df, sessionObj, parts, this);
            response.sendRedirect("viewnewbuilding.jsp");
            return;
        }

        //TODO: seperate action and redirect
        if (page.equalsIgnoreCase("vieweditedbuilding")) {
            Building b = bh.updateBuilding(request, df, sessionObj, parts, this);
            response.sendRedirect("viewbuildingadmin.jsp");
            return;
        }

        //TODO: seperate action and redirect
        if (page.equalsIgnoreCase("submitcustomer")) {
            cuh.createNewCustomer(request, df, sessionObj, this);
            response.sendRedirect("customersubmitted.jsp");
            return;
        }

        if (page.equalsIgnoreCase("addfloorsubmit")) {
            bh.addFloors(request, df, sessionObj, this);
            response.sendRedirect("addfloor.jsp");
            return;
        }

        if (page.equalsIgnoreCase("selBdg")) {
            bh.selectBuilding(request, df, sessionObj, this);
            response.sendRedirect("addfloor.jsp");
            return;
        }

        if (page.equalsIgnoreCase("addfloor")) {
            sessionObj.setAttribute("customerSelcted", false);
            cuh.chooseCustomer(sessionObj, df);
            response.sendRedirect("addfloor.jsp");
            return;
        }

        if (page.equalsIgnoreCase("selCust")) {
            bh.loadCustomersBuildings(request, sessionObj, df);
            response.sendRedirect("addfloor.jsp");
            return;
        }

        if (page.equalsIgnoreCase("loadFloors")) {
            bh.loadFloors(request, sessionObj, df, this);
            response.sendRedirect("addfloor.jsp");
            return;
        }

        if (page.equalsIgnoreCase("selFlr")) {
            bh.selectFloor(request, sessionObj, df, this);
            response.sendRedirect("addroom.jsp");
            return;
        }

        if (page.equalsIgnoreCase("loadRooms")) {
            bh.loadRooms(request, sessionObj, df, this);
            response.sendRedirect("addroom.jsp");
            return;
        }

        if (page.equalsIgnoreCase("addroomsubmit")) {
            bh.addRoom(request, sessionObj, df, this);
            response.sendRedirect("addroom.jsp");
            return;
        }

        //loading order request page
        if (page.equalsIgnoreCase("orderRequest")) {
            bh.loadBuildingsAfterLogIn(sessionObj, df, this);
            response.sendRedirect("orderRequest.jsp");
            return;
        }

        //selecting a building for order request
        if (page.equalsIgnoreCase("selBdgReq")) {
            bh.selectBuilding(request, df, sessionObj, this);
            response.sendRedirect("orderRequest.jsp");
            return;
        }

        //create an order request
        if (page.equalsIgnoreCase("orderRequestSubmit")) {
            oh.saveOrder(request, sessionObj, df, this);
            response.sendRedirect("ordersuccess.jsp");
            return;
        }

        //displays the order history and order progress
        if (page.equalsIgnoreCase("orderhistory")) {
            oh.loadCustomerOrders(sessionObj, df, this);
            response.sendRedirect("orderhistory.jsp");
            return;
        }

        //displays the order list and order progress
        if (page.equalsIgnoreCase("orderslist")) {
            oh.loadAllOrders(sessionObj, df);
            response.sendRedirect("orderslist.jsp");
            return;
        }

        //displays the order details
        if (page.equalsIgnoreCase("vieworder")) {
            int orderNumber = Integer.parseInt(request.getParameter("ordernumber"));
            sessionObj.setAttribute("orderNumber", orderNumber);
            sessionObj.setAttribute("selectedOrder", df.getOrder(orderNumber));
            response.sendRedirect("vieworder.jsp");
            return;
        }

        //updates the order progress
        if (page.equalsIgnoreCase("updateStat")) {
            int newStat = Integer.parseInt(request.getParameter("orderstatus"));
            Order o = (Order) sessionObj.getAttribute("selectedOrder");
            df.updateStatus(o.getOrderNumber(), newStat);
            oh.loadAllOrders(sessionObj, df);
            response.sendRedirect("orderslist.jsp");
            return;
        }

        if (page.equalsIgnoreCase("continue")) {
            url = "/addroom.jsp";
        }

        if (page.equalsIgnoreCase("login")) {
            url = "/login.jsp";

        }
        if (page.equalsIgnoreCase("loguserin")) {
            if (request.getParameter("empOrCus").equals("emp")) {
                cuh.emplogin(df, request, response);
            } else {
                cuh.login(df, request, response);
            }
            url = "/login.jsp";
        }

        if (page.equalsIgnoreCase("logout")) {
            request.setAttribute("user", null);
            request.setAttribute("loggedin", false);
            request.getSession().invalidate();
            url = "/index.jsp";
        }

        if (page.equalsIgnoreCase("printReport")) {
            rh.printReport(sessionObj, df, response, this);
            return;
        }

        if (request.getServletPath().equalsIgnoreCase("/viewreports")) {
            url = "/viewreports.jsp";
        }
        if (request.getServletPath().equalsIgnoreCase("/getreport")) {
            url = "/viewreport.jsp";
        }
        System.out.println(request.getServletPath());
        System.out.println(request.getMethod());

        //get the building and send it to the sessionobj
        System.out.println("test of action: " + action);
        if (action.equalsIgnoreCase("viewbuildingadmin")) {
            System.out.println("test!");
            int buildId = Integer.parseInt(request.getParameter("buildingid"));
            Building b = df.getBuilding(buildId);
            request.getSession().setAttribute("building", b);
            request.setAttribute("showBuilding", true);
            url = "/viewbuildingadmin.jsp";

        }

        //retrieve a room from the buildingobject and put it in response.
        if (action.equalsIgnoreCase("viewroom")) {
            Building b = (Building) request.getSession().getAttribute("building");
            int roomNumber;
            String viewReportRoomString = request.getParameter("viewroom");
            if (viewReportRoomString != null && b != null) {
                roomNumber = Integer.parseInt(viewReportRoomString);
                BuildingRoom r = b.returnARoom(roomNumber);
                request.getSession().setAttribute("room", r);
                request.getSession().setAttribute("building", b);
                request.setAttribute("showRoom", true);
                url = "/viewbuildingadmin.jsp";

            }
        }

        if (action.equalsIgnoreCase("addfloor")) {
            request.setAttribute("addFloor", true);
            url = "/viewbuildingadmin.jsp";

        }
        if (action.equalsIgnoreCase("addroom")) {
            int floorId = Integer.parseInt(request.getParameter("floor"));
            request.setAttribute("addRoom", true);
            request.setAttribute("floorId", floorId);
            url = "/viewbuildingadmin.jsp";

        }
        if (action.equalsIgnoreCase("listreports")) {
            request.getSession().setAttribute("reports", df.getSimpleListOfReports());
        }

        if (action.equalsIgnoreCase("addfloorsubmit")) {
            bh.addFloors(request, df);
            url = "/viewbuildingadmin.jsp";

        }
        if (action.equalsIgnoreCase("addroomsubmit")) {
            int floorId = Integer.parseInt(request.getParameter("floorID"));
            bh.addRoom(request, df, floorId);
            request.setAttribute("showBuilding", true);
            url = "/viewbuildingadmin.jsp";

        }
        if (action.equalsIgnoreCase("editbuilding")) {
            request.setAttribute("editBuilding", true);
            url = "/viewbuildingadmin.jsp";

        }
        if (action.equalsIgnoreCase("showBuilding")) {
            request.setAttribute("showBuilding", true);
            url = "/viewbuildingadmin.jsp";

        }
        if (action.equalsIgnoreCase("showreport")) {

            int reportId = Integer.parseInt(request.getParameter("reportid"));
            Report report = df.getReport(reportId);
            Building b = df.getBuilding(report.getBuildingId());
            report.setBuildingName(b.getBuildingName());
            //
            request.getSession().setAttribute("report", report);

        }
        if (action.equalsIgnoreCase("reportroom")) {

            int reportRoomId = Integer.parseInt(request.getParameter("viewroom"));
            Report report = (Report) request.getSession().getAttribute("report");
            ReportRoom rr = report.getReportRoomFromReportFloor(reportRoomId);
            //
            request.setAttribute("reportroom", rr);
            request.setAttribute("showroom", true);
            url = "/viewreport.jsp";

        }

        //Trying to see if I can work this out
        if (action.equalsIgnoreCase("roomfiles")) {
            //int buildId = Integer.parseInt(request.getParameter("buildingid"));
            request.setAttribute("roomfiles", true);
            //request.setAttribute("reportroom", report.getReportRoomFromReportFloor(roomId) );
            url = "/viewbuildingadmin.jsp";

        }
        if (action.equalsIgnoreCase("addfloorplans")) {
            Building b = (Building) request.getSession().getAttribute("building");
            ArrayList<BuildingFloor> bfList = df.listOfFloors(b.getBdgId());
            ArrayList<Floorplan> plans = df.getFloorplans(bfList);
            request.getSession().setAttribute("floorplans", plans);
            request.getSession().setAttribute("floorsList", bfList);
            request.setAttribute("addfloorplans", true);
            url = "/viewbuildingadmin.jsp";

        }

        if (action.equalsIgnoreCase("addfilessubmit")) {
            request = nfu.addFiles(request, parts, df, this);
            url = "/viewbuildingadmin.jsp";

        }

        if (action.equalsIgnoreCase("addfloorplanssubmit")) {
            request = nfu.addFloorplans(request, parts, df, this);
            url = "/viewbuildingadmin.jsp";

        }

        if (action.equalsIgnoreCase("addBuilding")) {
            Building b = new Building();
            b.setBuildingName("tempname");
            request.getSession().setAttribute("building", b);

        }
        if (action.equalsIgnoreCase("viewbuildingadmin")) {
            int buildId = Integer.parseInt(request.getParameter("buildingid"));
            Building b = df.getBuilding(buildId);
            request.getSession().setAttribute("building", b);
        }
        if (action.equalsIgnoreCase("viewbuildingreports")) {
            request.setAttribute("viewbuildingreports", true);
            url = "/viewbuildingadmin.jsp";

        }
    } catch (PolygonException ex) {
        Logger.getLogger(FrontControl.class.getName()).log(Level.SEVERE, null, ex);
        request.setAttribute("errormessage", ex.getMessage());
        url = "/errorpage.jsp";
    }
    RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
    dispatcher.forward(request, response);
}

From source file:com.shoylpik.controller.AddProduct.java

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

    String SAVE_DIRECTORY = "shoylpik_images";
    String absolutePath = request.getServletContext().getRealPath("");
    String savePath = absolutePath + File.separator + SAVE_DIRECTORY;

    File imageSaveDirectory = new File(savePath);
    if (!imageSaveDirectory.exists()) {
        imageSaveDirectory.mkdir();/*from  ww  w  .  j ava  2 s.  co  m*/
    }

    System.out.println("imageSaveDirectory.getAbsolutePath(): " + imageSaveDirectory.getAbsolutePath());
    String fileName = null;
    //Get all the parts from request and write it to the file on server
    for (Part part : request.getParts()) {
        fileName = getFileName(part);
        System.out.println("fileName: " + fileName);
        part.write(savePath + File.separator + fileName);
    }

    try {
        System.out.println("savePath : " + savePath);
        String imageName = request.getParameter("IPimage");
        System.out.println("imageName: " + imageName);
        Part filePart = request.getPart("IPimage");
        InputStream imageInputStream = filePart.getInputStream();

        Product product = new Product();
        product.setProductId(Integer.parseInt(request.getParameter("IPID")));
        product.setProductName(request.getParameter("IPname"));
        product.setProductImageName(imageName);
        product.setProductCategory(request.getParameter("IPcat"));
        product.setProductPrice(Float.parseFloat(request.getParameter("IPprice")));
        product.setProductQuantity(Integer.parseInt(request.getParameter("IPQuant")));

        ProductBean pBean = new ProductBean();
        pBean.addProduct(product);

        String fullImagePath = savePath + File.separator + imageName;
        File file = new File(fullImagePath);
        System.out.println("fullImagePath : " + fullImagePath);
        FileOutputStream fos = new FileOutputStream(file);

        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if (!isMultipart) {

        } else {
            System.out.println("Inside else");
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List items = null;

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

            }
            Iterator itr = items.iterator();
            while (itr.hasNext()) {
                System.out.println("Inside while");
                FileItem item = (FileItem) items.iterator();
                item.write(file);
            }
        }
    } catch (SQLException ex) {
        Logger.getLogger(AddProduct.class.getName()).log(Level.SEVERE, null, ex);
    } catch (Exception ex) {
        Logger.getLogger(AddProduct.class.getName()).log(Level.SEVERE, null, ex);
    }
    response.sendRedirect("AdministrationPage.jsp");
}

From source file:com.ikon.servlet.WorkflowRegisterServlet.java

@SuppressWarnings("unchecked")
private String handleRequest(HttpServletRequest request) throws FileUploadException, IOException, Exception {
    log.debug("handleRequest({})", request);

    if (ServletFileUpload.isMultipartContent(request)) {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List<FileItem> items = upload.parseRequest(request);

        if (items.isEmpty()) {
            String msg = "No process file in the request";
            log.warn(msg);/*from  ww  w.  j av  a 2  s  . c  o m*/
            return msg;
        } else {
            FileItem fileItem = (FileItem) items.get(0);

            if (fileItem.getContentType().indexOf("application/x-zip-compressed") == -1) {
                String msg = "Not a process archive";
                log.warn(msg);
                throw new Exception(msg);
            } else {
                log.info("Deploying process archive: {}", fileItem.getName());
                JbpmContext jbpmContext = JBPMUtils.getConfig().createJbpmContext();
                InputStream isForms = null;
                ZipInputStream zis = null;

                try {
                    zis = new ZipInputStream(fileItem.getInputStream());
                    ProcessDefinition processDefinition = ProcessDefinition.parseParZipInputStream(zis);

                    // Check XML form definition
                    FileDefinition fileDef = processDefinition.getFileDefinition();
                    isForms = fileDef.getInputStream("forms.xml");
                    FormUtils.parseWorkflowForms(isForms);

                    log.debug("Created a processdefinition: {}", processDefinition.getName());
                    jbpmContext.deployProcessDefinition(processDefinition);
                    return "Process " + processDefinition.getName() + " deployed successfully";
                } finally {
                    IOUtils.closeQuietly(isForms);
                    IOUtils.closeQuietly(zis);
                    jbpmContext.close();
                }
            }
        }
    } else {
        log.warn("Not a multipart request");
        return "Not a multipart request";
    }
}

From source file:edu.fullerton.ldvservlet.Upload.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
 *
 * @param request servlet request//  w w w  .  j av  a 2s  . c o  m
 * @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 {
    long startTime = System.currentTimeMillis();

    if (!ServletFileUpload.isMultipartContent(request)) {
        throw new ServletException("This action requires a multipart form with a file attached.");
    }
    ServletSupport servletSupport;

    servletSupport = new ServletSupport();
    servletSupport.init(request, viewerConfig, false);

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

    // 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");
    factory.setRepository(repository);

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

    ImageTable imageTable;
    String viewServletPath = request.getContextPath() + "/view";

    try {
        imageTable = new ImageTable(servletSupport.getDb());
    } catch (SQLException ex) {
        String ermsg = "Image upload: can't access the Image table: " + ex.getClass().getSimpleName() + " "
                + ex.getLocalizedMessage();
        throw new ServletException(ermsg);
    }
    try {
        HashMap<String, String> params = new HashMap<>();
        ArrayList<Integer> uploadedIds = new ArrayList<>();

        Page vpage = servletSupport.getVpage();
        vpage.setTitle("Image upload");
        try {
            servletSupport.addStandardHeader(version);
            servletSupport.addNavBar();
        } catch (WebUtilException ex) {
            throw new ServerException("Adding nav bar after upload", ex);
        }

        // Parse the request
        List<FileItem> items = upload.parseRequest(request);
        int cnt = items.size();
        for (FileItem item : items) {
            if (item.isFormField()) {
                String name = item.getFieldName();
                String value = item.getString();
                if (!value.isEmpty()) {
                    params.put(name, value);
                }
            }
        }
        for (FileItem item : items) {
            if (!item.isFormField()) {
                int imgId = addFile(item, params, vpage, servletSupport.getVuser().getCn(), imageTable);
                if (imgId != 0) {
                    uploadedIds.add(imgId);
                }
            }
        }
        if (!uploadedIds.isEmpty()) {
            showImages(vpage, uploadedIds, imageTable, viewServletPath);
        }
        servletSupport.showPage(response);
    } catch (FileUploadException ex) {
        Logger.getLogger(Upload.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:controllers.ControladorFotoCoin.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//www. j  a v a2  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 {
    int idMatch = Integer.parseInt(request.getParameter("idMatch"));
    String userPath = "";
    String UPLOAD_DIRECTORY = "/Users/patriciacuevas/NetBeansProjects/PerfectMatchTis2/web/fotosUsuarios";
    if (ServletFileUpload.isMultipartContent(request)) {
        String pathFile = "";
        try {
            List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);

            for (FileItem item : multiparts) {
                if (!item.isFormField()) {
                    String name = new File(item.getName()).getName();
                    pathFile = UPLOAD_DIRECTORY + File.separator + name;
                    item.write(new File(pathFile));

                }
            }

            PmtMatchDTO match = new PmtMatchDTO();
            match.setMatId(idMatch);

            PmtIntercambioFotosDTO intercambio = new PmtIntercambioFotosDTO();
            intercambio.setInfRutaUsuarioCoincidente(pathFile);
            intercambio.setMat(match);

            intercambio.guardar(intercambio);

            request.setAttribute("message", "Su foto fue enviada exitosamente");
            userPath = "cliente";

        } catch (Exception ex) {
            request.setAttribute("message", "Error al cargar el archivo");
            userPath = "enviarFotoCoincidente";
        }

        String url = "WEB-INF/view/" + userPath + ".jspf";
        RequestDispatcher rd = request.getRequestDispatcher(url);
        rd.forward(request, response);
    }
}

From source file:Controllers.EditItem.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*from   ww  w.j  a  va2s  .co m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String id = null;
    String name = null;
    String itemCode = null;
    String price = null;
    String quantity = null;
    String category = null;
    String image = null;
    HttpSession session = request.getSession(true);
    User user = (User) session.getAttribute("user");
    if (user == null) {
        response.sendRedirect("login");
        return;
    }
    //        request.getServletContext().getRealPath("/uploads");
    String path = request.getServletContext().getRealPath("/uploads");
    System.out.println(path);

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

            for (FileItem item : multiparts) {
                if (!item.isFormField()) {
                    String fileName = new File(item.getName()).getName();
                    //                        new File(path).mkdirs();
                    File directory = new File(path + File.separator + fileName);
                    image = fileName;
                    item.write(directory);
                } else {
                    if ("name".equals(item.getFieldName())) {
                        name = item.getString();
                    } else if ("id".equals(item.getFieldName())) {
                        id = item.getString();
                    } else if ("itemCode".equals(item.getFieldName())) {
                        itemCode = item.getString();
                    } else if ("price".equals(item.getFieldName())) {
                        price = item.getString();
                    } else if ("quantity".equals(item.getFieldName())) {
                        quantity = item.getString();
                    } else if ("category".equals(item.getFieldName())) {
                        category = item.getString();
                    }
                }
            }

            //File uploaded successfully
            System.out.println("done");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    boolean status = ItemRepository.editItem(name, itemCode, price, quantity, category, image, id);
    String message;
    System.out.println(status);
    if (status) {
        message = "Item saved successfully";
        response.sendRedirect("dashboard");
    } else {
        message = "Item not saved !!";
        request.setAttribute("message", message);
        request.getRequestDispatcher("dashboard/addItem.jsp").forward(request, response);
    }
}

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

/**
 * Processes requests for both HTTP//from w w  w  .  j  av  a 2  s .c  o  m
 * <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);
    }
}