Example usage for org.apache.commons.fileupload.servlet ServletFileUpload ServletFileUpload

List of usage examples for org.apache.commons.fileupload.servlet ServletFileUpload ServletFileUpload

Introduction

In this page you can find the example usage for org.apache.commons.fileupload.servlet ServletFileUpload ServletFileUpload.

Prototype

public ServletFileUpload() 

Source Link

Document

Constructs an uninitialised instance of this class.

Usage

From source file:com.pronoiahealth.olhie.server.rest.BooklogoUploadServiceImpl.java

@Override
@POST//from  w  w w . j a v  a2s .c  o  m
@Path("/upload")
@Produces("text/html")
@SecureAccess({ SecurityRoleEnum.ADMIN, SecurityRoleEnum.AUTHOR })
public String process(@Context HttpServletRequest req)
        throws ServletException, IOException, FileUploadException {
    try {
        // Check that we have a file upload request
        boolean isMultipart = ServletFileUpload.isMultipartContent(req);
        if (isMultipart == true) {

            // FileItemFactory fileItemFactory = new FileItemFactory();
            String bookId = null;
            String contentType = null;
            // String data = null;
            byte[] bytes = null;
            String fileName = null;
            long size = 0;
            ServletFileUpload fileUpload = new ServletFileUpload();
            fileUpload.setSizeMax(FILE_SIZE_LIMIT);
            FileItemIterator iter = fileUpload.getItemIterator(req);
            while (iter.hasNext()) {
                FileItemStream item = iter.next();
                InputStream stream = item.openStream();
                if (item.isFormField()) {
                    // BookId
                    if (item.getFieldName().equals("bookId")) {
                        bookId = Streams.asString(stream);
                    }
                } else {
                    if (item != null) {
                        contentType = item.getContentType();
                        fileName = item.getName();
                        item.openStream();
                        InputStream in = item.openStream();
                        ByteArrayOutputStream bos = new ByteArrayOutputStream();
                        IOUtils.copy(in, bos);
                        bytes = bos.toByteArray(); // fileItem.get();
                        size = bytes.length;
                        // data = Base64.encodeBytes(bytes);
                    }
                }
            }

            // Add the logo
            Book book = bookDAO.getBookById(bookId);

            // Update the front cover
            BookCategory cat = holder.getCategoryByName(book.getCategory());
            BookCover cover = holder.getCoverByName(book.getCoverName());
            String authorName = bookDAO.getAuthorName(book.getAuthorId());
            //String frontBookCoverEncoded = imgService
            //      .createDefaultFrontCoverEncoded(book, cat, cover,
            //            bytes, authorName);
            byte[] frontBookCoverBytes = imgService.createDefaultFrontCover(book, cat, cover, bytes,
                    authorName);

            //String smallFrontBookCoverEncoded = imgService
            //      .createDefaultSmallFrontCoverEncoded(book, cat, cover,
            //            bytes, authorName);
            byte[] frontBookCoverSmallBytes = imgService.createDefaultSmallFrontCover(book, cat, cover, bytes,
                    authorName);

            // Save it
            // Add the logo
            book = bookDAO.addLogoAndFrontCoverBytes(bookId, contentType, bytes, fileName, size,
                    frontBookCoverBytes, frontBookCoverSmallBytes);

        }
        return "OK";
    } catch (Exception e) {
        log.log(Level.SEVERE, "Throwing servlet exception for unhandled exception", e);
        // return "ERROR:\n" + e.getMessage();

        if (e instanceof FileUploadException) {
            throw (FileUploadException) e;
        } else {
            throw new FileUploadException(e.getMessage());
        }
    }
}

From source file:guru.nidi.ramltester.util.FormDecoder.java

private Values decodeMultipart(RamlRequest request) {
    try {//from   w  w  w.  j av a 2  s  .c o  m
        final Values values = new Values();
        final RamlRequestFileUploadContext context = new RamlRequestFileUploadContext(request);
        final FileItemIterator iter = new ServletFileUpload().getItemIterator(context);
        while (iter.hasNext()) {
            final FileItemStream itemStream = iter.next();
            values.addValue(itemStream.getFieldName(), valueOf(itemStream));
        }
        return values;
    } catch (IOException | FileUploadException e) {
        throw new IllegalArgumentException("Could not parse multipart request", e);
    }
}

