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

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

Introduction

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

Prototype

InputStream getInputStream() throws IOException;

Source Link

Document

Returns an java.io.InputStream InputStream that can be used to retrieve the contents of the file.

Usage

From source file:com.sun.socialsite.web.rest.servlets.UploadServlet.java

/**
 * Note: using SuppressWarnings annotation because the Commons FileUpload API is
 * not genericized.//from  w  w  w.j a  va2  s . c om
 */
@Override
@SuppressWarnings(value = "unchecked")
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    try {

        // ensure calling app/gadget has perm to use SocialSite API
        SecurityToken token = new AuthInfo(req).getSecurityToken();
        Factory.getSocialSite().getPermissionManager().checkPermission(requiredPerm, token);

        GroupManager gmgr = Factory.getSocialSite().getGroupManager();
        ProfileManager pmgr = Factory.getSocialSite().getProfileManager();
        int errorCode = -1;
        Group group = null;
        Profile profile = null;

        // parse URL to get route and subjectId
        String route = null;
        String subjectId = "";
        if (req.getPathInfo() != null) {
            String[] pathInfo = req.getPathInfo().split("/");
            route = pathInfo[1];
            subjectId = pathInfo[2];
        }

        // first, figure out destination profile or group and check the
        // caller's permission to upload an image for that profile or group

        if ("profile".equals(route)) {
            if (token.getViewerId().equals(subjectId)) {
                profile = pmgr.getProfileByUserId(subjectId);
            } else {
                errorCode = HttpServletResponse.SC_UNAUTHORIZED;
            }

        } else if ("group".equals(route)) {
            group = gmgr.getGroupByHandle(subjectId);
            if (group != null) {
                // ensure called is group ADMIN or founder
                Profile viewer = pmgr.getProfileByUserId(token.getViewerId());
                GroupRelationship grel = gmgr.getMembership(group, viewer);
                if (grel == null || (grel.getRelcode() != GroupRelationship.Relationship.ADMIN
                        && grel.getRelcode() != GroupRelationship.Relationship.FOUNDER)) {
                } else {
                    errorCode = HttpServletResponse.SC_UNAUTHORIZED;
                }
            } else {
                // group not found
                errorCode = HttpServletResponse.SC_NOT_FOUND;
            }
        }

        // next, parse out the image and save it in profile or group

        if (errorCode != -1 && group == null && profile == null) {
            errorCode = HttpServletResponse.SC_NOT_FOUND;

        } else if (errorCode == -1) {

            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            FileItem fileItem = null;
            List<FileItem> items = (List<FileItem>) upload.parseRequest(req);
            if (items.size() > 0) {
                fileItem = items.get(0);
            }

            if ((fileItem != null) && (types.contains(fileItem.getContentType()))) {

                // read incomining image via Commons Upload
                InputStream is = fileItem.getInputStream();
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                Utilities.copyInputToOutput(is, baos);
                byte[] byteArray = baos.toByteArray();

                // save it in the profile or group indicated
                if (profile != null) {
                    profile.setImageType(fileItem.getContentType());
                    profile.setImage(byteArray);
                    pmgr.saveProfile(profile);
                    Factory.getSocialSite().flush();

                } else if (group != null) {
                    group.setImageType(fileItem.getContentType());
                    group.setImage(byteArray);
                    gmgr.saveGroup(group);
                    Factory.getSocialSite().flush();

                } else {
                    // group or profile not indicated properly
                    errorCode = HttpServletResponse.SC_NOT_FOUND;
                }
            }

        }

        if (errorCode == -1) {
            resp.sendError(HttpServletResponse.SC_OK);
            return;
        } else {
            resp.sendError(errorCode);
        }

    } catch (SecurityException sx) {
        log.error("Permission denied", sx);
        resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);

    } catch (FileUploadException fx) {
        log.error("ERROR uploading profile image", fx);
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);

    } catch (SocialSiteException ex) {
        log.error("ERROR saving profile image", ex);
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }

}

