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

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

Introduction

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

Prototype

long getSize();

Source Link

Document

Returns the size of the file item.

Usage

From source file:com.example.web.Update_profile.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {
        /* TODO output your page here. You may use following sample code. */

        String fileName = "";
        int f = 0;
        String user = null;/*from  w w  w .  j  av  a  2s  . c o m*/
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("user")) {
                    user = cookie.getValue();
                }
            }
        }
        String email = request.getParameter("email");
        String First_name = request.getParameter("First_name");
        String Last_name = request.getParameter("Last_name");
        String Phone_number_1 = request.getParameter("Phone_number_1");
        String Address = request.getParameter("Address");
        String message = "";
        int valid = 1;
        String query;
        ResultSet rs;
        Connection conn;
        String url = "jdbc:mysql://localhost:3306/";
        String dbName = "tworld";
        String driver = "com.mysql.jdbc.Driver";
        isMultipart = ServletFileUpload.isMultipartContent(request);
        if (isMultipart) {
            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("/var/lib/tomcat7/webapps/www_term_project/temp/"));
            factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);
            // maximum file size to be uploaded.
            upload.setSizeMax(maxFileSize);

            try {
                // 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
                        String fieldName = fi.getFieldName();
                        fileName = fi.getName();
                        String contentType = fi.getContentType();
                        boolean isInMemory = fi.isInMemory();
                        long sizeInBytes = fi.getSize();
                        String[] spliting = fileName.split("\\.");
                        // Write the file
                        System.out.println(sizeInBytes + " " + maxFileSize);
                        System.out.println(spliting[spliting.length - 1]);
                        if (!fileName.equals("")) {
                            if ((sizeInBytes < maxFileSize) && (spliting[spliting.length - 1].equals("jpg")
                                    || spliting[spliting.length - 1].equals("png")
                                    || spliting[spliting.length - 1].equals("jpeg"))) {

                                if (fileName.lastIndexOf("\\") >= 0) {
                                    file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\")));
                                } else {
                                    file = new File(
                                            filePath + fileName.substring(fileName.lastIndexOf("\\") + 1));
                                }
                                fi.write(file);
                                System.out.println("Uploaded Filename: " + fileName + "<br>");
                            } else {
                                valid = 0;
                                message = "not a valid image";
                            }
                        }
                    }
                    BufferedReader br = null;
                    StringBuilder sb = new StringBuilder();

                    String line;
                    try {
                        br = new BufferedReader(new InputStreamReader(fi.getInputStream()));
                        while ((line = br.readLine()) != null) {
                            sb.append(line);
                        }
                    } catch (IOException e) {
                    } finally {
                        if (br != null) {
                            try {
                                br.close();
                            } catch (IOException e) {
                            }
                        }
                    }
                    if (f == 0) {
                        email = sb.toString();
                    } else if (f == 1) {
                        First_name = sb.toString();
                    } else if (f == 2) {
                        Last_name = sb.toString();
                    } else if (f == 3) {
                        Phone_number_1 = sb.toString();
                    } else if (f == 4) {
                        Address = sb.toString();
                    }
                    f++;

                }
            } catch (Exception ex) {
                System.out.println("hi");
                System.out.println(ex);

            }
        }
        try {
            Class.forName(driver).newInstance();
            conn = DriverManager.getConnection(url + dbName, "admin", "admin");
            if (!email.equals("")) {
                PreparedStatement pst = (PreparedStatement) conn
                        .prepareStatement("update `tworld`.`users` set `email`=? where `Username`=?");
                pst.setString(1, email);
                pst.setString(2, user);
                pst.executeUpdate();
                pst.close();
            }
            if (!First_name.equals("")) {
                PreparedStatement pst = (PreparedStatement) conn
                        .prepareStatement("update `tworld`.`users` set `First_name`=? where `Username`=?");
                pst.setString(1, First_name);
                pst.setString(2, user);
                pst.executeUpdate();
                pst.close();
            }
            if (!Last_name.equals("")) {
                PreparedStatement pst = (PreparedStatement) conn
                        .prepareStatement("update `tworld`.`users` set `Last_name`=? where `Username`=?");
                pst.setString(1, Last_name);
                pst.setString(2, user);
                pst.executeUpdate();
                pst.close();
            }
            if (!Phone_number_1.equals("")) {
                PreparedStatement pst = (PreparedStatement) conn
                        .prepareStatement("update `tworld`.`users` set `Phone_number_1`=? where `Username`=?");
                pst.setString(1, Phone_number_1);
                pst.setString(2, user);
                pst.executeUpdate();
                pst.close();
            }
            if (!Address.equals("")) {
                PreparedStatement pst = (PreparedStatement) conn
                        .prepareStatement("update `tworld`.`users` set `Address`=? where `Username`=?");
                pst.setString(1, Address);
                pst.setString(2, user);
                pst.executeUpdate();
                pst.close();
            }
            if (!fileName.equals("")) {
                PreparedStatement pst = (PreparedStatement) conn
                        .prepareStatement("update `tworld`.`users` set `Fototitle`=? where `Username`=?");
                pst.setString(1, fileName);
                pst.setString(2, user);
                pst.executeUpdate();
                pst.close();
            }

        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | SQLException ex) {
            System.out.println("hi mom");
        }

        request.setAttribute("s_page", "4");
        request.getRequestDispatcher("/index.jsp").forward(request, response);
    }
}

