Example usage for org.apache.commons.fileupload FileItemStream openStream

List of usage examples for org.apache.commons.fileupload FileItemStream openStream

Introduction

In this page you can find the example usage for org.apache.commons.fileupload FileItemStream openStream.

Prototype

InputStream openStream() throws IOException;

Source Link

Document

Creates an InputStream , which allows to read the items contents.

Usage

From source file:sapience.proxy.spring.StreamingMultipartFile.java

public StreamingMultipartFile(FileItemStream item) throws IOException {

    this.item = item;

    // copy into bytes
    bytes = IOUtils.toByteArray(item.openStream());

}

From source file:se.vgregion.portal.innovationsslussen.idea.controller.IdeaViewController.java

/**
 * Upload file action.//from   w w  w . j  av  a  2s.  c  o  m
 *
 * @param request  the request
 * @param response the response
 * @param model    the model
 * @throws FileUploadException the file upload exception
 */
@ActionMapping(params = "action=uploadFile")
public void uploadFile(ActionRequest request, ActionResponse response, Model model)
        throws FileUploadException, SystemException, PortalException {

    ThemeDisplay themeDisplay = getThemeDisplay(request);
    long scopeGroupId = themeDisplay.getScopeGroupId();
    long userId = themeDisplay.getUserId();

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

    String fileType = request.getParameter("fileType");
    boolean publicIdea;
    if (fileType.equals("public")) {
        publicIdea = true;
    } else if (fileType.equals("private")) {
        publicIdea = false;
    } else {
        throw new IllegalArgumentException("Unknown filetype: " + fileType);
    }

    //TODO ondig slagning? Cacha?
    Idea idea = ideaService.findIdeaByUrlTitle(urlTitle);
    //TODO Kan det inte finnas flera med samma titel i olika communities?

    IdeaContentType ideaContentType = publicIdea ? IdeaContentType.IDEA_CONTENT_TYPE_PUBLIC
            : IdeaContentType.IDEA_CONTENT_TYPE_PRIVATE;

    if (!isAllowedToDoAction(request, idea, Action.UPLOAD_FILE, ideaContentType)) {
        sendRedirectToContextRoot(response);
        return;
    }

    boolean mayUploadFile = idea.getUserId() == userId;

    IdeaPermissionChecker ideaPermissionChecker = ideaPermissionCheckerService
            .getIdeaPermissionChecker(scopeGroupId, userId, idea);

    if (!mayUploadFile) {
        if (publicIdea) {
            mayUploadFile = ideaPermissionChecker.isHasPermissionAddDocumentPublic();
        } else {
            mayUploadFile = ideaPermissionChecker.isHasPermissionAddDocumentPrivate();
        }
    }

    if (mayUploadFile) {
        response.setRenderParameter("urlTitle", urlTitle);

        PortletFileUpload p = new PortletFileUpload();

        try {
            FileItemIterator itemIterator = p.getItemIterator(request);

            while (itemIterator.hasNext()) {
                FileItemStream fileItemStream = itemIterator.next();

                if (fileItemStream.getFieldName().equals("file")) {

                    InputStream is = fileItemStream.openStream();
                    BufferedInputStream bis = new BufferedInputStream(is);

                    String fileName = fileItemStream.getName();
                    String contentType = fileItemStream.getContentType();

                    ideaService.uploadFile(idea, publicIdea, fileName, contentType, bis);
                }
            }
        } catch (FileUploadException e) {
            doExceptionStuff(e, response, model);
            return;
        } catch (IOException e) {
            doExceptionStuff(e, response, model);
            return;
        } catch (se.vgregion.service.innovationsslussen.exception.FileUploadException e) {
            doExceptionStuff(e, response, model);
            return;
        } catch (RuntimeException e) {
            Throwable lastCause = Util.getLastCause(e);
            if (lastCause instanceof SQLException) {
                SQLException nextException = ((SQLException) lastCause).getNextException();
                if (nextException != null) {
                    LOGGER.error(nextException.getMessage(), nextException);
                }
            }
        } finally {
            response.setRenderParameter("ideaType", fileType);
        }
    } else {
        throw new FileUploadException("The user is not authorized to upload to this idea instance.");
    }

    response.setRenderParameter("urlTitle", urlTitle);
    response.setRenderParameter("type", fileType);
    response.setRenderParameter("showView", "showIdea");
}

