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:controller.controller.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//  w w  w .j av 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");
    HttpSession session = request.getSession();
    try (PrintWriter out = response.getWriter()) {
        /* TODO output your page here. You may use following sample code. */
        String action = request.getParameter("action");
        String type = request.getParameter("type");
        System.out.println(action);
        if (action.equals("getproduct")) {
            System.out.println(type);
            DAO dao = new DAO();
            ArrayList<pro> product = dao.getProduct(type);
            session.setAttribute("product", product);
            dispatcher(request, response, "tablet.jsp");
        }

        if (action.equals("productDetail")) {
            int id = Integer.parseInt(request.getParameter("id"));
            DAO detail = new DAO();
            pro productDetail = detail.productDetail(id);
            session.setAttribute("productdetail", productDetail);
            dispatcher(request, response, "view.jsp");
        }
        if (action.equals("AddtoCart")) {
            System.out.println(action);
            shoppingCart cart = (shoppingCart) session.getAttribute("cart");

            if (cart == null) {
                System.out.println("cart: " + null);
                cart = new shoppingCart();
            }

            System.out.println("product " + session.getAttribute("productdetail"));

            pro temp = (pro) session.getAttribute("productdetail");
            int qu = temp.getQuantity();
            System.out.println("qu " + qu);
            if (qu > 0) {
                --qu;
                System.out.println("qu " + qu);
                temp.setQuantity(qu);
                //int quantity = Integer.parseInt(request.getParameter("quantity"));

                cart.addProduct(temp);
                System.out.println("cart " + cart.getProducts().size());
            }
            session.setAttribute("cart", cart);

        }
        if (action.equals("checkout")) {
            System.out.println(action);
            shoppingCart cart = (shoppingCart) session.getAttribute("cart");
            if (cart == null) {
                cart = new shoppingCart();
            }
            session.setAttribute("cart", cart);
            dispatcher(request, response, "checkout.jsp");
        }

        if (action.equals("order")) {
            shoppingCart cart = (shoppingCart) session.getAttribute("cart");
            String accid = (String) session.getAttribute("login");
            DAO dao = new DAO();
            dao.order(cart, accid);
            session.removeAttribute("cart");
            response.sendRedirect("index.jsp");

        }
        if (action.equals("upload")) {

            String dirNames = "D:\\Task\\IU\\Web Application Development\\New\\Final project\\ECommerceProject";

            String user = (String) session.getAttribute("login");

            String fileName = null;
            boolean isMultiPArt = ServletFileUpload.isMultipartContent(request);

            if (isMultiPArt) {
                System.out.println(1);
                FileItemFactory factory = new DiskFileItemFactory();
                ServletFileUpload upload = new ServletFileUpload(factory);
                List items = null;
                try {
                    items = upload.parseRequest(request);
                } catch (FileUploadException e) {
                    e.printStackTrace();
                }
                Iterator iter = items.iterator();
                Hashtable params = new Hashtable();

                File theDir = new File(dirNames + File.separator + user);

                // if the directory does not exist, create it
                if (!theDir.exists()) {
                    System.out.println("creating directory: " + user);
                    boolean result = false;

                    try {
                        theDir.mkdir();
                        result = true;
                    } catch (SecurityException se) {
                        //handle it
                    }
                    if (result) {
                        System.out.println("DIR created");
                    }
                }
                String[] url = new String[5];
                int cnt = 0;
                while (iter.hasNext()) {
                    FileItem item = (FileItem) iter.next();
                    if (item.isFormField()) {
                        params.put(item.getFieldName(), item.getString());
                    } else {
                        try {
                            String itemName = item.getName();
                            fileName = itemName.substring(itemName.lastIndexOf("\\") + 1);
                            System.out.println("path: " + fileName);
                            String realPath = dirNames + File.separator + user + File.separator + fileName;
                            System.out.println("realPath: " + realPath);
                            File savedFile = new File(realPath);
                            item.write(savedFile);
                            url[cnt] = "./database" + File.separator + user + File.separator + fileName;
                            ++cnt;
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }

                String name = (String) params.get("name");
                String price = (String) params.get("price");
                String quantity = (String) params.get("quantity");
                String typepr = (String) params.get("type");

                System.out.println(name + " " + price + " " + quantity + " " + typepr);

                DAO uploadReal = new DAO();
                uploadReal.inserPro(name, price, quantity, typepr, url[0]);
                //                        newUser = new User();
                //                        newUser.setEmail(Email);
                out.print(url[0]);
                String temp = ".\\User" + File.separator + user + File.separator + fileName;
                System.out.println("Temp " + temp);

                //Connector.editUser(myProfile.getEmail(), newUser);
                //response.sendRedirect("index.jsp");
                dispatcher(request, response, "index.jsp");
            }

        }
    }

}

From source file:com.eufar.asmm.server.UploadFunction.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    System.out.println("UploadFunction - the function started");
    response.setContentType("text/html;charset=UTF-8");
    response.addHeader("Cache-Control", "no-cache,no-store");
    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    try {// w  w  w .  j a v a2s . co m
        List items = upload.parseRequest(request);
        Iterator iter = items.iterator();
        while (iter.hasNext()) {
            Object obj = iter.next();
            org.apache.commons.fileupload.FileItem item = (org.apache.commons.fileupload.FileItem) obj;
            if (FilenameUtils.getExtension(item.getName()).matches("(xml|XML)")) {
                if (item.isFormField()) {
                    String name = item.getName();
                    String value = "";
                    if (name.compareTo("textBoxFormElement") == 0) {
                        value = item.getString();
                    } else {
                        value = item.getString();
                    }
                    response.getWriter().write(name + "=" + value + "\n");
                } else {
                    byte[] fileContents = item.get();
                    String message = new String(fileContents);
                    response.setCharacterEncoding("UTF-8");
                    response.setContentType("text/html");
                    response.getWriter().write(message);
                    System.out.println("UploadFunction - file uploaded");
                }
            } else {
                System.out.println("UploadFunction - file rejected: wrong format");
                response.setCharacterEncoding("UTF-8");
                response.setContentType("text/html");
                response.getWriter().write("format");
            }
        }
    } catch (Exception ex) {
        System.out.println("UploadFunction - a problem occured: " + ex);
        response.getWriter().write("ERROR:" + ex.getMessage());
    }
}