From source file:fr.paris.lutece.plugins.stock.modules.billetterie.web.ShowJspBean.java

/**
 * Get the poster in the request and write it on the disk.
 *
 * @param request/* w ww.j  av a2s.co m*/
 *            http request (multipart if contains poster)
 * @param product
 *            product entity
 * @return the poster image file (0 : thumbnail, 1 : full size)
 * @throws BusinessException
 *             the business exception
 */
private File[] writePoster(HttpServletRequest request, ShowDTO product) throws BusinessException {
    File[] filePosterArray = null;
    boolean fileGotten = false;

    // File uploaded
    if (request instanceof MultipartHttpServletRequest) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        FileItem fileItem = multipartRequest.getFile(PARAMETER_POSTER);

        if ((fileItem != null) && (fileItem.getSize() > 0)) {
            InputStream fisPoster = null;

            try {
                fisPoster = fileItem.getInputStream();

                // File fPoster = new File( new File( posterFolderPath ),
                // fileItem.getName( ) );
                File fPoster = File.createTempFile(FilenameUtils.getBaseName(fileItem.getName()), null);

                // Generate unique name
                fPoster = fr.paris.lutece.plugins.stock.utils.FileUtils.getUniqueFile(fPoster);

                // Store poster picture
                fr.paris.lutece.plugins.stock.utils.FileUtils.writeInputStreamToFile(fisPoster, fPoster);

                File fPosterResize = ImageUtils.resizeImage(fPoster,
                        AppPropertiesService.getPropertyInt(PROPERTY_POSTER_MAX_WIDTH,
                                PROPERTY_POSTER_MAX_WIDTH_DEFAULT),
                        AppPropertiesService.getPropertyInt(PROPERTY_POSTER_MAX_HEIGHT,
                                PROPERTY_POSTER_MAX_HEIGHT_DEFAULT),
                        null);

                // Create a thumbnail image
                File fTbPoster = ImageUtils.createThumbnail(fPoster,
                        AppPropertiesService.getPropertyInt(PROPERTY_POSTER_THUMB_WIDTH, 120),
                        AppPropertiesService.getPropertyInt(PROPERTY_POSTER_THUMB_HEIGHT, 200));

                // Save file name into entity
                product.setPosterName(fPoster.getName());
                fileGotten = true;

                filePosterArray = new File[] { fTbPoster, fPosterResize };
            } catch (IOException e) {
                throw new BusinessException(product, MESSAGE_ERROR_GET_AFFICHE);
            } finally {
                if (fisPoster != null) {
                    try {
                        fisPoster.close();
                    } catch (IOException e) {
                        AppLogService.error(e.getMessage(), e);
                    }
                }
            }
        }
    }

    if (!fileGotten) {
        // Error mandatory poster
        if (StringUtils.isEmpty(product.getPosterName())) {
            throw new BusinessException(product, MESSAGE_ERROR_MANDATORY_POSTER);
        }
    }

    return filePosterArray;
}

From source file:com.wabacus.system.fileupload.AbsFileUpload.java

