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

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

Introduction

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

Prototype

boolean isFormField();

Source Link

Document

Determines whether or not a FileItem instance represents a simple form field.

Usage

From source file:com.aspectran.web.activity.request.multipart.MultipartFormDataParser.java

/**
 * Parse form fields and file item./* ww  w  .j  av  a  2 s  . c o m*/
 *
 * @param fileItemListMap the file item list map
 * @param requestAdapter the request adapter
 * @throws UnsupportedEncodingException the unsupported encoding exception
 */
private void parseMultipart(Map<String, List<FileItem>> fileItemListMap, RequestAdapter requestAdapter)
        throws UnsupportedEncodingException {
    String characterEncoding = requestAdapter.getCharacterEncoding();
    Map<String, List<String>> parameterListMap = new HashMap<String, List<String>>();
    Map<String, List<FileParameter>> fileParameterListMap = new HashMap<String, List<FileParameter>>();

    for (Map.Entry<String, List<FileItem>> entry : fileItemListMap.entrySet()) {
        String fieldName = entry.getKey();
        List<FileItem> fileItemList = entry.getValue();

        if (fileItemList != null && !fileItemList.isEmpty()) {
            for (FileItem fileItem : fileItemList) {
                if (fileItem.isFormField()) {
                    String value = getString(fileItem, characterEncoding);
                    putParameter(fieldName, value, parameterListMap);
                } else {
                    String fileName = fileItem.getName();

                    // Skip file uploads that don't have a file name - meaning that
                    // no file was selected.
                    if (fileName == null || StringUtils.isEmpty(fileName))
                        continue;

                    boolean valid = FilenameUtils.isValidFileExtension(fileName, allowedFileExtensions,
                            deniedFileExtensions);
                    if (!valid)
                        continue;

                    FileParameter fileParameter = new MultipartFileParameter(fileItem);
                    putFileParameter(fieldName, fileParameter, fileParameterListMap);

                    requestAdapter.setFileParameter(fieldName, fileParameter);
                }
            }
        }
    }

    if (!parameterListMap.isEmpty()) {
        for (Map.Entry<String, List<String>> entry : parameterListMap.entrySet()) {
            String name = entry.getKey();
            List<String> list = entry.getValue();
            String[] values = list.toArray(new String[list.size()]);
            requestAdapter.setParameter(name, values);
        }
    }

    if (!fileParameterListMap.isEmpty()) {
        for (Map.Entry<String, List<FileParameter>> entry : fileParameterListMap.entrySet()) {
            String name = entry.getKey();
            List<FileParameter> list = entry.getValue();
            FileParameter[] values = list.toArray(new FileParameter[list.size()]);
            requestAdapter.setFileParameter(name, values);
        }
    }
}

From source file:crds.pub.FCKeditor.uploader.SimpleUploaderServlet.java