From source file:com.vmware.photon.controller.api.frontend.resources.vm.VmIsoAttachResource.java

private Task parseIsoDataFromRequest(HttpServletRequest request, String id)
        throws InternalException, ExternalException {
    Task task = null;//  w  ww  .  java2 s . co m

    ServletFileUpload fileUpload = new ServletFileUpload();
    List<InputStream> dataStreams = new LinkedList<>();

    try {
        FileItemIterator iterator = fileUpload.getItemIterator(request);
        while (iterator.hasNext()) {
            FileItemStream item = iterator.next();
            if (item.isFormField()) {
                logger.warn(String.format("The parameter '%s' is unknown in attach ISO.", item.getFieldName()));
            } else {
                InputStream fileStream = item.openStream();
                dataStreams.add(fileStream);

                task = vmFeClient.attachIso(id, fileStream, item.getName());
            }
        }
    } catch (IOException ex) {
        throw new IsoUploadException("Iso upload IOException", ex);
    } catch (FileUploadException ex) {
        throw new IsoUploadException("Iso upload FileUploadException", ex);
    } finally {
        for (InputStream stream : dataStreams) {
            try {
                stream.close();
            } catch (IOException | NullPointerException ex) {
                logger.warn("Unexpected exception closing data stream.", ex);
            }
        }
    }

    if (task == null) {
        throw new IsoUploadException("There is no iso stream data in the iso upload request.");
    }

    return task;
}

From source file:com.priocept.jcr.server.UploadServlet.java

private void processFiles(HttpServletRequest request, HttpServletResponse response) {
    HashMap<String, String> args = new HashMap<String, String>();
    try {/*from w  ww  . jav  a  2s  .c o  m*/
        if (log.isDebugEnabled())
            log.debug(request.getParameterMap());
        ServletFileUpload upload = new ServletFileUpload();
        FileItemIterator iter = upload.getItemIterator(request);
        // pick up parameters first and note actual FileItem
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            String name = item.getFieldName();
            if (item.isFormField()) {
                args.put(name, Streams.asString(item.openStream()));
            } else {
                args.put("contentType", item.getContentType());
                String fileName = item.getName();
                int slash = fileName.lastIndexOf("/");
                if (slash < 0)
                    slash = fileName.lastIndexOf("\\");
                if (slash > 0)
                    fileName = fileName.substring(slash + 1);
                args.put("fileName", fileName);

                if (log.isDebugEnabled())
                    log.debug(args);

                InputStream in = null;
                try {
                    in = item.openStream();
                    writeToFile(request.getSession().getId() + "/" + fileName, in, true,
                            request.getSession().getServletContext().getRealPath("/"));
                } catch (Exception e) {
                    //                  e.printStackTrace();
                    log.error("Fail to upload " + fileName);

                    response.setContentType("text/html");
                    response.setHeader("Pragma", "No-cache");
                    response.setDateHeader("Expires", 0);
                    response.setHeader("Cache-Control", "no-cache");
                    PrintWriter out = response.getWriter();
                    out.println("<html>");
                    out.println("<body>");
                    out.println("<script type=\"text/javascript\">");
                    out.println("if (parent.uploadFailed) parent.uploadFailed('"
                            + e.getLocalizedMessage().replaceAll("\'|\"", "") + "');");
                    out.println("</script>");
                    out.println("</body>");
                    out.println("</html>");
                    out.flush();
                    return;
                } finally {
                    if (in != null)
                        try {
                            in.close();
                        } catch (Exception e) {
                        }
                }

            }
        }
        response.setContentType("text/html");
        response.setHeader("Pragma", "No-cache");
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-cache");
        PrintWriter out = response.getWriter();
        out.println("<html>");
        out.println("<body>");
        out.println("<script type=\"text/javascript\">");
        out.println("if (parent.uploadComplete) parent.uploadComplete('" + args.get("fileName") + "');");
        out.println("</script>");
        out.println("</body>");
        out.println("</html>");
        out.flush();
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
}