From source file:com.portfolio.data.attachment.ConvertCSV.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) {
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (!isMultipart) {
        try {/*  w  w  w  .ja va 2  s .com*/
            request.getInputStream().close();
            response.setStatus(417);
            response.getWriter().close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return;
    }

    initialize(request);
    response.setContentType("application/json");

    JSONObject data = new JSONObject();
    try {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List<FileItem> items = upload.parseRequest(request);
        Iterator<FileItem> iter = items.iterator();

        List<String[]> meta = new ArrayList<String[]>();
        List<List<String[]>> linesData = new ArrayList<List<String[]>>();

        while (iter.hasNext()) {
            FileItem item = iter.next();
            if (item.isFormField()) {
                // Process regular form field (input type="text|radio|checkbox|etc", select, etc).
            } else {
                // Process form file field (input type="file").
                String fieldname = item.getFieldName();
                if ("uploadfile".equals(fieldname)) // name="uploadfile"
                {
                    InputStreamReader isr = new InputStreamReader(item.getInputStream());
                    CSVReader reader = new CSVReader(isr, ';');
                    String[] headerLine;
                    String[] dataLine;

                    headerLine = reader.readNext();
                    if (headerLine == null)
                        break;

                    dataLine = reader.readNext();
                    if (dataLine == null)
                        break;

                    for (int i = 0; i < headerLine.length; ++i) {
                        data.put(headerLine[i], dataLine[i]);
                    }

                    headerLine = reader.readNext();
                    if (headerLine == null)
                        break;

                    JSONArray lines = new JSONArray();
                    while ((dataLine = reader.readNext()) != null) {
                        JSONObject lineInfo = new JSONObject();
                        for (int i = 0; i < headerLine.length; ++i) {
                            lineInfo.put(headerLine[i], dataLine[i]);
                        }
                        lines.put(lineInfo);
                    }

                    data.put("lines", lines);

                    isr.close();
                }
            }
        }
    } catch (Exception e) {

    }

    PrintWriter out = null;
    try {
        out = response.getWriter();
        out.print(data);
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (out != null) {
            out.flush();
            out.close();
        }
    }

}

From source file:net.sf.ginp.GinpServlet.java

/**
*  Extract Command Parameter NAmes and Values from the HTTP Request.
*
*@param  req  HTTP Request.// ww  w.  jav  a 2  s.c  o m
*@return      A vector of Command Parameters.
*/
final Vector extractParameters(final HttpServletRequest req) {
    Vector params = new Vector();
    Enumeration names = req.getParameterNames();

    while (names.hasMoreElements()) {
        String name = (String) names.nextElement();
        params.add(new CommandParameter(name, req.getParameter(name)));
        log.debug("new CommandParameter(" + name + ", " + req.getParameter(name) + ")");
    }

    ServletRequestContext reqContext = new ServletRequestContext(req);

    if (FileUpload.isMultipartContent(reqContext)) {
        try {
            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload();

            // Set upload parameters
            //upload.setSizeThreshold(yourMaxMemorySize);
            //upload.setSizeMax(yourMaxRequestSize);
            //upload.setRepositoryPath(yourTempDirectory);
            // Parse the request
            List items = upload.parseRequest(req);
            Iterator iter = items.iterator();

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

                if (item.isFormField()) {
                    params.add(new CommandParameter(item.getFieldName(), item.getString()));
                } else {
                    CommandParameter fileParam = new CommandParameter(item.getFieldName(), item.getName());

                    fileParam.setObject(item.getInputStream());

                    params.add(fileParam);
                }
            }
        } catch (Exception ex) {
            log.error("extract parameters error getting input stream" + " from file upload", ex);
        }
    }

    return params;
}

From source file:com.duroty.application.mail.actions.SaveDraftAction.java

protected ActionForward doExecute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    ActionMessages errors = new ActionMessages();

    try {//from ww w .ja v  a2 s  .  c  o m
        boolean isMultipart = FileUpload.isMultipartContent(request);

        if (isMultipart) {
            Map fields = new HashMap();
            Vector attachments = new Vector();

            //Parse the request
            List items = diskFileUpload.parseRequest(request);

            //Process the uploaded items
            Iterator iter = items.iterator();

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

                if (item.isFormField()) {
                    fields.put(item.getFieldName(), item.getString());
                } else {
                    if (!StringUtils.isBlank(item.getName())) {
                        ByteArrayOutputStream baos = null;

                        try {
                            baos = new ByteArrayOutputStream();

                            IOUtils.copy(item.getInputStream(), baos);

                            MailPartObj part = new MailPartObj();
                            part.setAttachent(baos.toByteArray());
                            part.setContentType(item.getContentType());
                            part.setName(item.getName());
                            part.setSize(item.getSize());

                            attachments.addElement(part);
                        } catch (Exception ex) {
                        } finally {
                            IOUtils.closeQuietly(baos);
                        }
                    }
                }
            }

            String body = "";

            if (fields.get("taBody") != null) {
                body = (String) fields.get("taBody");
            } else if (fields.get("taReplyBody") != null) {
                body = (String) fields.get("taReplyBody");
            }

            Preferences preferencesInstance = getPreferencesInstance(request);

            Send sendInstance = getSendInstance(request);

            String mid = (String) fields.get("mid");

            sendInstance.saveDraft(mid, Integer.parseInt((String) fields.get("identity")),
                    (String) fields.get("to"), (String) fields.get("cc"), (String) fields.get("bcc"),
                    (String) fields.get("subject"), body, attachments,
                    preferencesInstance.getPreferences().isHtmlMessage(),
                    Charset.defaultCharset().displayName(), (String) fields.get("priority"));
        } else {
            errors.add("general",
                    new ActionMessage(ExceptionCode.ERROR_MESSAGES_PREFIX + "mail.send", "The form is null"));
            request.setAttribute("exception", "The form is null");
            request.setAttribute("newLocation", null);
            doTrace(request, DLog.ERROR, getClass(), "The form is null");
        }
    } catch (Exception ex) {
        String errorMessage = ExceptionUtilities.parseMessage(ex);

        if (errorMessage == null) {
            errorMessage = "NullPointerException";
        }

        errors.add("general", new ActionMessage(ExceptionCode.ERROR_MESSAGES_PREFIX + "general", errorMessage));
        request.setAttribute("exception", errorMessage);
        doTrace(request, DLog.ERROR, getClass(), errorMessage);
    } finally {
    }

    if (errors.isEmpty()) {
        doTrace(request, DLog.INFO, getClass(), "OK");

        return mapping.findForward(Constants.ACTION_SUCCESS_FORWARD);
    } else {
        saveErrors(request, errors);

        return mapping.findForward(Constants.ACTION_FAIL_FORWARD);
    }
}