From source file:gov.nih.nci.caadapter.ws.AddNewScenario.java

/** **********************************************************
 *  doPost()//from  w w  w .ja v  a  2s.co m
 ************************************************************ */
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    try {
        /* disable security for caAdatper 4.3 release 03-31-2009
         HttpSession session = req.getSession(false);
                
          if(session==null)
          {
          res.sendRedirect("/caAdapterWS/login.do");
          return;
          }
                
          String user = (String) session.getAttribute("userid");
          System.out.println(user);
          AbstractSecurityDAO abstractDao= DAOFactory.getDAO();
          SecurityAccessIF getSecurityAccess = abstractDao.getSecurityAccess();
          Permissions perm = getSecurityAccess.getUserObjectPermssions(user, 1);
          System.out.println(perm);
          if (!perm.getCreate()){
          System.out.println("No create Permission for user" + user);
          res.sendRedirect("/caAdapterWS/permissionmsg.do");
          return;
          }
          */
        String name = "EMPTY";

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

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

        // Parse the request
        List /* FileItem */ items = upload.parseRequest(req);

        // Process the uploaded items
        Iterator iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();

            if (item.isFormField()) {
                if (item.getFieldName().equals("MSName")) {
                    MSName = item.getString();
                    path = System.getProperty("gov.nih.nci.caadapter.path");
                    if (path == null)
                        path = ScenarioUtil.SCENARIO_HOME;
                    File scnHome = new File(path);
                    if (!scnHome.exists())
                        scnHome.mkdir();
                    path = path + "/";
                    System.out.println(path);
                    boolean exists = (new File(path + MSName)).exists();
                    if (exists) {
                        System.out.println("Scenario exists, overwriting ... ...");
                        String errMsg = "Scenario exists, not able to save:" + MSName;
                        req.setAttribute("rtnMessage", errMsg);
                        res.sendRedirect("/caAdapterWS/errormsg.do");
                        return;
                    } else {
                        boolean success = (new File(path + MSName)).mkdir();
                        if (!success) {
                            System.out.println("New scenario, Creating ... ...");
                        }
                    }

                }
            } else {
                System.out.println(item.getFieldName());
                name = item.getFieldName();

                String filePath = item.getName();
                String fileName = extractOriginalFileName(filePath);
                System.out.println("AddNewScenario.doPost()..original file Name:" + fileName);
                if (fileName == null || fileName.equals(""))
                    continue;
                String uploadedFilePath = path + MSName + "/" + fileName;
                System.out.println("AddNewScenario.doPost()...write data to file:" + uploadedFilePath);
                File uploadedFile = new File(uploadedFilePath);
                if (name.equals("mappingFileName")) {
                    String uploadedMapBak = uploadedFilePath + ".bak";
                    //write bak of Mapping file
                    item.write(new File(uploadedMapBak));
                    updateMapping(uploadedMapBak);
                } else
                    item.write(uploadedFile);
            }
        }
        ScenarioUtil.addNewScenarioRegistration(MSName);
        res.sendRedirect("/caAdapterWS/success.do");

    } catch (NullPointerException ne) {
        System.out.println("Error in doPost: " + ne);
        req.setAttribute("rtnMessage", ne.getMessage());
        res.sendRedirect("/caAdapterWS/errormsg.do");
    } catch (Exception e) {
        System.out.println("Error in doPost: " + e);
        req.setAttribute("rtnMessage", e.getMessage());
        res.sendRedirect("/caAdapterWS/error.do");
    }
}