/**
 * Manage the Upload requests.<br>
 *
 * The servlet accepts commands sent in the following format:<br>
 * simpleUploader?Type=ResourceType<br><br>
 * It store the file (renaming it in case a file with the same name exists) and then return an HTML file
 * with a javascript command in it./*from   w  w w  .  j  av a 2 s  . co m*/
 *
 */
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    HttpSession session = request.getSession();
    FormUserOperation formUser = Constant.getFormUserOperation(request);
    String fck_task_id = (String) request.getSession().getAttribute("fck_task_id");
    if (fck_task_id == null) {
        fck_task_id = "temp_task_id";
    }

    response.setContentType("text/html; charset=UTF-8");
    response.setHeader("Cache-Control", "no-cache");
    PrintWriter out = response.getWriter();

    String typeStr = request.getParameter("Type");

    String currentPath = baseDir + formUser.getCompany_code() + "/" + fck_task_id + "/" + typeStr;
    String currentDirPath = getServletContext().getRealPath(currentPath);

    File currentDir = new File(currentDirPath);
    if (!currentDir.exists()) {
        currentDir.mkdirs();
    }

    String retVal = "0";
    String newName = "";
    String fileUrl = "";
    String errorMessage = "";

    if (enabled) {
        org.apache.commons.fileupload.DiskFileUpload upload = new org.apache.commons.fileupload.DiskFileUpload();
        try {
            List items = upload.parseRequest(request);

            Map fields = new HashMap();

            Iterator iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                if (item.isFormField())
                    fields.put(item.getFieldName(), item.getString());
                else
                    fields.put(item.getFieldName(), item);
            }
            FileItem uplFile = (FileItem) fields.get("NewFile");
            String fileNameLong = uplFile.getName();
            fileNameLong = fileNameLong.replace('\\', '/');

            String[] pathParts = fileNameLong.split("/");
            String fileName = pathParts[pathParts.length - 1];

            String nameWithoutExt = getNameWithoutExtension(fileName);
            String ext = getExtension(fileName);
            File pathToSave = new File(currentDirPath, fileName);

            //???IP
            String server_ip = (String) session.getAttribute("server_ip");
            if (server_ip == null) {
                server_ip = CommonMethod.getServerIP(request) + ":" + request.getServerPort();//???IP?
            }
            String url = "http://" + server_ip + currentPath.substring(2, currentPath.length());

            fileUrl = url + "/" + fileName;
            if (extIsAllowed(typeStr, ext)) {
                int counter = 1;
                while (pathToSave.exists()) {
                    newName = nameWithoutExt + "(" + counter + ")" + "." + ext;
                    fileUrl = url + "/" + newName;
                    retVal = "201";
                    pathToSave = new File(currentDirPath, newName);
                    counter++;
                }
                uplFile.write(pathToSave);
            } else {
                retVal = "202";
                errorMessage = "";
            }
        } catch (Exception ex) {
            if (debug)
                ex.printStackTrace();
            retVal = "203";
        }
    } else {
        retVal = "1";
        errorMessage = "This file uploader is disabled. Please check the WEB-INF/web.xml file";
    }

    out.println("<script type=\"text/javascript\">");
    out.println("window.parent.OnUploadCompleted(" + retVal + ",'" + fileUrl + "','" + newName + "','"
            + errorMessage + "');");
    out.println("</script>");
    out.flush();
    out.close();

}

From source file:ch.zhaw.init.walj.projectmanagement.admin.properties.AdminProperties.java

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

    boolean isMultipart;
    String filePath;/*w  w  w .  j a v a 2 s .  c  om*/
    int maxFileSize = 9000 * 1024;
    int maxMemSize = 4 * 1024;
    File file;

    isMultipart = ServletFileUpload.isMultipartContent(request);
    response.setContentType("text/html");

    boolean small = request.getParameter("size").equals("small");

    String message;

    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(this.getServletContext().getRealPath("/") + "img/"));

    // 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<FileItem> fileItems = upload.parseRequest(request);

        // Process the uploaded file items

        for (FileItem fileItem : fileItems) {

            if (!fileItem.isFormField()) {
                // Get the uploaded file parameters
                String contentType = fileItem.getContentType();
                if (contentType.equals("image/png")) {
                    String fileName;
                    if (small) {
                        fileName = "logo_small.png";
                    } else {
                        fileName = "logo.png";
                    }
                    filePath = this.getServletContext().getRealPath("/") + "img/" + fileName;
                    // Write the file
                    file = new File(filePath);
                    fileItem.write(file);
                } else {
                    throw new Exception("type");
                }
            }
        }
        message = "<div class=\"row\">" + "<div class=\"small-12 columns\">" + "<div class=\"row\">"
                + "<div class=\"callout success\">" + "<h5>Logo uploaded successfully</h5>" + "</div>"
                + "</div>" + "</div>" + "</div>";
        request.setAttribute("msg", message);
    } catch (Exception ex) {

        if (ex.getMessage().equals("type")) {

            message = "<div class=\"row\">" + "<div class=\"small-12 columns\">" + "<div class=\"row\">"
                    + "<div class=\"callout alert\">" + "<h5>Wrong Type</h5>"
                    + "<p>Please upload a PNG image</p>" + "</div>" + "</div>" + "</div>" + "</div>";
        } else {
            message = "<div class=\"row\">" + "<div class=\"small-12 columns\">" + "<div class=\"row\">"
                    + "<div class=\"callout alert\">" + "<h5>Upload failed</h5>" + "</div>" + "</div>"
                    + "</div>" + "</div>";
        }
        request.setAttribute("msg", message);
    }
    doGet(request, response);
}

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