protected String doUploadFileAction(FileItem item, Map<String, String> mFormFieldValues, String orginalFilename,
        String configAllowTypes, List<String> lstConfigAllowTypes, String configDisallowTypes,
        List<String> lstConfigDisallowTypes) {
    String strmaxsize = mFormFieldValues.get(AbsFileUploadInterceptor.MAXSIZE_KEY);
    if (strmaxsize != null && !strmaxsize.trim().equals("")) {
        long lmaxsize = Long.parseLong(strmaxsize.trim());
        if (lmaxsize > 0 && lmaxsize < item.getSize())
            return "";
    }//from   www.jav a2s. c  om
    if (!isInvalidUploadFileType(orginalFilename, configAllowTypes, lstConfigAllowTypes, configDisallowTypes,
            lstConfigDisallowTypes)) {
        return "??";
    }
    String savepathTmp = mFormFieldValues.get(AbsFileUploadInterceptor.SAVEPATH_KEY);
    String destfilenameTmp = mFormFieldValues.get(AbsFileUploadInterceptor.FILENAME_KEY);
    if (!Tools.isEmpty(savepathTmp) && !Tools.isEmpty(destfilenameTmp)) {
        try {
            savepathTmp = FilePathAssistant.getInstance().standardFilePath(savepathTmp + File.separator);
            FilePathAssistant.getInstance().checkAndCreateDirIfNotExist(savepathTmp);
            item.write(new File(savepathTmp + destfilenameTmp));
        } catch (Exception e) {
            log.error("" + orginalFilename + "" + savepathTmp + "", e);
            return "" + orginalFilename + "" + savepathTmp + "";
        }
    }
    return null;
}

From source file:it.eng.spagobi.analiticalmodel.document.utils.DetBIObjModHelper.java

/**
 * Recover bi obj template details./*from w w  w.  ja v a  2s. c om*/
 * 
 * @return the obj template
 * 
 * @throws Exception the exception
 */
public ObjTemplate recoverBIObjTemplateDetails() throws Exception {
    // GET THE USER PROFILE
    SessionContainer session = reqCont.getSessionContainer();
    SessionContainer permanentSession = session.getPermanentContainer();
    IEngUserProfile profile = (IEngUserProfile) permanentSession.getAttribute(IEngUserProfile.ENG_USER_PROFILE);
    //String userId=(String)profile.getUserUniqueIdentifier();
    String userId = (String) ((UserProfile) profile).getUserId();
    ObjTemplate templ = null;

    FileItem uploaded = (FileItem) request.getAttribute("UPLOADED_FILE");
    if (uploaded != null) {
        String fileName = GeneralUtilities.getRelativeFileNames(uploaded.getName());
        if (fileName != null && !fileName.trim().equals("")) {
            if (uploaded.getSize() == 0) {
                EMFValidationError error = new EMFValidationError(EMFErrorSeverity.ERROR, "uploadFile", "201");
                this.respCont.getErrorHandler().addError(error);
                return null;
            }
            int maxSize = GeneralUtilities.getTemplateMaxSize();
            if (uploaded.getSize() > maxSize) {
                EMFValidationError error = new EMFValidationError(EMFErrorSeverity.ERROR, "uploadFile", "202");
                this.respCont.getErrorHandler().addError(error);
                return null;
            }
            templ = new ObjTemplate();
            templ.setActive(new Boolean(true));
            templ.setCreationUser(userId);
            templ.setDimension(Long.toString(uploaded.getSize() / 1000) + " KByte");
            templ.setName(fileName);
            byte[] uplCont = uploaded.get();
            templ.setContent(uplCont);
        }
    }

    //      UploadedFile uploaded = (UploadedFile) request.getAttribute("UPLOADED_FILE");
    //      if (uploaded != null) {
    //         String fileName = uploaded.getFileName();
    //         if (fileName != null && !fileName.trim().equals("")) {
    //            templ = new ObjTemplate();
    //            templ.setActive(new Boolean(true));
    //            templ.setCreationUser(userId);
    //            templ.setDimension(Long.toString(uploaded.getSizeInBytes()/1000)+" KByte");
    //              templ.setName(fileName);
    //              byte[] uplCont = uploaded.getFileContent();
    //              templ.setContent(uplCont);
    //         }
    //      }
    return templ;
}

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