From source file:com.northernwall.hadrian.handler.ImageHandler.java

private void updateImage(Request request, String serviceId) throws IOException, FileUploadException {
    if (!ServletFileUpload.isMultipartContent(request)) {
        logger.warn("Trying to upload image for {} but content is not multipart", serviceId);
        return;//  w w w.  j  a  va2 s. c om
    }
    logger.info("Trying to upload image for {}", serviceId);
    ServletFileUpload upload = new ServletFileUpload();

    // Parse the request
    FileItemIterator iter = upload.getItemIterator(request);
    while (iter.hasNext()) {
        FileItemStream item = iter.next();
        if (!item.isFormField()) {
            String name = item.getName();
            name = name.replace(' ', '-').replace('&', '-').replace('<', '-').replace('>', '-')
                    .replace('/', '-').replace('\\', '-').replace('&', '-').replace('@', '-').replace('?', '-')
                    .replace('^', '-').replace('#', '-').replace('%', '-').replace('=', '-').replace('$', '-')
                    .replace('{', '-').replace('}', '-').replace('[', '-').replace(']', '-').replace('|', '-')
                    .replace(';', '-').replace(':', '-').replace('~', '-').replace('`', '-');
            dataAccess.uploadImage(serviceId, name, item.getContentType(), item.openStream());
        }
    }
}

From source file:com.doculibre.constellio.feedprotocol.FeedServlet.java

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

    LOG.fine("FeedServlet: doPost(...)");
    // Check that we have a file upload request
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    PrintWriter out = null;//from w w w. java2s .com
    try {
        out = response.getWriter();
        if (isMultipart) {
            ServletFileUpload upload = new ServletFileUpload();

            String datasource = null;
            String feedtype = null;

            FileItemIterator iter = upload.getItemIterator(request);
            while (iter.hasNext()) {
                FileItemStream item = iter.next();
                //Disabled to allow easier update from HTML forms
                //if (item.isFormField()) {
                if (item.getFieldName().equals(FeedParser.XML_DATASOURCE)) {
                    InputStream itemStream = null;
                    try {
                        itemStream = item.openStream();
                        datasource = IOUtils.toString(itemStream);
                    } finally {
                        IOUtils.closeQuietly(itemStream);
                    }
                } else if (item.getFieldName().equals(FeedParser.XML_FEEDTYPE)) {
                    InputStream itemStream = null;
                    try {
                        itemStream = item.openStream();
                        feedtype = IOUtils.toString(itemStream);
                    } finally {
                        IOUtils.closeQuietly(itemStream);
                    }
                } else if (item.getFieldName().equals(FeedParser.XML_DATA)) {
                    try {
                        if (StringUtils.isBlank(datasource)) {
                            throw new IllegalArgumentException("Datasource is blank");
                        }
                        if (StringUtils.isBlank(feedtype)) {
                            throw new IllegalArgumentException("Feedtype is blank");
                        }

                        InputStream contentStream = null;
                        try {
                            contentStream = item.openStream();
                            final Feed feed = new FeedStaxParser().parse(datasource, feedtype, contentStream);

                            Callable<Object> processFeedTask = new Callable<Object>() {
                                @Override
                                public Object call() throws Exception {
                                    FeedProcessor feedProcessor = new FeedProcessor(feed);
                                    feedProcessor.processFeed();
                                    return null;
                                }
                            };
                            threadPoolExecutor.submit(processFeedTask);

                            out.append(GsaFeedConnection.SUCCESS_RESPONSE);
                            return;
                        } catch (Exception e) {
                            LOG.log(Level.SEVERE, "Exception while processing contentStream", e);
                        } finally {
                            IOUtils.closeQuietly(contentStream);
                        }
                    } finally {
                        IOUtils.closeQuietly(out);
                    }
                }
                //}
            }
        }
    } catch (Throwable e) {
        LOG.log(Level.SEVERE, "Exception while uploading", e);
    } finally {
        IOUtils.closeQuietly(out);
    }
    out.append(GsaFeedConnection.INTERNAL_ERROR_RESPONSE);
}