@SuppressWarnings("unchecked")
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    log.debug("doPost({}, {})", request, response);
    request.setCharacterEncoding("UTF-8");
    String action = "";
    String userId = request.getRemoteUser();
    updateSessionManager(request);/*from  w ww  .j a  v  a2s . c  o m*/

    try {
        if (ServletFileUpload.isMultipartContent(request)) {
            InputStream is = null;
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items = upload.parseRequest(request);
            Report rp = new Report();

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

                if (item.isFormField()) {
                    if (item.getFieldName().equals("action")) {
                        action = item.getString("UTF-8");
                    } else if (item.getFieldName().equals("rp_id")) {
                        rp.setId(Integer.parseInt(item.getString("UTF-8")));
                    } else if (item.getFieldName().equals("rp_name")) {
                        rp.setName(item.getString("UTF-8"));
                    } else if (item.getFieldName().equals("rp_active")) {
                        rp.setActive(true);
                    }
                } else {
                    is = item.getInputStream();
                    rp.setFileName(FilenameUtils.getName(item.getName()));
                    rp.setFileMime(MimeTypeConfig.mimeTypes.getContentType(item.getName()));
                    rp.setFileContent(SecureStore.b64Encode(IOUtils.toByteArray(is)));
                    is.close();
                }
            }

            if (action.equals("create")) {
                long id = ReportDAO.create(rp);

                // Activity log
                UserActivity.log(userId, "ADMIN_REPORT_CREATE", Long.toString(id), null, rp.toString());
                list(userId, request, response);
            } else if (action.equals("edit")) {
                Report tmp = ReportDAO.findByPk(rp.getId());
                tmp.setActive(rp.isActive());
                tmp.setFileContent(rp.getFileContent());
                tmp.setFileMime(rp.getFileMime());
                tmp.setFileName(rp.getFileName());
                tmp.setName(rp.getName());
                ReportDAO.update(tmp);

                // Activity log
                UserActivity.log(userId, "ADMIN_REPORT_EDIT", Long.toString(rp.getId()), null, rp.toString());
                list(userId, request, response);
            } else if (action.equals("delete")) {
                ReportDAO.delete(rp.getId());

                // Activity log
                UserActivity.log(userId, "ADMIN_REPORT_DELETE", Long.toString(rp.getId()), null, null);
                list(userId, request, response);
            }
        }
    } catch (DatabaseException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    } catch (FileUploadException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    }
}