public static String uploadDocument(HttpServletRequest request, String fileid, String userId)
        throws ServiceException {
    String result = "";
    try {//ww w  .  j a v  a  2s  .c  o  m
        String destinationDirectory = StorageHandler.GetDocStorePath() + StorageHandler.GetFileSeparator()
                + "importcontacts" + StorageHandler.GetFileSeparator() + userId;
        org.apache.commons.fileupload.DiskFileUpload fu = new org.apache.commons.fileupload.DiskFileUpload();
        org.apache.commons.fileupload.FileItem fi = null;
        org.apache.commons.fileupload.FileItem docTmpFI = null;

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

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

                docTmpFI = fi;
                fileupload = true;
            }
        }

        if (fileupload) {

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

From source file:com.wabacusdemo.TestFileUploadInterceptor.java

public boolean beforeFileUpload(HttpServletRequest request, FileItem fileitemObj,
        Map<String, String> mFormAndConfigValues, PrintWriter out) {
    String testfieldvalue = mFormAndConfigValues.get("testfieldname");//???
    if (testfieldvalue == null)
        testfieldvalue = "";
    String inputboxid = mFormAndConfigValues.get(INPUTBOXID_KEY);
    if (inputboxid != null && !inputboxid.trim().equals("")) {//
        String filename = mFormAndConfigValues.get(FILENAME_KEY);//????
        String savedvalue = filename;
        if (!testfieldvalue.trim().equals(""))
            testfieldvalue = "(" + testfieldvalue + ")";
        savedvalue = testfieldvalue + savedvalue + "[" + fileitemObj.getSize() / 1024 + "kb]";//???
        mFormAndConfigValues.put(SAVEVALUE_KEY, savedvalue);//??
    } else {//
        if (testfieldvalue != null && !testfieldvalue.trim().equals("")) {
            out.println("?" + testfieldvalue + "<br>");
        }//from   w  w  w  . j a v a 2  s  .c o  m
        if (fileitemObj != null) {
            out.println("?" + fileitemObj.getSize() + "<br>");
        }
    }
    return true;//?
}

From source file:com.ikon.servlet.admin.CheckTextExtractionServlet.java

@SuppressWarnings("unchecked")
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    log.debug("doPost({}, {})", request, response);
    request.setCharacterEncoding("UTF-8");
    updateSessionManager(request);//from   w  w w . j  av  a2 s  .  c  o m
    InputStream is = null;

    try {
        if (ServletFileUpload.isMultipartContent(request)) {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items = upload.parseRequest(request);
            String docUuid = null;
            String repoPath = null;
            String text = null;
            String mimeType = null;
            String extractor = null;

            for (Iterator<FileItem> it = items.iterator(); it.hasNext();) {
                FileItem item = it.next();

                if (item.isFormField()) {
                    if (item.getFieldName().equals("docUuid")) {
                        docUuid = item.getString("UTF-8");
                    } else if (item.getFieldName().equals("repoPath")) {
                        repoPath = item.getString("UTF-8");
                    }
                } else {
                    is = item.getInputStream();
                    String name = FilenameUtils.getName(item.getName());
                    mimeType = MimeTypeConfig.mimeTypes.getContentType(name.toLowerCase());

                    if (!name.isEmpty() && item.getSize() > 0) {
                        docUuid = null;
                        repoPath = null;
                    } else if (docUuid.isEmpty() && repoPath.isEmpty()) {
                        mimeType = null;
                    }
                }
            }

            if (docUuid != null && !docUuid.isEmpty()) {
                repoPath = OKMRepository.getInstance().getNodePath(null, docUuid);
            }

            if (repoPath != null && !repoPath.isEmpty()) {
                String name = PathUtils.getName(repoPath);
                mimeType = MimeTypeConfig.mimeTypes.getContentType(name.toLowerCase());
                is = OKMDocument.getInstance().getContent(null, repoPath, false);
            }

            long begin = System.currentTimeMillis();

            if (is != null) {
                if (!MimeTypeConfig.MIME_UNDEFINED.equals(mimeType)) {
                    TextExtractor extClass = RegisteredExtractors.getTextExtractor(mimeType);

                    if (extClass != null) {
                        extractor = extClass.getClass().getCanonicalName();
                        text = RegisteredExtractors.getText(mimeType, null, is);
                    } else {
                        extractor = "Undefined text extractor";
                    }
                }
            }

            ServletContext sc = getServletContext();
            sc.setAttribute("docUuid", docUuid);
            sc.setAttribute("repoPath", repoPath);
            sc.setAttribute("text", text);
            sc.setAttribute("time", System.currentTimeMillis() - begin);
            sc.setAttribute("mimeType", mimeType);
            sc.setAttribute("extractor", extractor);
            sc.getRequestDispatcher("/admin/check_text_extraction.jsp").forward(request, response);
        }
    } catch (DatabaseException e) {
        sendErrorRedirect(request, response, e);
    } catch (FileUploadException e) {
        sendErrorRedirect(request, response, e);
    } catch (PathNotFoundException e) {
        sendErrorRedirect(request, response, e);
    } catch (AccessDeniedException e) {
        sendErrorRedirect(request, response, e);
    } catch (RepositoryException e) {
        sendErrorRedirect(request, response, e);
    } finally {
        IOUtils.closeQuietly(is);
    }
}

