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

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

Introduction

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

Prototype

byte[] get();

Source Link

Document

Returns the contents of the file item as an array of bytes.

Usage

From source file:com.Voxce.DAO.MedicalLicenseDAO.java

public int UploadMedicalLicense(FileItem item, MedicalLicense medicallicense, int idnum) {

    if (item != null) {
        medicallicense.setData(item.get());
        medicallicense.setFilename(item.getName());
        medicallicense.setType(item.getContentType());
    }/*from   ww  w . ja va 2s  .  c  o m*/
    if (idnum == 0) {
        Calendar cal = Calendar.getInstance();
        Date oneDate = new java.sql.Date(cal.getTime().getTime());

        medicallicense.setDate_created(oneDate);
        medicallicense.setDate_modified(oneDate);
        try {
            data = hibernateTemplate.find("FROM MedicalLicense WHERE site_id='" + medicallicense.getSite_id()
                    + "' AND study_id='" + medicallicense.getStudy_id() + "' AND user_id='"
                    + medicallicense.getUser_id() + "' AND begin_dt='" + medicallicense.getBegin_dt()
                    + "' AND start_dt='" + medicallicense.getStart_dt() + "' AND expire_dt='"
                    + medicallicense.getExpire_dt() + "'");

        } catch (Exception e) {
            e.printStackTrace();
        }

        if (data.size() != 0) {
            System.out.println("Record Found");
            return 0;
        }
        // Code Does not Exists //
        else if (data.size() == 0) {
            hibernateTemplate.saveOrUpdate(medicallicense);

            return 1;
        }
    } else {
        Calendar cal = Calendar.getInstance();
        Date oneDate = new java.sql.Date(cal.getTime().getTime());
        medicallicense.setDate_modified(oneDate);

        try {
            System.out.println("editing...");
            hibernateTemplate.saveOrUpdate(medicallicense);

            return 1;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }
    return 0;

}

From source file:controller.EditProfileController.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {//from w  ww .j  av  a  2 s .  co m

        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List<FileItem> items = upload.parseRequest(request);
        Iterator<FileItem> it = items.iterator();

        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute("user");
        if (user == null) {
            user = new User();
        }
        ArrayList<String> newInterests = new ArrayList<>();
        while (it.hasNext()) {
            FileItem item = it.next();
            if (!item.isFormField()) {
                byte[] image = item.get();
                if (image != null && image.length != 0) {
                    user.setImage(image);
                }
                //                    System.out.println(user.getImage());
            } else {
                switch (item.getFieldName()) {
                case "name":
                    user.setUserName(item.getString());
                    break;
                case "mail":
                    user.setEmail(item.getString());
                    break;
                case "password":
                    user.setPassword(item.getString());
                    break;
                case "job":
                    user.setJob(item.getString());
                    break;
                case "date":
                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                    LocalDate date = LocalDate.parse(item.getString(), formatter);
                    user.setDOB(date);
                    break;
                case "address":
                    user.setAddress(item.getString());
                    break;
                case "credit":
                    user.setCreditNumber(item.getString());
                    break;
                default:
                    newInterests.add(item.getString());
                    //                            System.out.println(item.getFieldName() + " : " + item.getString());
                }
            }
        }
        user.setInterests(newInterests);
        UserDaoImpl userDao = new UserDaoImpl();
        userDao.updateUser(user);

        session.setAttribute("user", user);
        //            System.out.println(user.getInterests());
        //            System.out.println(user.getImage());
    } catch (FileUploadException ex) {
        Logger.getLogger(EditProfileController.class.getName()).log(Level.SEVERE, null, ex);
    } catch (Exception ex) {
        Logger.getLogger(EditProfileController.class.getName()).log(Level.SEVERE, null, ex);
    }
    response.sendRedirect("profile.jsp");
}