From source file:net.morphbank.mbsvc3.webservices.RestfulService.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    MorphbankConfig.SYSTEM_LOGGER.info("starting post");
    response.setContentType("text/xml");
    System.err.println("<!-- persistence: " + MorphbankConfig.getPersistenceUnit() + " -->");
    MorphbankConfig.SYSTEM_LOGGER.info("<!-- filepath: " + filepath + " -->");
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    // response.setContentType("text/html");

    try {/*from   w w w  . j  av a  2  s.c om*/
        // Process the uploaded items
        List<?> /* FileItem */ items = upload.parseRequest(request);
        Iterator<?> iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();

            if (item.isFormField()) {
                MorphbankConfig.SYSTEM_LOGGER.info("Form field " + item.getFieldName());
                // processFormField(item);
            } else {
                // processUploadedFile(item);
                String paramName = item.getFieldName();
                String fileName = item.getName();
                InputStream stream = item.getInputStream();
                // Reader reader = new InputStreamReader(stream);
                if ("uploadFileXml".equals(paramName)) {
                    MorphbankConfig.SYSTEM_LOGGER.info("Processing file " + fileName);
                    processRequest(stream, out, fileName);
                    MorphbankConfig.SYSTEM_LOGGER.info("Processing complete");
                } else {
                    // Process the input stream
                    MorphbankConfig.SYSTEM_LOGGER
                            .info("Upload field name " + item.getFieldName() + " ignored!");
                }
            }
        }
    } catch (FileUploadException e) {
        e.printStackTrace();
    }
}