From source file:isl.FIMS.servlet.imports.ImportVocabulary.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    this.initVars(request);
    String username = getUsername(request);

    Config conf = new Config("AdminVoc");

    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    StringBuilder xml = new StringBuilder(
            this.xmlStart(this.topmenu, username, this.pageTitle, this.lang, "", request));
    String file = request.getParameter("file");

    if (ServletFileUpload.isMultipartContent(request)) {
        // configures some settings
        String filePath = this.export_import_Folder;
        java.util.Date date = new java.util.Date();
        Timestamp t = new Timestamp(date.getTime());
        String currentDir = filePath + t.toString().replaceAll(":", "");
        File saveDir = new File(currentDir);
        if (!saveDir.exists()) {
            saveDir.mkdir();/*from  w  w w  . ja  v  a2 s.  c om*/
        }
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD);
        factory.setRepository(saveDir);

        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(REQUEST_SIZE);
        // constructs the directory path to store upload file
        String uploadPath = currentDir;

        try {
            // parses the request's content to extract file data
            List formItems = upload.parseRequest(request);
            Iterator iter = formItems.iterator();
            // iterates over form's fields
            File storeFile = null;
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                // processes only fields that are not form fields
                if (!item.isFormField()) {
                    String fileName = new File(item.getName()).getName();
                    filePath = uploadPath + File.separator + fileName;
                    storeFile = new File(filePath);
                    // saves the file on disk
                    item.write(storeFile);
                }
            }
            ArrayList<String> content = Utils.readFile(storeFile);
            DMSConfig vocConf = new DMSConfig(this.DBURI, this.systemDbCollection + "Vocabulary/", this.DBuser,
                    this.DBpassword);
            Vocabulary voc = new Vocabulary(file, this.lang, vocConf);
            String[] terms = voc.termValues();

            for (int i = 0; i < content.size(); i++) {
                String addTerm = content.get(i);
                if (!Arrays.asList(terms).contains(addTerm)) {
                    voc.addTerm(addTerm);
                }

            }
            Utils.deleteDir(currentDir);
            response.sendRedirect("AdminVoc?action=list&file=" + file + "&menuId=AdminVoc");
        } catch (Exception ex) {
        }

    }

    xml.append("<FileName>").append(file).append("</FileName>\n");
    xml.append("<EntityType>").append("AdminVoc").append("</EntityType>\n");

    xml.append(this.xmlEnd());
    String xsl = conf.IMPORT_Vocabulary;
    try {
        XMLTransform xmlTrans = new XMLTransform(xml.toString());
        xmlTrans.transform(out, xsl);
    } catch (DMSException e) {
        e.printStackTrace();
    }
    out.close();
}

From source file:edu.pitt.servlets.processAddMedia.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/* w ww.j ava2s  . c  o m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    HttpSession session = request.getSession();
    String userID = (String) session.getAttribute("userID");

    String error = "select correct format ";
    session.setAttribute("error", error);

    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {
        // Process only if its multipart content
        // Create a factory for disk-based file items
        File file;
        // We might need to play with the file sizes
        int maxFileSize = 50000 * 1024;
        int maxMemSize = 50000 * 1024;
        ServletContext context = this.getServletContext();
        // Note that this file path refers to a virtual path
        // relative to this servlet.  The uploads directory
        // is part of this project.  The physical path varies 
        // from the virtual path

        String filePath = context.getRealPath("/uploads") + "/";
        out.println("Physical folder is located at: " + filePath + "<br />");

        // Verify the content type
        String contentType = request.getContentType();
        // This is very important - make sure that the web form that 
        // uploads the file is actually set to enctype="multipart/form-data"
        // An example of upload form for this project is in index.html
        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(filePath));

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

                        out.println("field name" + fieldName);
                        String fileName = fi.getName();

                        out.println("file name" + fileName); // file name is present

                        boolean isInMemory = fi.isInMemory();
                        long sizeInBytes = fi.getSize();
                        //  out.println("file size"+ sizeInBytes);
                        // Write the file
                        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);
                        //  out.println("Uploaded Filename: " + filePath  + fileName + "<br />");
                        String savepath = filePath + fileName;

                        // to check correct format is entered or not 
                        int dotindex = fileName.indexOf(".");
                        if (!(fileName.substring(dotindex).matches(".ogv|.webm|.mp4|.png|.jpeg|.jpg|.gif"))) {
                            response.sendRedirect("./pages/addMedia.jsp");

                        }

                        // receives projectID from listProjects.jsp from edit href link , adding in existing project 
                        // corresponding constructor is used          
                        if (session.getAttribute("projectID") != null) {
                            Integer projectID = (Integer) session.getAttribute("projectID");

                            media = new Media(projectID, fileName);
                        }
                        // first time when user enters media for project , this constructor is used          
                        else {
                            media = new Media(userID, fileName);
                        }

                        System.out.println("Into the media constructor");
                        // redirected to listProject
                        response.sendRedirect("./pages/listProject.jsp");

                        // media constructor

                        // response.redirect(listprojects.jsp);

                        processRequest(request, response);
                    }

                }

            }

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

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

/**
 * Funcin que se ejecuta cuando el servlet recibe los datos
 *///from   w ww.  j a va2 s  . c  o m
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:controllers.ServerController.java