From source file:eg.agrimarket.controller.EditProfileController.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {//  w w  w  . j  ava2 s. c  o m

        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List<FileItem> items = upload.parseRequest(request);
        Iterator<FileItem> it = items.iterator();

        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute("user");
        if (user == null) {
            user = new User();
        }
        ArrayList<Interest> newInterests = new ArrayList<>();
        while (it.hasNext()) {
            FileItem item = it.next();
            if (!item.isFormField()) {
                byte[] image = item.get();
                if (image != null && image.length != 0) {
                    user.setImage(image);
                }
                //                    System.out.println(user.getImage());
            } else {
                switch (item.getFieldName()) {
                case "name":
                    user.setUserName(item.getString());
                    break;
                case "mail":
                    user.setEmail(item.getString());
                    break;
                case "password":
                    user.setPassword(item.getString());
                    break;
                case "job":
                    user.setJob(item.getString());
                    break;
                case "date":
                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                    LocalDate date = LocalDate.parse(item.getString(), formatter);
                    user.setDOB(date);
                    break;
                case "address":
                    user.setAddress(item.getString());
                    break;
                case "credit":
                    user.setCreditNumber(item.getString());
                    break;
                default:

                    eg.agrimarket.model.dto.Interest interest = new eg.agrimarket.model.dto.Interest();
                    interest.setId(Integer.parseInt(item.getString()));
                    interest.setName(item.getFieldName());
                    newInterests.add(interest);
                    System.out.println(item.getFieldName() + " : " + item.getString());
                }
            }
        }
        user.setInterests(newInterests);
        UserDaoImpl userDao = new UserDaoImpl();
        userDao.updateUser(user);

        session.setAttribute("user", user);
    } catch (FileUploadException ex) {
        Logger.getLogger(EditProfileController.class.getName()).log(Level.SEVERE, null, ex);
    } catch (Exception ex) {
        Logger.getLogger(EditProfileController.class.getName()).log(Level.SEVERE, null, ex);
    }
    response.sendRedirect("profile.jsp");
}

From source file:com.silverpeas.gallery.ImageHelper.java

/**
 * @param fileHandler//from w w  w.  j  a  va2s.c  om
 * @param photo
 * @param image
 * @param watermark
 * @param watermarkHD
 * @param watermarkOther
 * @throws Exception
 */
public static void processImage(final FileHandler fileHandler, final PhotoDetail photo, final FileItem image,
        final boolean watermark, final String watermarkHD, final String watermarkOther) throws Exception {
    final String photoId = photo.getPhotoPK().getId();
    final String instanceId = photo.getPhotoPK().getInstanceId();

    if (image != null) {
        String name = image.getName();
        if (name != null) {
            name = FileUtil.getFilename(name);
            if (ImageType.isImage(name)) {
                final String subDirectory = gallerySettings.getString("imagesSubDirectory");
                final HandledFile handledImageFile = fileHandler.getHandledFile(BASE_PATH, instanceId,
                        subDirectory + photoId, name);
                handledImageFile.writeByteArrayToFile(image.get());
                photo.setImageName(name);
                photo.setImageMimeType(image.getContentType());
                photo.setImageSize(image.getSize());
                createImage(name, handledImageFile, photo, watermark, watermarkHD, watermarkOther);
            }
        }
    }
}

From source file:com.college.AddAdditionalMarksheet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.// 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
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();

    try {

        String certificateName = request.getParameter("certificateName");

        Class.forName("com.mysql.jdbc.Driver");
        con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
        ps = con.prepareStatement("insert into certificate (studentId, certificate) values (?,?)");

        DiskFileItemFactory factory = new DiskFileItemFactory();

        ServletFileUpload sfu = new ServletFileUpload(factory);
        List items = sfu.parseRequest(request);

        Iterator iter = items.iterator();
        byte[] certificate = null;

        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();

            byte[] blobValue = item.get();
            if (blobValue != null && blobValue.length > 0) {
                String fieldName = item.getFieldName();

                if (!item.isFormField()) { //This if clause is for images.
                    if ("certificate".equalsIgnoreCase(fieldName)) {
                        certificate = blobValue;
                    }

                    // you can add more clauses here.
                } else { // This else clause if for other fields.
                    String fieldValue = new String(blobValue);
                    if (item.getFieldName() != null) {
                        if ("studentId".equalsIgnoreCase(fieldName)) {
                            studentId = fieldValue;
                        } else if ("studentName".equalsIgnoreCase(fieldName)) {
                            studentName = fieldValue;
                        }

                        // add more fields here.
                    }
                }
            }
        }

        ps.setString(1, studentId);
        ps.setBytes(2, certificate);

        int i = ps.executeUpdate();
        if (i != 0) {
            out.println("Success");
            response.sendRedirect(
                    "additionalMarksheetForm.jsp?studentName=" + studentName + "&studentId=" + studentId);
            out.println("Success");
        } else {
            out.println("Failed");
        }
    } catch (Exception ex) {
        out.println(ex);
    } finally {
        out.close();
    }
}