From source file:tech.oleks.pmtalk.PmTalkServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    Order o = new Order();
    ServletFileUpload upload = new ServletFileUpload();
    try {/*w w  w .j av a2 s.com*/
        FileItemIterator it = upload.getItemIterator(req);
        while (it.hasNext()) {
            FileItemStream item = it.next();
            InputStream fieldValue = item.openStream();
            String fieldName = item.getFieldName();
            if ("candidate".equals(fieldName)) {
                String candidate = Streams.asString(fieldValue);
                o.setCandidate(candidate);
            } else if ("staffing".equals(fieldName)) {
                String staffingLink = Streams.asString(fieldValue);
                o.setStaffingLink(staffingLink);
            } else if ("resume".equals(fieldName)) {
                FileUpload resume = new FileUpload();
                ByteArrayOutputStream os = new ByteArrayOutputStream();
                IOUtils.copy(fieldValue, os);
                resume.setStream(new ByteArrayInputStream(os.toByteArray()));
                resume.setContentType(item.getContentType());
                resume.setFileName(item.getName());
                o.setResume(resume);
            }
        }
    } catch (FileUploadException e) {
        e.printStackTrace();
    }

    pmTalkService.minimal(o);
    req.setAttribute("order", o);
    if (o.getErrors() != null) {
        forward("/form.jsp", req, resp);
    } else {
        forward("/created.jsp", req, resp);
    }
}

From source file:temporal.web.DemoServlet.java

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

    InputStream in = null;//from   w  ww .j  a  va2s.c o m
    OutputStream out = null;

    try {
        response.setContentType(mDemo.responseType());
        out = response.getOutputStream();

        @SuppressWarnings("unchecked") // bad inherited API from commons
        Properties properties = mapToProperties((Map<String, String[]>) request.getParameterMap());

        String reqContentType = request.getContentType();

        if (reqContentType == null || reqContentType.startsWith("text/plain")) {
            properties.setProperty("inputType", "text/plain");
            String reqCharset = request.getCharacterEncoding();
            if (reqCharset != null)
                properties.setProperty("inputCharset", reqCharset);
            in = request.getInputStream();

        } else if (reqContentType.startsWith("application/x-www-form-urlencoded")) {
            String codedText = request.getParameter("inputText");
            byte[] bytes = codedText.getBytes("ISO-8859-1");
            in = new ByteArrayInputStream(bytes);

        } else if (ServletFileUpload.isMultipartContent(new ServletRequestContext(request))) {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload uploader = new ServletFileUpload(factory);
            FileItemIterator it = uploader.getItemIterator(request);
            /*  @SuppressWarnings("unchecked") // bad commons API
            /*  List<FileItem> items = (List<FileItem>) uploader.parseRequest(request);
              Iterator<FileItem> it = items.iterator();*/
            while (it.hasNext()) {
                log("found item");
                FileItemStream item = it.next();
                InputStream stream = item.openStream();
                if (item.isFormField()) {
                    String key = item.getFieldName();
                    //   String val = item.getString();
                    String val = org.apache.commons.fileupload.util.Streams.asString(stream);
                    properties.setProperty(key, val);
                } else {
                    byte[] bytes = org.apache.commons.fileupload.util.Streams.asString(stream).getBytes();
                    in = new ByteArrayInputStream(bytes);
                }
            }

        } else {
            System.out.println("unexpected content type");
            String msg = "Unexpected request content" + reqContentType;
            throw new ServletException(msg);
        }
        mDemo.process(in, out, properties);
    } catch (FileUploadException e) {
        throw new ServletException(e);
    } finally {
        Streams.closeQuietly(in);
        Streams.closeQuietly(out);
    }
}