From source file:com.openkm.servlet.admin.CheckTextExtractionServlet.java

@SuppressWarnings("unchecked")
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    log.debug("doPost({}, {})", request, response);
    request.setCharacterEncoding("UTF-8");
    updateSessionManager(request);/*from   ww w.jav  a  2 s  . c  o m*/
    InputStream is = null;

    try {
        if (ServletFileUpload.isMultipartContent(request)) {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items = upload.parseRequest(request);
            String docUuid = null;
            String repoPath = null;
            String text = null;
            String error = null;
            String mimeType = null;
            String extractor = null;

            for (Iterator<FileItem> it = items.iterator(); it.hasNext();) {
                FileItem item = it.next();

                if (item.isFormField()) {
                    if (item.getFieldName().equals("docUuid")) {
                        docUuid = item.getString("UTF-8");
                    } else if (item.getFieldName().equals("repoPath")) {
                        repoPath = item.getString("UTF-8");
                    }
                } else {
                    is = item.getInputStream();
                    String name = FilenameUtils.getName(item.getName());
                    mimeType = MimeTypeConfig.mimeTypes.getContentType(name.toLowerCase());

                    if (!name.isEmpty() && item.getSize() > 0) {
                        docUuid = null;
                        repoPath = null;
                    } else if (docUuid.isEmpty() && repoPath.isEmpty()) {
                        mimeType = null;
                    }
                }
            }

            if (docUuid != null && !docUuid.isEmpty()) {
                repoPath = OKMRepository.getInstance().getNodePath(null, docUuid);
            }

            if (repoPath != null && !repoPath.isEmpty()) {
                String name = PathUtils.getName(repoPath);
                mimeType = MimeTypeConfig.mimeTypes.getContentType(name.toLowerCase());
                is = OKMDocument.getInstance().getContent(null, repoPath, false);
            }

            long begin = System.currentTimeMillis();

            if (is != null) {
                if (!MimeTypeConfig.MIME_UNDEFINED.equals(mimeType)) {
                    TextExtractor extClass = RegisteredExtractors.getTextExtractor(mimeType);

                    if (extClass != null) {
                        try {
                            extractor = extClass.getClass().getCanonicalName();
                            text = RegisteredExtractors.getText(mimeType, null, is);
                        } catch (Exception e) {
                            error = e.getMessage();
                        }
                    } else {
                        extractor = "Undefined text extractor";
                    }
                }
            }

            ServletContext sc = getServletContext();
            sc.setAttribute("docUuid", docUuid);
            sc.setAttribute("repoPath", repoPath);
            sc.setAttribute("text", text);
            sc.setAttribute("time", System.currentTimeMillis() - begin);
            sc.setAttribute("mimeType", mimeType);
            sc.setAttribute("error", error);
            sc.setAttribute("extractor", extractor);
            sc.getRequestDispatcher("/admin/check_text_extraction.jsp").forward(request, response);
        }
    } catch (DatabaseException e) {
        sendErrorRedirect(request, response, e);
    } catch (FileUploadException e) {
        sendErrorRedirect(request, response, e);
    } catch (PathNotFoundException e) {
        sendErrorRedirect(request, response, e);
    } catch (AccessDeniedException e) {
        sendErrorRedirect(request, response, e);
    } catch (RepositoryException e) {
        sendErrorRedirect(request, response, e);
    } finally {
        IOUtils.closeQuietly(is);
    }
}

From source file:fr.paris.lutece.portal.business.user.attribute.AttributeImage.java