From source file:com.groupon.odo.HttpUtilities.java

/**
 * Sets up the given {@link org.apache.commons.httpclient.methods.PostMethod} to send the same multipart POST data
 * as was sent in the given {@link HttpServletRequest}
 *
 * @param postMethodProxyRequest The {@link org.apache.commons.httpclient.methods.PostMethod} that we are configuring to send a
 *                               multipart POST request
 * @param httpServletRequest     The {@link HttpServletRequest} that contains the multipart
 *                               POST data to be sent via the {@link org.apache.commons.httpclient.methods.PostMethod}
 *//*from  w w  w  . j a v  a2s . c o m*/
@SuppressWarnings("unchecked")
public static void handleMultipartPost(EntityEnclosingMethod postMethodProxyRequest,
        HttpServletRequest httpServletRequest, DiskFileItemFactory diskFileItemFactory)
        throws ServletException {

    // Create a new file upload handler
    ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
    // Parse the request
    try {
        // Get the multipart items as a list
        List<FileItem> listFileItems = (List<FileItem>) servletFileUpload.parseRequest(httpServletRequest);
        // Create a list to hold all of the parts
        List<Part> listParts = new ArrayList<Part>();
        // Iterate the multipart items list
        for (FileItem fileItemCurrent : listFileItems) {
            // If the current item is a form field, then create a string
            // part
            if (fileItemCurrent.isFormField()) {
                StringPart stringPart = new StringPart(fileItemCurrent.getFieldName(), // The field name
                        fileItemCurrent.getString() // The field value
                );
                // Add the part to the list
                listParts.add(stringPart);
            } else {
                // The item is a file upload, so we create a FilePart
                FilePart filePart = new FilePart(fileItemCurrent.getFieldName(), // The field name
                        new ByteArrayPartSource(fileItemCurrent.getName(), // The uploaded file name
                                fileItemCurrent.get() // The uploaded file contents
                        ));
                // Add the part to the list
                listParts.add(filePart);
            }
        }
        MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity(
                listParts.toArray(new Part[listParts.size()]), postMethodProxyRequest.getParams());

        postMethodProxyRequest.setRequestEntity(multipartRequestEntity);

        // The current content-type header (received from the client) IS of
        // type "multipart/form-data", but the content-type header also
        // contains the chunk boundary string of the chunks. Currently, this
        // header is using the boundary of the client request, since we
        // blindly copied all headers from the client request to the proxy
        // request. However, we are creating a new request with a new chunk
        // boundary string, so it is necessary that we re-set the
        // content-type string to reflect the new chunk boundary string
        postMethodProxyRequest.setRequestHeader(STRING_CONTENT_TYPE_HEADER_NAME,
                multipartRequestEntity.getContentType());
    } catch (FileUploadException fileUploadException) {
        throw new ServletException(fileUploadException);
    }
}

From source file:com.enonic.cms.domain.user.field.UserFieldTransformer.java

public UserFieldMap toUserFields(ExtendedMap form) {
    Map<String, String> map = toStringStringMap(form);
    UserFieldMap fields = fromStoreableMap(map);

    FileItem item = form.getFileItem(UserFieldType.PHOTO.getName(), null);
    if (item != null) {
        updatePhoto(fields, UserPhotoHelper.convertPhoto(item.get()));
    }//ww w  .  j av  a  2s . co m

    return fields;
}