From source file:uk.ac.ebi.sail.server.service.UploadSvc.java

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    // Check that we have a file upload request
    boolean isMultipart = ServletFileUpload.isMultipartContent(req);

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

    String res = null;/*from   w ww . j a  v a2s  .c o m*/
    int studyID = -1;
    int collectionID = -1;

    String fileContent = null;

    String upType = null;

    try {
        // Parse the request
        FileItemIterator iter = upload.getItemIterator(req);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            String name = item.getFieldName();
            InputStream stream = item.openStream();
            if (item.isFormField()) {
                if ("CollectionID".equals(name)) {
                    try {
                        collectionID = Integer.parseInt(Streams.asString(stream));
                    } catch (Exception e) {
                    }
                }
                if ("StudyID".equals(name)) {
                    try {
                        studyID = Integer.parseInt(Streams.asString(stream));
                    } catch (Exception e) {
                    }
                } else if ("UploadType".equals(name)) {
                    upType = Streams.asString(stream);
                }

                //     System.out.println("Form field " + name + " with value " + Streams.asString(stream) + " detected.");
            } else {
                //     System.out.println("File field " + name + " with file name " + item.getName() + " detected.");
                InputStream uploadedStream = item.openStream();
                ByteArrayOutputStream baos = new ByteArrayOutputStream();

                StreamPump.doPump(uploadedStream, baos);

                byte[] barr = baos.toByteArray();

                if ((barr[0] == -1 && barr[1] == -2) || (barr[0] == -2 && barr[1] == -1))
                    fileContent = new String(barr, "UTF-16");
                else
                    fileContent = new String(barr);
            }
        }
    } catch (Exception ex) {
        res = ex.getMessage();
        ex.printStackTrace();
    }

    if (fileContent != null) {
        if ("AvailabilityData".equals(upType)) {
            if (collectionID != -1) {
                try {
                    DataManager.getInstance().importData(fileContent, collectionID);
                } catch (Exception ex) {
                    res = ex.getMessage();
                    ex.printStackTrace();
                }
            } else
                res = "Invalid or absent collection ID";
        } else if ("RelationMap".equals(upType)) {
            try {
                DataManager.getInstance().importRelations(new String(fileContent));
            } catch (Exception ex) {
                res = ex.getMessage();
                ex.printStackTrace();
            }
        } else if ("Study2SampleRelation".equals(upType)) {
            try {
                DataManager.getInstance().importSample2StudyRelations(new String(fileContent), studyID,
                        collectionID);
            } catch (Exception ex) {
                res = ex.getMessage();
                ex.printStackTrace();
            }
        } else {
            try {
                DataManager.getInstance().importParameters(fileContent);
            } catch (ParseException pex) {
                res = "Line " + pex.getLineNumber() + ": " + pex.getMessage();
            } catch (Exception ex) {
                res = ex.getMessage();
                ex.printStackTrace();
            }

        }

    } else {
        res = "File content not found";
    }

    JSONObject response = null;
    try {
        response = new JSONObject();
        response.put("success", res == null);
        response.put("error", res == null ? "uploaded successfully" : res);
        response.put("code", "232");
    } catch (Exception e) {

    }

    Writer w = new OutputStreamWriter(resp.getOutputStream());
    w.write(response.toString());
    System.out.println(response.toString());
    w.close();
    resp.setStatus(HttpServletResponse.SC_OK);
}

From source file:us.mn.state.health.lims.analyzerimport.action.AnalyzerImportServlet.java

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

    String password = null;/*from   w w  w  .j  a v a2  s .co m*/
    String user = null;
    AnalyzerReader reader = null;
    boolean fileRead = false;

    InputStream stream = null;

    try {
        ServletFileUpload upload = new ServletFileUpload();

        FileItemIterator iterator = upload.getItemIterator(request);
        while (iterator.hasNext()) {
            FileItemStream item = iterator.next();
            stream = item.openStream();

            String name = null;

            if (item.isFormField()) {

                if (PASSWORD.equals(item.getFieldName())) {
                    password = streamToString(stream);
                } else if (USER.equals(item.getFieldName())) {
                    user = streamToString(stream);
                }

            } else {

                name = item.getName();

                reader = AnalyzerReaderFactory.getReaderFor(name);

                if (reader != null) {
                    fileRead = reader.readStream(new InputStreamReader(stream));
                }
            }

            stream.close();
        }
    } catch (Exception ex) {
        throw new ServletException(ex);
    } finally {
        if (stream != null) {
            try {
                stream.close();
            } catch (IOException e) {
                //   LOG.warning(e.toString());
            }
        }
    }

    if (GenericValidator.isBlankOrNull(user) || GenericValidator.isBlankOrNull(password)) {
        response.getWriter().print("missing user");
        response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
        return;
    }

    if (!userValid(user, password)) {
        response.getWriter().print("invalid user/password");
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    if (fileRead) {
        boolean successful = reader.insertAnalyzerData(systemUserId);

        if (successful) {
            response.getWriter().print("success");
            response.setStatus(HttpServletResponse.SC_OK);
            return;
        } else {
            response.getWriter().print(reader.getError());
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }

    } else {
        response.getWriter().print(reader.getError());
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }

}