From source file:de.eorganization.hoopla.server.servlets.TemplateImportServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    DecisionTemplate newDecisionTemplate = new DecisionTemplate();
    DecisionTemplate decisionTemplate = null;
    try {/*from  ww w.ja v  a  2s .  c  o m*/

        ServletFileUpload upload = new ServletFileUpload();
        resp.setContentType("text/plain");

        FileItemIterator itemIterator = upload.getItemIterator(req);
        while (itemIterator.hasNext()) {
            FileItemStream item = itemIterator.next();
            if (item.isFormField() && "substituteTemplateId".equals(item.getFieldName())) {
                log.warning("Got a form field: " + item.getFieldName());

                String itemContent = IOUtils.toString(item.openStream());
                try {
                    decisionTemplate = new HooplaServiceImpl()
                            .getDecisionTemplate(new Long(itemContent).longValue());
                    new HooplaServiceImpl().deleteDecisionTemplate(decisionTemplate);
                } catch (Exception e) {
                    log.log(Level.WARNING, e.getLocalizedMessage(), e);
                }
                if (decisionTemplate == null)
                    newDecisionTemplate.setKeyId(new Long(itemContent).longValue());
                else
                    newDecisionTemplate.setKeyId(decisionTemplate.getKeyId());
            } else {
                InputStream stream = item.openStream();

                log.info("Got an uploaded file: " + item.getFieldName() + ", name = " + item.getName());

                Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(stream);

                // doc.getDocumentElement().normalize();

                Element decisionElement = doc.getDocumentElement();
                String rootName = decisionElement.getNodeName();
                if (rootName.equals("decision")) {
                    isDecisionTemplate = false;
                } else if (rootName.equals("decisionTemplate")) {
                    isDecisionTemplate = true;
                } else {
                    log.warning("This XML Document has a wrong RootElement: " + rootName
                            + ". It should be <decision> or <decisionTemplate>.");
                }

                NodeList decisionNodes = decisionElement.getChildNodes();
                for (int i = 0; i < decisionNodes.getLength(); i++) {
                    Node node = decisionNodes.item(i);

                    if (node instanceof Element) {
                        Element child = (Element) node;
                        if (child.getNodeName().equals("name") && !child.getTextContent().equals("")) {
                            newDecisionTemplate.setName(child.getTextContent());
                            log.info("Parsed decision name: " + newDecisionTemplate.getName());
                        }
                        if (child.getNodeName().equals("description") && !child.getTextContent().equals("")) {
                            newDecisionTemplate.setDescription(child.getTextContent());
                            log.info("Parsed decision description: " + newDecisionTemplate.getDescription());
                        }
                        if (isDecisionTemplate && child.getNodeName().equals("templateName")) {
                            newDecisionTemplate.setTemplateName(child.getTextContent());
                            log.info("Parsed decision TemplateName: " + newDecisionTemplate.getTemplateName());
                        }
                        if (child.getNodeName().equals("alternatives")) {
                            parseAlternatives(child.getChildNodes(), newDecisionTemplate);
                        }
                        if (child.getNodeName().equals("goals")) {
                            parseGoals(child.getChildNodes(), newDecisionTemplate);
                        }
                        if (child.getNodeName().equals("importanceGoals")) {
                            parseGoalImportances(child.getChildNodes(), newDecisionTemplate);
                        }
                    }
                }

                log.info("Fully parsed XML Upload: " + newDecisionTemplate.toString());

            }
        }

    } catch (Exception ex) {
        log.log(Level.WARNING, ex.getLocalizedMessage(), ex);
        resp.sendError(400);
        return;
    }

    try {
        new HooplaServiceImpl().storeDecisionTemplate(newDecisionTemplate);
    } catch (Exception e) {
        log.log(Level.WARNING, e.getLocalizedMessage(), e);
        resp.sendError(500);
        return;
    }

    log.info("returning to referer " + req.getHeader("referer"));
    resp.sendRedirect(
            req.getHeader("referer") != null && !"".equals(req.getHeader("referer")) ? req.getHeader("referer")
                    : "localhost:8088");
}

From source file:com.twosigma.beaker.core.module.elfinder.ConnectorController.java