From source file:com.alibaba.citrus.service.requestcontext.rundata.RunDataTests.java

@Test
public void multipartForm() throws Exception {
    assertEquals("hello", requestContext.getParameters().getString("myparam"));

    FileItem fileItem = requestContext.getParameters().getFileItem("myfile");

    assertEquals("myfile", fileItem.getFieldName());
    assertEquals(new File(srcdir, "smallfile.txt"), new File(fileItem.getName()));
    assertFalse(fileItem.isFormField());
    assertEquals(new String("?".getBytes("GBK"), "8859_1"), fileItem.getString());
    assertEquals("?", fileItem.getString("GBK"));
    assertTrue(fileItem.isInMemory());//from w  w  w . j  a  va2  s .c  om
}

From source file:net.i2cat.csade.life2.backoffice.servlet.UserManagementService.java

/**
 * Funcin que se ejecuta cuando el servlet recibe los datos
 *//*from  w  w  w  .j  a  va2 s .c  om*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    ChangablePropertiesManager cpm = new ChangablePropertiesManager(this.getServletContext());
    String operation = request.getParameter("operation");
    PlatformUserManager pum = new PlatformUserManager();
    String data = "";
    if (operation != null && !"".equals(operation)) {
        if (operation.equals("savePicturePreference")) {
            String photo_hor = request.getParameter("photo_hor");
            cpm.saveProperty("photo_hor", photo_hor);

            data = "{ \"message\": \"preferences saved.\" }";
        }
        if (operation.equals("getPicturePreference")) {
            String photo_hor = cpm.getProperty("photo_hor");

            data = "{ \"photo_hor\": \"" + photo_hor + "\"}";
        }

        if (operation.equals("getPlatformUser")) {
            String login = request.getParameter("login");
            try {
                data = pum.getUser(login).toJSON().toString();
            } catch (RemoteException re) {
                data = "{ \"message\": \"Could not not retrieve user with login=" + login + " Reason:"
                        + re.getMessage() + ".\" }";
            } catch (ServiceException se) {
                data = "{ \"message\": \"Could not not retrieve user with login=" + login + " Reason:"
                        + se.getMessage() + ".\" }";
            }
        }
        if (operation.equals("delPlatformUser")) {
            String login = request.getParameter("login");
            try {
                if (!request.isUserInRole("admin"))
                    throw new ServiceException("You are not allowed to delete users");
                if (login != null && login.equals(request.getUserPrincipal().getName()))
                    throw new ServiceException("You cannot delete your own user");
                pum.deleteUser(login);
                data = "{ \"message\": \"User with login " + login + " deleted.\" }";
            } catch (RemoteException re) {
                data = "{ \"message\": \"Could not not delete user with login=" + login + " Reason:"
                        + re.getMessage() + ".\" }";
            } catch (ServiceException se) {
                data = "{ \"message\": \"Could not not delete user with login=" + login + " Reason:"
                        + se.getMessage() + ".\" }";
            }
        }
        if (operation.equals("savePlatformUser")) {
            FileItem uploadedFile = null;
            PlatformUser user = null;
            int res = 0;
            byte[] foto = null;
            try {
                if (!request.isUserInRole("admin"))
                    throw new ServiceException("You are not allowed to upadte users");
                user = new PlatformUser();
                user.setNew(false);
                ServletFileUpload sfu = new ServletFileUpload(new DiskFileItemFactory());
                sfu.setFileSizeMax(329000);
                sfu.setHeaderEncoding("UTF-8");
                @SuppressWarnings("unchecked")
                List<FileItem> items = sfu.parseRequest(request);

                for (FileItem item : items) {
                    if (item.isFormField()) {
                        if (item.getFieldName().equals("login"))
                            user.setLogin(item.getString());
                        if (item.getFieldName().equals("username"))
                            user.setLogin(item.getString());
                        if (item.getFieldName().equals("password")) {
                            user.setPass(item.getString());
                        }
                        if (item.getFieldName().equals("idUser")) {
                            if (item.getString() == null || "".equals(item.getString()))
                                user.setNew(true);
                        }
                        if (item.getFieldName().equals("name")) {
                            byte[] fnb = item.get();
                            String text = PasswordGenerator.utf8Decoder(fnb);
                            user.setName(text);
                        }
                        if (item.getFieldName().equals("email")) {
                            String mail = item.getString();
                            if (MailUtils.isValidEmail(mail))
                                user.setEmail(mail);
                            else
                                throw new ServiceException("El email del usuario es incorrecto");
                        }
                        if (item.getFieldName().equals("telephonenumber"))
                            user.setTelephonenumber(item.getString());
                        if (item.getFieldName().equals("role"))
                            user.setRole(Integer.parseInt(item.getString()));
                        if (item.getFieldName().equals("language"))
                            user.setLanguage(item.getString());
                        if (item.getFieldName().equals("notification_level"))
                            user.setNotification_level(item.getString());
                        if (item.getFieldName().equals("promoter_id"))
                            user.setPromoter_id(item.getString());
                        if (item.getFieldName().equals("user_average_mark"))
                            user.setUser_average_mark(item.getString());
                        if (item.getFieldName().equals("user_votes"))
                            user.setUser_votes(item.getString());
                        if (item.getFieldName().equals("latitude"))
                            user.setHome_area_lat(item.getString());
                        if (item.getFieldName().equals("longitude"))
                            user.setHome_area_lon(item.getString());
                        if (item.getFieldName().equals("enabled"))
                            user.setEnabled(item.getString().equals("0") ? 0 : 1);
                    } else {
                        uploadedFile = item;
                        String inputExtension = FilenameUtils
                                .getExtension(uploadedFile.getName().toLowerCase());
                        if ("jpg".equals(inputExtension) || "gif".equals(inputExtension)
                                || "png".equals(inputExtension)) {
                            InputStream filecontent = item.getInputStream();
                            foto = new byte[(int) uploadedFile.getSize()];
                            filecontent.read(foto, 0, (int) uploadedFile.getSize());

                        }
                        //else
                        //   throw new FileUploadException("Extension not supported. Only jpg,gif or png files are allowed");
                    }
                }
                res = pum.saveUser(user);
                if (foto != null) {
                    //String v=cpm.getProperty("photo_hor");
                    //byte[] resizedPhoto=ImageUtil.resizeImageAsJPG(foto, (v==null || "".equals(v)) ?200:Integer.parseInt(v));
                    pum.uploadFoto(user.getLogin(), foto);
                }
                data = "{ \"message\": \"User with login " + user.getLogin() + " (id=" + res + ") saved.\" }";
            } catch (RemoteException exc) {
                data = "{ \"message\": \"Could not not save user with login=" + user.getLogin() + " Reason:"
                        + exc.getMessage() + ".\" }";
            } catch (ServiceException exc) {
                data = "{ \"message\": \"Could not not save user with login=" + user.getLogin() + " Reason:"
                        + exc.getMessage() + ".\" }";
            } catch (FileUploadException exc) {
                data = "{ \"message\": \"User with login " + user.getLogin() + " (id=" + res
                        + ") saved, but there was a problem uploading picture:" + exc.getMessage() + "\" }";
            }
        }
        if (operation.equals("listPlatformUsers")) {
            JQueryDataTableParamModel param = DataTablesParamUtility.getParam(request);
            try {
                JSONObject jsonResponse = pum.getPlatformUsersJSON(param);
                data = jsonResponse.toString();

            } catch (RemoteException re) {
                data = "{ \"message\": \"Could not not retrieve platform user listing. Reason:"
                        + re.getMessage() + ".\" }";
            } catch (ServiceException se) {
                data = "{ \"message\": \"Could not not retrieve platform user listing.  Reason:"
                        + se.getMessage() + ".\" }";
            }
        }
    }
    response.setContentType("application/json;charset=UTF-8");
    //response.setContentType("application/json");
    response.getWriter().print(data);
    response.getWriter().close();
}

From source file:com.apt.ajax.controller.AjaxUpload.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*  w w  w  .j  a  v a 2s.  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("application/json");

    String uploadDir = request.getServletContext().getRealPath(File.separator) + "upload";
    Gson gson = new Gson();
    MessageBean messageBean = new MessageBean();
    try (PrintWriter out = response.getWriter()) {
        /* TODO output your page here. You may use following sample code. */
        File x = new File(uploadDir);
        if (!x.exists()) {
            x.mkdir();
        }
        boolean isMultiplePart = ServletFileUpload.isMultipartContent(request);

        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        if (!isMultiplePart) {

        } else {
            List items = null;

            try {
                items = upload.parseRequest(request);
                if (items != null) {
                    Iterator iterator = items.iterator();
                    String assignmentId = "";
                    String stuid = "";
                    while (iterator.hasNext()) {
                        FileItem item = (FileItem) iterator.next();
                        if (item.isFormField()) {
                            String fieldName = item.getFieldName();
                            if (fieldName.equals("assignmentid")) {
                                assignmentId = item.getString();
                                File c = new File(uploadDir + File.separator + assignmentId);
                                if (!c.exists()) {
                                    c.mkdir();
                                }
                                uploadDir = c.getPath();
                                if (request.getSession().getAttribute("studentId") != null) {
                                    stuid = request.getSession().getAttribute("studentId").toString();
                                    File stuDir = new File(uploadDir + File.separator + stuid);
                                    if (!stuDir.exists()) {
                                        stuDir.mkdir();
                                    }
                                    uploadDir = stuDir.getPath();
                                }
                            }
                        } else {
                            String itemname = item.getName();
                            if (itemname == null || itemname.equals("")) {
                            } else {
                                String filename = FilenameUtils.getName(itemname);
                                File f = new File(uploadDir + File.separator + filename);
                                String[] split = f.getPath().split(Pattern.quote(File.separator) + "upload"
                                        + Pattern.quote(File.separator));
                                String save = split[split.length - 1];
                                if (assignmentId != null && !assignmentId.equals("")) {
                                    if (stuid != null && !stuid.equals("")) {

                                    } else {
                                        Assignment assignment = new AssignmentFacade()
                                                .findAssignment(Integer.parseInt(assignmentId));
                                        assignment.setUrl(save);
                                        new AssignmentFacade().updateAssignment(assignment);
                                    }
                                }
                                item.write(f);
                                messageBean.setStatus(0);
                                messageBean.setMessage("File " + f.getName() + " sucessfuly uploaded");

                            }
                        }
                    }
                }

                gson.toJson(messageBean, out);
            } catch (Exception ex) {
                messageBean.setStatus(1);
                messageBean.setMessage(ex.getMessage());
                gson.toJson(messageBean, out);
            }

        }
    } catch (Exception ex) {
        Logger.getLogger(AjaxUpload.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.eufar.emc.server.UploadFunction.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    System.out.println("UploadFunction - the function started");
    response.setContentType("text/html;charset=UTF-8");
    response.addHeader("Cache-Control", "no-cache,no-store");
    @SuppressWarnings("unused")
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    try {//  w  w  w  . j a  v a  2  s  . co m
        List<?> items = upload.parseRequest(request);
        Iterator<?> iter = items.iterator();
        while (iter.hasNext()) {
            Object obj = iter.next();
            if (obj == null) {
                continue;
            }
            org.apache.commons.fileupload.FileItem item = (org.apache.commons.fileupload.FileItem) obj;
            if (FilenameUtils.getExtension(item.getName()).matches("(xml|XML)")) {
                if (item.isFormField()) {
                    String name = item.getName();
                    String value = "";
                    if (name.compareTo("textBoxFormElement") == 0) {
                        value = item.getString();
                    } else {
                        value = item.getString();
                    }
                    response.getWriter().write(name + "=" + value + "\n");
                } else {
                    byte[] fileContents = item.get();
                    String message = new String(fileContents);
                    response.setCharacterEncoding("UTF-8");
                    response.setContentType("text/html");
                    response.getWriter().write(message);
                    System.out.println("UploadFunction - file uploaded");
                }
            } else {
                System.out.println("UploadFunction - file rejected: wrong format");
                response.setCharacterEncoding("UTF-8");
                response.setContentType("text/html");
                response.getWriter().write("format");
            }
        }
    } catch (Exception ex) {
        System.out.println("UploadFunction - a problem occured: " + ex);
        response.getWriter().write("ERROR:" + ex.getMessage());
    }
}

From source file:it.biblio.servlets.Modificapub.java

/**
 * metodo per gestire l'upload di file e inserimento dati
 *
 * @param request//from   www .  ja  va 2  s  .co m
 * @param response
 * @return
 * @throws IOException
 */
private boolean upload(HttpServletRequest request) throws IOException, SQLException, Exception {
    HttpSession s = SecurityLayer.checkSession(request);

    Map<String, Object> pub = new HashMap<String, Object>();
    Map<String, Object> ristampe = new HashMap<String, Object>();
    Map<String, Object> keyword = new HashMap<String, Object>();
    Map<String, Object> storyboard = new HashMap<String, Object>();

    if (ServletFileUpload.isMultipartContent(request)) {
        FileItemFactory fif = new DiskFileItemFactory();
        ServletFileUpload sfo = new ServletFileUpload(fif);
        List<FileItem> items = sfo.parseRequest(request);
        for (FileItem item : items) {
            String fname = item.getFieldName();
            if (item.isFormField() && fname.equals("titolo") && !item.getString().isEmpty()) {
                pub.put("titolo", item.getString());
            } else if (item.isFormField() && fname.equals("autore") && !item.getString().isEmpty()) {
                pub.put("Autore", item.getString());
            } else if (item.isFormField() && fname.equals("descrizione") && !item.getString().isEmpty()) {
                pub.put("descrizione", item.getString());
            } else if (item.isFormField() && fname.equals("categoria") && !item.getString().isEmpty()) {
                pub.put("categoria", item.getString());
            } else if (item.isFormField() && fname.equals("ISBN") && !item.getString().isEmpty()) {
                ristampe.put("isbn", item.getString());
            } else if (item.isFormField() && fname.equals("numero_pagine") && !item.getString().isEmpty()) {
                ristampe.put("numpagine", Integer.parseInt(item.getString()));
            } else if (item.isFormField() && fname.equals("anno_pub") && !item.getString().isEmpty()) {
                ristampe.put("datapub", item.getString());
            } else if (item.isFormField() && fname.equals("editore") && !item.getString().isEmpty()) {
                ristampe.put("editore", item.getString());
            } else if (item.isFormField() && fname.equals("lingua") && !item.getString().isEmpty()) {
                ristampe.put("lingua", item.getString());
            } else if (item.isFormField() && fname.equals("indice") && !item.getString().isEmpty()) {
                ristampe.put("indice", item.getString());
            } else if (item.isFormField() && fname.equals("keyword") && !item.getString().isEmpty()) {
                keyword.put("tag1", item.getString());
            } else if (item.isFormField() && fname.equals("keyword2") && !item.getString().isEmpty()) {
                keyword.put("tag2", item.getString());
            } else if (item.isFormField() && fname.equals("keyword3") && !item.getString().isEmpty()) {
                keyword.put("tag3", item.getString());
            } else if (item.isFormField() && fname.equals("idkey") && !item.getString().isEmpty()) {
                keyword.put("id", item.getString());
            } else if (item.isFormField() && fname.equals("idpub") && !item.getString().isEmpty()) {
                pub.put("id", item.getString());
            } else if (item.isFormField() && fname.equals("idris") && !item.getString().isEmpty()) {
                ristampe.put("isbn", item.getString());
            } else if (item.isFormField() && fname.equals("modifica") && !item.getString().isEmpty()) {
                storyboard.put("descrizione_modifica", item.getString());
            } else if (!item.isFormField() && fname.equals("PDF")) {
                String name = item.getName();
                long size = item.getSize();
                if (size > 0 && !name.isEmpty()) {
                    File target = new File(getServletContext().getRealPath("") + File.separatorChar + "PDF"
                            + File.separatorChar + name);
                    item.write(target);
                    ristampe.put("download", "PDF" + File.separatorChar + name);
                }
            } else if (!item.isFormField() && fname.equals("copertina")) {
                String name = item.getName();
                long size = item.getSize();
                if (size > 0 && !name.isEmpty()) {
                    File target = new File(getServletContext().getRealPath("") + File.separatorChar
                            + "Copertine" + File.separatorChar + name);
                    item.write(target);
                    ristampe.put("copertina", "Copertine" + File.separatorChar + name);
                }
            }
        }

        storyboard.put("id_utente", s.getAttribute("userid"));
        storyboard.put("id_pub", pub.get("id"));

        if (Database.updateRecord("keyword", keyword, "id=" + keyword.get("id"))) {

            Database.updateRecord("pubblicazioni", pub, "id=" + pub.get("id"));
            Database.insertRecord("storyboard", storyboard);
            Database.updateRecord("ristampe", ristampe, "isbn=" + ristampe.get("isbn"));

            return true;
        } else {
            return false;
        }
    }
    return false;
}

From source file:it.swim.servlet.profilo.azioni.RilasciaFeedBackServlet.java

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
 *      response)//from   ww  w.j  a va  2s . c o m
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // ottengo l'email dell'utente collegato dalla sessione, appoggiandomi
    // ad una classe di utilita'
    String emailUtenteCollegato = (String) UtenteCollegatoUtil.getEmailUtenteCollegato(request);
    List<FileItem> items;
    int punteggioFeedBack = 0;
    String commento = "";
    // se e' null e' perche' l'utente non e' collegato e allora devo fare il
    // redirect alla home

    if (emailUtenteCollegato == null) {
        response.sendRedirect("../../home");
        return;
    }

    try {
        items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
        for (FileItem item : items) {
            if (item.isFormField()) {
                // Process regular form field (input
                // type="text|radio|checkbox|etc", select, etc).
                // ... (do your job here)
                if (item.getFieldName().equals("punteggioFeedBack")) {
                    punteggioFeedBack = Integer.parseInt(item.getString().trim());
                }
                if (item.getFieldName().equals("commentoFeedBack")) {
                    commento = item.getString().trim();
                }
            }
        }
    } catch (FileUploadException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    if (punteggioFeedBack < 1 || punteggioFeedBack > 5) {
        request.setAttribute("erroreNelPunteggio", "Il punteggio deve essere compreso tra 1 e 5");
        getServletConfig().getServletContext().getRequestDispatcher("/jsp/utenti/profilo/rilascioFeedBack.jsp")
                .forward(request, response);
        return;
    }
    if (commento.isEmpty()) {
        commento = "Non ci sono commenti rilasciati";
    }
    try {
        collab.rilasciaFeedback(idCollaborazione, punteggioFeedBack, commento);
    } catch (LoginException e) {
        // TODO Auto-generated catch block
        request.setAttribute("erroreNelPunteggio", "Collaborazione a cui aggiungere il feedBack non trovata");
        getServletConfig().getServletContext().getRequestDispatcher("/jsp/utenti/profilo/rilascioFeedBack.jsp")
                .forward(request, response);
        return;
    }
    request.setAttribute("feedBackRilasciato", "Feedback rilasciato con successo");
    getServletConfig().getServletContext().getRequestDispatcher("/jsp/utenti/profilo/rilascioFeedBack.jsp")
            .forward(request, response);

}