From source file:util.Support.java

public static boolean processFile(String filePath, FileItemStream itemStream, String imageName,
        String fileExtension) {/*from www.j  av a 2s  .c om*/
    try {
        File f = new File(filePath);
        if (f.exists()) {
            f.mkdir();
        }
        File saveFile = new File(f.getAbsolutePath() + File.separator + imageName + "." + fileExtension);
        try (FileOutputStream fos = new FileOutputStream(saveFile)) {
            InputStream is = itemStream.openStream();
            int x = 0;
            byte[] b = new byte[1024];
            while ((x = is.read(b)) != -1) {
                fos.write(b, 0, x);
            }
            fos.flush();
            fos.close();
        }
        return true;
    } catch (IOException e) {
        e.printStackTrace();
    }
    return false;
}

From source file:zutil.jee.upload.AjaxFileUpload.java

@SuppressWarnings("unchecked")
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    FileUploadListener listener = new FileUploadListener();
    try {//from www  .  j ava2s  . c  om
        // Initiate list and HashMap that will contain the data
        HashMap<String, String> fields = new HashMap<String, String>();
        ArrayList<FileItem> files = new ArrayList<FileItem>();

        // Add the listener to the session
        HttpSession session = request.getSession();
        LinkedList<FileUploadListener> list = (LinkedList<FileUploadListener>) session
                .getAttribute(SESSION_FILEUPLOAD_LISTENER);
        if (list == null) {
            list = new LinkedList<FileUploadListener>();
            session.setAttribute(SESSION_FILEUPLOAD_LISTENER, list);
        }
        list.add(listener);

        // Create a factory for disk-based file items
        DiskFileItemFactory factory = new DiskFileItemFactory();
        if (TEMPFILE_PATH != null)
            factory.setRepository(TEMPFILE_PATH);
        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setProgressListener(listener);
        // Set overall request size constraint
        //upload.setSizeMax(yourMaxRequestSize);

        // Parse the request
        FileItemIterator it = upload.getItemIterator(request);
        while (it.hasNext()) {
            FileItemStream item = it.next();
            // Is the file type allowed?
            if (!item.isFormField()
                    && !ALLOWED_EXTENSIONS.contains(FileUtil.getFileExtension(item.getName()).toLowerCase())) {
                String msg = "Filetype '" + FileUtil.getFileExtension(item.getName()) + "' is not allowed!";
                logger.warning(msg);
                listener.setStatus(Status.Error);
                listener.setFileName(item.getName());
                listener.setMessage(msg);
                return;
            }
            listener.setFileName(item.getName());
            FileItem fileItem = factory.createItem(item.getFieldName(), item.getContentType(),
                    item.isFormField(), item.getName());
            // Read the file data
            Streams.copy(item.openStream(), fileItem.getOutputStream(), true);
            if (fileItem instanceof FileItemHeadersSupport) {
                final FileItemHeaders fih = item.getHeaders();
                ((FileItemHeadersSupport) fileItem).setHeaders(fih);
            }

            //Handle the item
            if (fileItem.isFormField()) {
                fields.put(fileItem.getFieldName(), fileItem.getString());
            } else {
                files.add(fileItem);
                logger.info("Recieved file: " + fileItem.getName() + " ("
                        + StringUtil.formatByteSizeToString(fileItem.getSize()) + ")");
            }
        }
        // Process the upload
        listener.setStatus(Status.Processing);
        doUpload(request, response, fields, files);
        // Done
        listener.setStatus(Status.Done);
    } catch (Exception e) {
        logger.log(Level.SEVERE, null, e);
        listener.setStatus(Status.Error);
        listener.setFileName("");
        listener.setMessage(e.getMessage());
    }
}