private HttpServletRequest parseMultipartContent(final HttpServletRequest request) throws Exception {
    if (!ServletFileUpload.isMultipartContent(request))
        return request;

    final Map<String, String> requestParams = new HashMap<String, String>();
    List<FileItemStream> listFiles = new ArrayList<FileItemStream>();

    // Parse the request
    ServletFileUpload sfu = new ServletFileUpload();
    String characterEncoding = request.getCharacterEncoding();
    if (characterEncoding == null) {
        characterEncoding = "UTF-8";
    }//from  w  ww.  j  ava  2s. co m
    sfu.setHeaderEncoding(characterEncoding);
    FileItemIterator iter = sfu.getItemIterator(request);

    while (iter.hasNext()) {
        final FileItemStream item = iter.next();
        String name = item.getFieldName();
        InputStream stream = item.openStream();
        if (item.isFormField()) {
            requestParams.put(name, Streams.asString(stream, characterEncoding));
        } else {
            String fileName = item.getName();
            if (fileName != null && !"".equals(fileName.trim())) {
                ByteArrayOutputStream os = new ByteArrayOutputStream();
                IOUtils.copy(stream, os);
                final byte[] bs = os.toByteArray();
                stream.close();

                listFiles.add((FileItemStream) Proxy.newProxyInstance(this.getClass().getClassLoader(),
                        new Class[] { FileItemStream.class }, new InvocationHandler() {
                            @Override
                            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                                if ("openStream".equals(method.getName())) {
                                    return new ByteArrayInputStream(bs);
                                }

                                return method.invoke(item, args);
                            }
                        }));
            }
        }
    }

    request.setAttribute(FileItemStream.class.getName(), listFiles);

    Object proxyInstance = Proxy.newProxyInstance(this.getClass().getClassLoader(),
            new Class[] { HttpServletRequest.class }, new InvocationHandler() {
                @Override
                public Object invoke(Object arg0, Method arg1, Object[] arg2) throws Throwable {
                    // we replace getParameter() and getParameterValues()
                    // methods
                    if ("getParameter".equals(arg1.getName())) {
                        String paramName = (String) arg2[0];
                        return requestParams.get(paramName);
                    }

                    if ("getParameterValues".equals(arg1.getName())) {
                        String paramName = (String) arg2[0];

                        // normalize name 'key[]' to 'key'
                        if (paramName.endsWith("[]"))
                            paramName = paramName.substring(0, paramName.length() - 2);

                        if (requestParams.containsKey(paramName))
                            return new String[] { requestParams.get(paramName) };

                        // if contains key[1], key[2]...
                        int i = 0;
                        List<String> paramValues = new ArrayList<String>();
                        while (true) {
                            String name2 = String.format("%s[%d]", paramName, i++);
                            if (requestParams.containsKey(name2)) {
                                paramValues.add(requestParams.get(name2));
                            } else {
                                break;
                            }
                        }

                        return paramValues.isEmpty() ? new String[0]
                                : paramValues.toArray(new String[paramValues.size()]);
                    }

                    return arg1.invoke(request, arg2);
                }
            });
    return (HttpServletRequest) proxyInstance;
}

From source file:edu.ucla.loni.pipeline.server.Upload.Uploaders.FileUploadServlet.java

/**
 * Handles Request to Upload File, Builds a Response
 * //from w w w.  j  a v  a2s.c o  m
 * @param req
 * @param respBuilder
 */
private void handleFileUpload(HttpServletRequest req, ResponseBuilder respBuilder) {

    // process only multipart requests
    if (ServletFileUpload.isMultipartContent(req)) {
        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload();

        try {
            // Parse the request
            FileItemIterator iter = upload.getItemIterator(req);

            while (iter.hasNext()) {
                FileItemStream item = iter.next();
                handleUploadedFile(item, respBuilder);
            }
        } catch (FileUploadException e) {
            respBuilder.appendRespMessage("The file was not uploaded successfully.");
        } catch (IOException e) {
            respBuilder.appendRespMessage("The file was not uploaded successfully.");
        }
    } else {
        respBuilder.appendRespMessage("Your form of request is not supported by this upload servlet.");
    }
}