From source file:net.morphbank.mbsvc3.webservices.RestService.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    if (!isIPAllowed(request.getRemoteAddr())) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN,
                "This IP is not allowed. Current IP used:" + request.getRemoteAddr());
        return;/*  w w  w. java2  s .com*/
    }
    PrintWriter out = response.getWriter();
    MorphbankConfig.SYSTEM_LOGGER.info("starting post from ip:" + request.getRemoteAddr());
    MorphbankConfig.ensureWorkingConnection();
    response.setContentType("text/xml");
    MorphbankConfig.SYSTEM_LOGGER.info("<!-- persistence: " + MorphbankConfig.getPersistenceUnit() + " -->");
    MorphbankConfig.SYSTEM_LOGGER.info("<!-- filepath: " + folderPath + " -->");
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    //      response.setContentType("text/html");

    String parameter = request.getParameter("uploadxml");
    if (parameter != null) {
        ServletContext context = getServletContext();
        InputStream fis = context.getResourceAsStream(parameter);
        processRequest(fis, out, request.getParameter("fileName"));
    } else {
        try {
            // Process the uploaded items
            List<?> /* FileItem */ items = upload.parseRequest(request);
            Iterator<?> iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();

                if (item.isFormField()) {
                    // processFormField(item);
                } else {
                    // processUploadedFile(item);
                    String paramName = item.getFieldName();
                    String fileName = item.getName();
                    InputStream stream = item.getInputStream();
                    MorphbankConfig.SYSTEM_LOGGER.info("Processing file " + fileName);
                    processRequest(stream, out, fileName);
                    MorphbankConfig.SYSTEM_LOGGER.info("Processing complete");
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
    }
}

From source file:it.eng.spagobi.engines.talend.services.JobUploadService.java

private JobDeploymentDescriptor getJobsDeploymetDescriptor(List items) {
    JobDeploymentDescriptor jobDeploymentDescriptor = null;

    Iterator iter = items.iterator();
    while (iter.hasNext()) {
        FileItem item = (FileItem) iter.next();
        if (!item.isFormField()) {
            String fieldName = item.getFieldName();
            if (fieldName.equalsIgnoreCase("deploymentDescriptor")) {
                jobDeploymentDescriptor = new JobDeploymentDescriptor();
                try {
                    jobDeploymentDescriptor.load(item.getInputStream());
                } catch (DocumentException e) {
                    e.printStackTrace();
                    return null;
                } catch (IOException e) {
                    e.printStackTrace();
                    return null;
                }/*from  ww  w  .  ja  v a  2 s. c o m*/
            }
        }
    }
    return jobDeploymentDescriptor;
}

From source file:com.enonic.cms.web.portal.services.FormServicesProcessor.java

private void createAndSendMail(String subject, User user, String[] recipients, ExtendedMap formItems,
        StringBuffer body, String fromEmail, String fromName, boolean addAttachment) {
    final SimpleMailTemplate formMail = new SimpleMailTemplate();
    if (fromEmail != null) {
        formMail.setFrom(fromName, fromEmail);
    } else {// w  w  w  .j  ava 2s  .co m
        if (user.getType() != UserType.ANONYMOUS) {
            formMail.setFrom(user.getDisplayName(), user.getEmail());
        } else {
            formMail.setFrom("Anonymous", adminEmail);
        }
    }

    formMail.setSubject(subject);
    formMail.setMessage(body.toString());
    for (String recipient : recipients) {
        formMail.addRecipient(null, recipient, MailRecipientType.TO_RECIPIENT);
    }

    if (addAttachment) {
        if (formItems.hasFileItems()) {
            FileItem[] fileItems = formItems.getFileItems();
            for (FileItem fileItem : fileItems) {
                try {
                    formMail.addAttachment(fileItem.getName(), fileItem.getInputStream());
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
    sendMailService.sendMail(formMail);
}

From source file:com.sun.licenseserver.License.java

/**
 * Construct a license object using the input provided in the 
 * request object,/*  w  w w  . j  a v a2 s.c o m*/
 * 
 * @param req
 */
public License(HttpServletRequest req) {
    if (FileUpload.isMultipartContent(req)) {
        DiskFileUpload upload = new DiskFileUpload();
        upload.setSizeMax(2 * 1024 * 1024);
        List items;
        try {
            items = upload.parseRequest(req);
        } catch (FileUploadException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return;
        }
        Iterator iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            if (!item.isFormField()) {
                if (item.getSize() > 2 * 1024 * 1024) {
                    continue;
                }
                m_log.fine("Size of uploaded license is [" + item.getSize() + "]");
                try {
                    license = item.getInputStream();
                    licSize = item.getSize();
                    mime = item.getContentType();
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                    return;
                }

            } else {
                String name = item.getFieldName();
                String value = item.getString();
                m_log.fine("MC ItemName [" + name + "] Value[" + value + "]");
                if (name != null) {
                    if (name.equals("id")) {
                        id = value;
                        continue;
                    }
                    if (name.equals("userId")) {
                        userId = value;
                        continue;
                    }
                    if (name.equals("contentId")) {
                        contentId = value;
                        continue;
                    }
                    if (name.equals("shopId")) {
                        shopId = value;
                        continue;
                    }

                }
            }

        }
    }
}

From source file:hudson.plugins.promoted_builds_simple.PromotedBuildsSimplePlugin.java

/**
 * Receive file upload from startUpload.jelly.
 * File is placed in $JENKINS_HOME/userContent directory.
 *//*from   w  w  w  .ja  v  a2 s .  c  o  m*/
public void doUpload(StaplerRequest req, StaplerResponse rsp)
        throws IOException, ServletException, InterruptedException {
    Hudson hudson = Hudson.getInstance();
    hudson.checkPermission(Hudson.ADMINISTER);
    FileItem file = req.getFileItem("badgeicon.file");
    String error = null, filename = null;
    if (file == null || file.getName().isEmpty())
        error = Messages.Upload_NoFile();
    else {
        filename = "userContent/"
                // Sanitize given filename:
                + file.getName().replaceFirst(".*/", "").replaceAll("[^\\w.,;:()#@!=+-]", "_");
        FilePath imageFile = hudson.getRootPath().child(filename);
        if (imageFile.exists())
            error = Messages.Upload_DupName();
        else {
            imageFile.copyFrom(file.getInputStream());
            imageFile.chmod(0644);
        }
    }
    rsp.setContentType("text/html");
    rsp.getWriter().println((error != null ? error : Messages.Upload_Uploaded("<tt>/" + filename + "</tt>"))
            + " <a href=\"javascript:history.back()\">" + Messages.Upload_Back() + "</a>");
}