/**
 * Get the data of the user fields//from w w  w.  j  a  va  2s  . c om
 * @param request HttpServletRequest
 * @param user user
 * @return user field data
 */
@Override
public List<AdminUserField> getUserFieldsData(HttpServletRequest request, AdminUser user) {
    String strUpdateAttribute = request
            .getParameter(PARAMETER_UPDATE_ATTRIBUTE + CONSTANT_UNDERSCORE + getIdAttribute());
    List<AdminUserField> listUserFields = new ArrayList<AdminUserField>();

    try {
        if (StringUtils.isNotBlank(strUpdateAttribute)) {
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            FileItem fileItem = multipartRequest
                    .getFile(PARAMETER_ATTRIBUTE + CONSTANT_UNDERSCORE + getIdAttribute());

            if ((fileItem != null) && (fileItem.getName() != null)
                    && !EMPTY_STRING.equals(fileItem.getName())) {
                File file = new File();
                PhysicalFile physicalFile = new PhysicalFile();
                physicalFile.setValue(fileItem.get());
                file.setTitle(FileUploadService.getFileNameOnly(fileItem));
                file.setSize((int) fileItem.getSize());
                file.setPhysicalFile(physicalFile);
                file.setMimeType(FileSystemUtil.getMIMEType(FileUploadService.getFileNameOnly(fileItem)));

                //verify that the file is an image
                ImageIO.read(new ByteArrayInputStream(file.getPhysicalFile().getValue()));

                AdminUserField userField = new AdminUserField();
                userField.setUser(user);
                userField.setAttribute(this);

                AttributeService.getInstance().setAttributeField(this);

                if ((getListAttributeFields() != null) && (getListAttributeFields().size() > 0)) {
                    userField.setAttributeField(getListAttributeFields().get(0));
                    userField.setFile(file);
                }

                listUserFields.add(userField);
            }
        } else {
            AdminUserFieldFilter auFieldFilter = new AdminUserFieldFilter();
            auFieldFilter.setIdAttribute(getIdAttribute());

            String strIdUser = request.getParameter(PARAMETER_ID_USER);

            if (StringUtils.isNotBlank(strIdUser)) {
                auFieldFilter.setIdUser(StringUtil.getIntValue(strIdUser, 0));
            }

            listUserFields = AdminUserFieldHome.findByFilter(auFieldFilter);

            for (AdminUserField userField : listUserFields) {
                if (userField.getFile() != null) {
                    File file = FileHome.findByPrimaryKey(userField.getFile().getIdFile());
                    userField.setFile(file);

                    int nIdPhysicalFile = file.getPhysicalFile().getIdPhysicalFile();
                    PhysicalFile physicalFile = PhysicalFileHome.findByPrimaryKey(nIdPhysicalFile);
                    userField.getFile().setPhysicalFile(physicalFile);
                }
            }
        }
    } catch (IOException e) {
        AppLogService.error(e);
    }

    return listUserFields;
}

From source file:fr.paris.lutece.plugins.stock.modules.billetterie.web.ShowJspBean.java

/**
 * Returns the form to modify a provider.
 *
 * @param request/*from  www . j a  v  a 2  s.  c o m*/
 *            The Http request
 * @param strProductClassName
 *            The class name of the provider entity to modify
 * @return the html code of the provider form
 */