public void uploadFile(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

    String UPLOAD_DIRECTORY = "/opt/ppd";
    int MEMORY_THRESHOLD = 1024 * 1024 * 3; // 3MB
    int MAX_FILE_SIZE = 1024 * 1024 * 40; // 40MB
    int MAX_REQUEST_SIZE = 1024 * 1024 * 50; // 50MB

    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(MEMORY_THRESHOLD);
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setFileSizeMax(MAX_FILE_SIZE);
    upload.setSizeMax(MAX_REQUEST_SIZE);

    File uploadDir = new File(UPLOAD_DIRECTORY);
    if (!uploadDir.exists())
        uploadDir.mkdir();//from w w w  . ja v a2  s. co  m

    try {
        // parses the request's content to extract file data
        @SuppressWarnings("unchecked")
        List<FileItem> formItems = upload.parseRequest(request);
        if (formItems != null && formItems.size() > 0) {
            // iterates over form's fields
            for (FileItem item : formItems) {
                // processes only fields that are not form fields
                if (!item.isFormField()) {
                    String fileName = new File(item.getName()).getName();
                    String filePath = UPLOAD_DIRECTORY + File.separator + fileName;
                    File storeFile = new File(filePath);
                    item.write(storeFile);
                    PrintWriter out = response.getWriter();
                    Runtime runtime = Runtime.getRuntime();
                    Process process = runtime.exec("/opt/script.sh " + fileName);
                    out.write("uplad success");
                    out.close();
                }
            }
        }
    } catch (Exception ex) {
        PrintWriter out = response.getWriter();
        out.write("There was an error: " + ex.getMessage().toString());
        out.close();
    }

}

From source file:edu.emory.cci.aiw.cvrg.eureka.servlet.JobSubmitServlet.java

private Long submitJob(HttpServletRequest request, Principal principal)
        throws FileUploadException, IOException, ClientException, ParseException {

    DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();

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

    ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
    /*
     * Parse the request
     */
    List items = uploadHandler.parseRequest(request);
    Properties fields = new Properties();
    for (Iterator itr = items.iterator(); itr.hasNext();) {
        FileItem item = (FileItem) itr.next();
        /*
         * Handle Form Fields.
         */
        if (item.isFormField()) {
            fields.setProperty(item.getFieldName(), item.getString());
        }
    }

    JobSpec jobSpec = MAPPER.readValue(fields.getProperty("jobSpec"), JobSpec.class);

    for (Iterator itr = items.iterator(); itr.hasNext();) {
        FileItem item = (FileItem) itr.next();
        if (!item.isFormField()) {
            //Handle Uploaded files.
            log("Spreadsheet upload for user " + principal.getName() + ": Field Name = " + item.getFieldName()
                    + ", File Name = " + item.getName() + ", Content type = " + item.getContentType()
                    + ", File Size = " + item.getSize());
            if (item.getSize() > 0) {
                InputStream is = item.getInputStream();
                try {
                    this.servicesClient.upload(FilenameUtils.getName(item.getName()),
                            jobSpec.getSourceConfigId(), item.getFieldName(), is);
                    log("File '" + item.getName() + "' uploaded successfully");
                } finally {
                    if (is != null) {
                        try {
                            is.close();
                        } catch (IOException ignore) {
                        }
                    }
                }
            } else {
                log("File '" + item.getName() + "' ignored because it was zero length");
            }
        }
    }

    URI uri = this.servicesClient.submitJob(jobSpec);
    String uriStr = uri.toString();
    Long jobId = Long.valueOf(uriStr.substring(uriStr.lastIndexOf("/") + 1));
    log("Job " + jobId + " submitted for user " + principal.getName());
    return jobId;
}