From source file:admin.controller.ServletUploadFonts.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from   w  ww.j  a va 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
 */
@Override
public void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    super.processRequest(request, response);
    response.setContentType("text/html;charset=UTF-8");
    String filePath;
    String file_name = null, field_name, upload_path;
    RequestDispatcher request_dispatcher;
    String font_name = "", look_id;
    String font_family_name = "";
    PrintWriter out = response.getWriter();
    File file;
    int maxFileSize = 5000 * 1024;
    int maxMemSize = 5000 * 1024;

    try {

        // 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();

            while (i.hasNext()) {
                FileItem fi = (FileItem) i.next();
                if (fi.isFormField()) {
                    // Get the uploaded file parameters
                    field_name = fi.getFieldName();
                    if (field_name.equals("fontname")) {
                        font_name = fi.getString();
                    }
                    if (field_name.equals("fontstylecss")) {
                        font_family_name = fi.getString();
                    }

                } else {

                    //                        check = fonts.checkAvailability(font_name);
                    //                        if (check == false){

                    field_name = fi.getFieldName();
                    file_name = fi.getName();

                    if (file_name != "") {
                        File uploadDir = new File(AppConstants.BASE_FONT_UPLOAD_PATH);
                        if (!uploadDir.exists()) {
                            uploadDir.mkdirs();
                        }

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

                        filePath = AppConstants.BASE_FONT_UPLOAD_PATH + File.separator + file_name;
                        File storeFile = new File(filePath);

                        fi.write(storeFile);

                        out.println("Uploaded Filename: " + filePath + "<br>");
                    }
                    fonts.addFont(font_name, file_name, font_family_name);
                    response.sendRedirect(request.getContextPath() + "/admin/fontsfamily.jsp");

                    //                            }else {
                    //                                response.sendRedirect(request.getContextPath() + "/admin/fontsfamily.jsp?exist=exist");
                    //                            }
                }
            }
        }

    } catch (Exception e) {
        logger.log(Level.SEVERE, "Exception while uploading fonts", e);
    }
}