@Transactional(readOnly = true)
public String getSaveProduct(HttpServletRequest request, String strProductClassName) {
    ShowDTO product = null;
    Map<String, Object> model = new HashMap<String, Object>();

    FunctionnalException fe = getErrorOnce(request);

    if (fe != null) {
        product = (ShowDTO) fe.getBean();
        model.put(BilletterieConstants.ERROR, getHtmlError(fe));
    } else {
        String strProductId = request.getParameter(PARAMETER_CATEGORY_ID);
        String strPartnerId = request.getParameter(PARAMETER_PRODUCT_PARTNER_ID);
        String strCategoryId = request.getParameter(PARAMETER_PRODUCT_CATEGORY_ID);

        if (strProductId != null) {
            setPageTitleProperty(PAGE_TITLE_MODIFY_PRODUCT);

            int nIdProduct = Integer.parseInt(strProductId);
            product = _serviceProduct.findById(nIdProduct);

            int idProvider = product.getIdProvider();

            if (request.getParameter(PARAMETER_REFRESH_CONTACT) != null) {
                // case of wanting to get the contact which can be link to
                // the product
                populate(product, request);
                String strIdProvider = request.getParameter(PARAMETER_PRODUCT_ID_PROVIDER);
                int nIdSelectedProvider = Integer.valueOf(strIdProvider);

                if (nIdSelectedProvider >= 0) {
                    idProvider = nIdSelectedProvider;
                }

            }

            model.put(MARK_CONTACT_LIST, getContactComboList(idProvider));

            _serviceProduct.correctProduct(product);
        } else {
            setPageTitleProperty(PAGE_TITLE_CREATE_PRODUCT);
            product = new ShowDTO();

            // If creation and filter "Salle" exist, pre-select the partner
            if (StringUtils.isNotBlank(strPartnerId)) {
                product.setIdProvider(Integer.parseInt(strPartnerId));
            } else {
                populate(product, request);
            }

            // If creation and filter "Categorie" exist, pre-select the
            // category
            if (StringUtils.isNotBlank(strCategoryId)) {
                product.setIdCategory(Integer.parseInt(strCategoryId));
            }

            if ((request.getParameter(PARAMETER_PRODUCT_ID_PROVIDER) != null)
                    && !request.getParameter(PARAMETER_PRODUCT_ID_PROVIDER).equals("-1")) {
                Integer idProvider = Integer.valueOf(request.getParameter(PARAMETER_PRODUCT_ID_PROVIDER));

                model.put(MARK_CONTACT_LIST, getContactComboList(idProvider));
            }
        }
    }

    if (request instanceof MultipartHttpServletRequest) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        FileItem fileItem = multipartRequest.getFile(PARAMETER_POSTER);

        if ((fileItem != null) && (fileItem.getSize() > 0)) {
            // writePoster( request, product );
            product.setPosterName(fileItem.getName());
            populate(product, request);
        }
    }

    // Combo
    List<String> orderList = new ArrayList<String>();
    orderList.add(BilletterieConstants.NAME);

    ProviderFilter providerFilter = new ProviderFilter();
    providerFilter.setOrderAsc(true);
    providerFilter.setOrders(orderList);

    ReferenceList providerComboList = ListUtils.toReferenceList(
            _serviceProvider.findByFilter(providerFilter, null), BilletterieConstants.ID,
            BilletterieConstants.NAME, StockConstants.EMPTY_STRING);
    CategoryFilter categoryFilter = new CategoryFilter();
    categoryFilter.setOrderAsc(true);
    categoryFilter.setOrders(orderList);

    ReferenceList categoryComboList = ListUtils.toReferenceList(
            _serviceCategory.findByFilter(categoryFilter, null), BilletterieConstants.ID,
            BilletterieConstants.NAME, StockConstants.EMPTY_STRING);
    model.put(MARK_LIST_PROVIDERS, providerComboList);
    model.put(MARK_LIST_CATEGORIES, categoryComboList);
    model.put(MARK_PUBLIC_LIST, ListUtils.getPropertyList(PROPERTY_STOCK_BILLETTERIE_SHOW_PUBLIC));

    model.put(StockConstants.MARK_JSP_BACK, request.getParameter(StockConstants.MARK_JSP_BACK));
    model.put(MARK_PRODUCT, product);
    model.put(MARK_URL_POSTER, AppPropertiesService.getProperty(PROPERTY_POSTER_PATH));

    // Richtext editor parameters
    model.put(MARK_WEBAPP_URL, AppPathService.getBaseUrl(request));
    model.put(MARK_LOCALE, getLocale());

    if ((product.getId() != null) && (product.getId() != 0)) {
        model.put(MARK_TITLE, I18nService.getLocalizedString(PAGE_TITLE_MODIFY_PRODUCT, Locale.getDefault()));
    } else {
        model.put(MARK_TITLE, I18nService.getLocalizedString(PAGE_TITLE_CREATE_PRODUCT, Locale.getDefault()));
    }

    ExtendableResourcePluginActionManager.fillModel(request, getUser(), model, String.valueOf(product.getId()),
            ShowDTO.PROPERTY_RESOURCE_TYPE);

    HtmlTemplate template = AppTemplateService.getTemplate(TEMPLATE_SAVE_PRODUCT, getLocale(), model);

    return getAdminPage(template.getHtml());
}