From source file:eg.agrimarket.controller.ProductController.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {/*w w w.j  av a 2s .  c o m*/
        PrintWriter out = response.getWriter();
        eg.agrimarket.model.pojo.Product product = new eg.agrimarket.model.pojo.Product();
        Product productJPA = new Product();
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List<FileItem> items = upload.parseRequest(request);
        Iterator<FileItem> it = items.iterator();

        while (it.hasNext()) {
            FileItem item = it.next();
            if (!item.isFormField()) {
                byte[] image = item.get();
                if (image != null && image.length != 0) {
                    product.setImage(image);
                    productJPA.setImage(image);
                }
            } else {
                switch (item.getFieldName()) {
                case "name":
                    product.setName(item.getString());
                    productJPA.setName(item.getString());
                    System.out.println("name" + item.getString());
                    break;
                case "price":
                    product.setPrice(Float.valueOf(item.getString()));
                    productJPA.setPrice(Float.valueOf(item.getString()));
                    break;
                case "quantity":
                    product.setQuantity(Integer.valueOf(item.getString()));
                    productJPA.setQuantity(Integer.valueOf(item.getString()));
                    break;
                case "desc":
                    product.setDesc(item.getString());
                    productJPA.setDesc(item.getString());
                    System.out.println("desc: " + item.getString());
                    break;
                default:
                    Category category = new Category();
                    category.setId(Integer.valueOf(item.getString()));
                    product.setCategoryId(category);
                    productJPA.setCategoryId(category.getId());
                }
            }
        }

        ProductDao daoImp = new ProductDaoImp();
        boolean check = daoImp.addProduct(product);
        if (check) {
            List<Product> products = (List<Product>) request.getServletContext().getAttribute("products");
            if (products != null) {
                products.add(productJPA);
                request.getServletContext().setAttribute("products", products);

            }
            response.sendRedirect("http://" + request.getServerName() + ":" + request.getServerPort()
                    + "/AgriMarket/admin/getProducts?success=Successfully#header3-41");
        } else {
            response.sendRedirect("http://" + request.getServerName() + ":" + request.getServerPort()
                    + "/AgriMarket/admin/getProducts?status=Exist!#header3-41");
        }

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

From source file:edu.umd.cs.submitServer.servlets.HandleBuildServerLogMessage.java

/**
 * The doPost method of the servlet. <br>
 *
 * This method is called when a form has its tag value method equals to
 * post.//from w  w  w. j  av a2 s . co m
 *
 * @param request
 *            the request send by the client to the server
 * @param response
 *            the response send by the server to the client
 * @throws ServletException
 *             if an error occurred
 * @throws IOException
 *             if an error occurred
 */
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    MultipartRequest multipartRequest = (MultipartRequest) request.getAttribute(MULTIPART_REQUEST);
    FileItem fileItem = null;
    LoggingEvent loggingEvent = null;
    ObjectInputStream in = null;
    try {
        fileItem = multipartRequest.getFileItem();
        byte[] data = fileItem.get();

        in = new ObjectInputStream(new ByteArrayInputStream(data));
        loggingEvent = (LoggingEvent) in.readObject();

        buildServerLogger.callAppenders(loggingEvent);
    } catch (ClassNotFoundException e) {
        throw new ServletException("Cannot find class: " + e.getMessage(), e);
    } finally {
        if (fileItem != null)
            fileItem.delete();
        if (in != null)
            in.close();
    }
}

From source file:com.enonic.cms.core.user.field.UserFieldTransformer.java

public UserFields toUserFields(ExtendedMap formValues) {
    Map<String, String> map = toStringStringMap(formValues);
    UserFields fields = fromStoreableMap(map);

    FileItem item = formValues.getFileItem(UserFieldType.PHOTO.getName(), null);
    if (item != null) {
        updatePhoto(fields, UserPhotoHelper.convertPhoto(item.get()));
    }/*from   www .ja va2  s  .c o  m*/

    return fields;
}