From source file:com.pronoiahealth.olhie.server.rest.BookAssetUploadServiceImpl.java

/**
 * Receive an upload book assest//  ww w  .  j  ava 2s .  co m
 * 
 * @see com.pronoiahealth.olhie.server.rest.BookAssetUploadService#process2(javax.servlet.http.HttpServletRequest)
 */
@Override
@POST
@Path("/upload2")
@Produces("text/html")
@SecureAccess({ SecurityRoleEnum.ADMIN, SecurityRoleEnum.AUTHOR })
public String process2(@Context HttpServletRequest req)
        throws ServletException, IOException, FileUploadException {
    try {
        // Check that we have a file upload request
        boolean isMultipart = ServletFileUpload.isMultipartContent(req);
        if (isMultipart == true) {

            // FileItemFactory fileItemFactory = new FileItemFactory();
            String description = null;
            String descriptionDetail = null;
            String hoursOfWorkStr = null;
            String bookId = null;
            String action = null;
            String dataType = null;
            String contentType = null;
            //String data = null;
            byte[] bytes = null;
            String fileName = null;
            long size = 0;
            ServletFileUpload fileUpload = new ServletFileUpload();
            fileUpload.setSizeMax(FILE_SIZE_LIMIT);
            FileItemIterator iter = fileUpload.getItemIterator(req);
            while (iter.hasNext()) {
                FileItemStream item = iter.next();
                InputStream stream = item.openStream();
                if (item.isFormField()) {
                    // description
                    if (item.getFieldName().equals("description")) {
                        description = Streams.asString(stream);
                    }

                    // detail
                    if (item.getFieldName().equals("descriptionDetail")) {
                        descriptionDetail = Streams.asString(stream);
                    }

                    // Work hours
                    if (item.getFieldName().equals("hoursOfWork")) {
                        hoursOfWorkStr = Streams.asString(stream);
                    }

                    // BookId
                    if (item.getFieldName().equals("bookId")) {
                        bookId = Streams.asString(stream);
                    }

                    // action
                    if (item.getFieldName().equals("action")) {
                        action = Streams.asString(stream);
                    }

                    // datatype
                    if (item.getFieldName().equals("dataType")) {
                        dataType = Streams.asString(stream);
                    }

                } else {
                    if (item != null) {
                        contentType = item.getContentType();
                        fileName = item.getName();
                        item.openStream();
                        InputStream in = item.openStream();
                        ByteArrayOutputStream bos = new ByteArrayOutputStream();
                        IOUtils.copy(in, bos);
                        bytes = bos.toByteArray();
                        size = bytes.length;
                    }
                }
            }

            // convert the hoursOfWork
            int hoursOfWork = 0;
            if (hoursOfWorkStr != null) {
                try {
                    hoursOfWork = Integer.parseInt(hoursOfWorkStr);
                } catch (Exception e) {
                    log.log(Level.WARNING, "Could not conver " + hoursOfWorkStr
                            + " to an int in BookAssetUploadServiceImpl. Converting to 0.");
                    hoursOfWork = 0;
                }
            }

            // Verify that the session user is the author or co-author of
            // the book. They would be the only ones who could add to the
            // book.
            String userId = userToken.getUserId();
            boolean isAuthor = bookDAO.isUserAuthorOrCoauthorOfBook(userId, bookId);
            if (isAuthor == false) {
                throw new Exception("The user " + userId + " is not the author or co-author of the book.");
            }

            // Add to the database
            bookDAO.addUpdateBookassetBytes(description, descriptionDetail, bookId, contentType,
                    BookAssetDataType.valueOf(dataType).toString(), bytes, action, fileName, null, null, size,
                    hoursOfWork, userId);

            // Tell Solr about the update
            queueBookEvent.fire(new QueueBookEvent(bookId, userId));
        }
        return "OK";
    } catch (Exception e) {
        log.log(Level.SEVERE, "Throwing servlet exception for unhandled exception", e);
        // return "ERROR:\n" + e.getMessage();

        if (e instanceof FileUploadException) {
            throw (FileUploadException) e;
        } else {
            throw new FileUploadException(e.getMessage());
        }
    }
}