Search in sources :

Example 1 with MultiPartInputStreamParser

use of org.eclipse.jetty.util.MultiPartInputStreamParser in project jetty.project by eclipse.

the class RequestTest method testMultiPart.

@Test
public void testMultiPart() throws Exception {
    final File testTmpDir = File.createTempFile("reqtest", null);
    if (testTmpDir.exists())
        testTmpDir.delete();
    testTmpDir.mkdir();
    testTmpDir.deleteOnExit();
    assertTrue(testTmpDir.list().length == 0);
    ContextHandler contextHandler = new ContextHandler();
    contextHandler.setContextPath("/foo");
    contextHandler.setResourceBase(".");
    contextHandler.setHandler(new MultiPartRequestHandler(testTmpDir));
    contextHandler.addEventListener(new MultiPartCleanerListener() {

        @Override
        public void requestDestroyed(ServletRequestEvent sre) {
            MultiPartInputStreamParser m = (MultiPartInputStreamParser) sre.getServletRequest().getAttribute(Request.__MULTIPART_INPUT_STREAM);
            ContextHandler.Context c = (ContextHandler.Context) sre.getServletRequest().getAttribute(Request.__MULTIPART_CONTEXT);
            assertNotNull(m);
            assertNotNull(c);
            assertTrue(c == sre.getServletContext());
            assertTrue(!m.getParsedParts().isEmpty());
            assertTrue(testTmpDir.list().length == 2);
            super.requestDestroyed(sre);
            String[] files = testTmpDir.list();
            assertTrue(files.length == 0);
        }
    });
    _server.stop();
    _server.setHandler(contextHandler);
    _server.start();
    String multipart = "--AaB03x\r\n" + "content-disposition: form-data; name=\"field1\"\r\n" + "\r\n" + "Joe Blow\r\n" + "--AaB03x\r\n" + "content-disposition: form-data; name=\"stuff\"; filename=\"foo.upload\"\r\n" + "Content-Type: text/plain;charset=ISO-8859-1\r\n" + "\r\n" + "000000000000000000000000000000000000000000000000000\r\n" + "--AaB03x--\r\n";
    String request = "GET /foo/x.html HTTP/1.1\r\n" + "Host: whatever\r\n" + "Content-Type: multipart/form-data; boundary=\"AaB03x\"\r\n" + "Content-Length: " + multipart.getBytes().length + "\r\n" + "Connection: close\r\n" + "\r\n" + multipart;
    String responses = _connector.getResponse(request);
    // System.err.println(responses);
    assertTrue(responses.startsWith("HTTP/1.1 200"));
}
Also used : ContextHandler(org.eclipse.jetty.server.handler.ContextHandler) ServletRequestEvent(javax.servlet.ServletRequestEvent) MultiPartInputStreamParser(org.eclipse.jetty.util.MultiPartInputStreamParser) File(java.io.File) Test(org.junit.Test)

Example 2 with MultiPartInputStreamParser

use of org.eclipse.jetty.util.MultiPartInputStreamParser in project jetty.project by eclipse.

the class MultiPartFilter method deleteFiles.

/* ------------------------------------------------------------ */
private void deleteFiles(ServletRequest request) {
    if (!_deleteFiles)
        return;
    MultiPartInputStreamParser mpis = (MultiPartInputStreamParser) request.getAttribute(MULTIPART);
    if (mpis != null) {
        try {
            mpis.deleteParts();
        } catch (Exception e) {
            _context.log("Error deleting multipart tmp files", e);
        }
    }
    request.removeAttribute(MULTIPART);
}
Also used : MultiPartInputStreamParser(org.eclipse.jetty.util.MultiPartInputStreamParser) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Example 3 with MultiPartInputStreamParser

use of org.eclipse.jetty.util.MultiPartInputStreamParser in project jetty.project by eclipse.

the class RequestTest method testBadMultiPart.

@Test
public void testBadMultiPart() throws Exception {
    //a bad multipart where one of the fields has no name
    final File testTmpDir = File.createTempFile("badmptest", null);
    if (testTmpDir.exists())
        testTmpDir.delete();
    testTmpDir.mkdir();
    testTmpDir.deleteOnExit();
    assertTrue(testTmpDir.list().length == 0);
    ContextHandler contextHandler = new ContextHandler();
    contextHandler.setContextPath("/foo");
    contextHandler.setResourceBase(".");
    contextHandler.setHandler(new BadMultiPartRequestHandler(testTmpDir));
    contextHandler.addEventListener(new MultiPartCleanerListener() {

        @Override
        public void requestDestroyed(ServletRequestEvent sre) {
            MultiPartInputStreamParser m = (MultiPartInputStreamParser) sre.getServletRequest().getAttribute(Request.__MULTIPART_INPUT_STREAM);
            ContextHandler.Context c = (ContextHandler.Context) sre.getServletRequest().getAttribute(Request.__MULTIPART_CONTEXT);
            assertNotNull(m);
            assertNotNull(c);
            assertTrue(c == sre.getServletContext());
            super.requestDestroyed(sre);
            String[] files = testTmpDir.list();
            assertTrue(files.length == 0);
        }
    });
    _server.stop();
    _server.setHandler(contextHandler);
    _server.start();
    String multipart = "--AaB03x\r\n" + "content-disposition: form-data; name=\"xxx\"\r\n" + "\r\n" + "Joe Blow\r\n" + "--AaB03x\r\n" + "content-disposition: form-data;  filename=\"foo.upload\"\r\n" + "Content-Type: text/plain;charset=ISO-8859-1\r\n" + "\r\n" + "000000000000000000000000000000000000000000000000000\r\n" + "--AaB03x--\r\n";
    String request = "GET /foo/x.html HTTP/1.1\r\n" + "Host: whatever\r\n" + "Content-Type: multipart/form-data; boundary=\"AaB03x\"\r\n" + "Content-Length: " + multipart.getBytes().length + "\r\n" + "Connection: close\r\n" + "\r\n" + multipart;
    try (StacklessLogging stackless = new StacklessLogging(HttpChannel.class)) {
        String responses = _connector.getResponse(request);
        //System.err.println(responses);
        assertTrue(responses.startsWith("HTTP/1.1 500"));
    }
}
Also used : ContextHandler(org.eclipse.jetty.server.handler.ContextHandler) ServletRequestEvent(javax.servlet.ServletRequestEvent) MultiPartInputStreamParser(org.eclipse.jetty.util.MultiPartInputStreamParser) StacklessLogging(org.eclipse.jetty.util.log.StacklessLogging) File(java.io.File) Test(org.junit.Test)

Example 4 with MultiPartInputStreamParser

use of org.eclipse.jetty.util.MultiPartInputStreamParser in project jetty.project by eclipse.

the class MultiPartFilter method doFilter.

/* ------------------------------------------------------------------------------- */
/**
     * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
     *      javax.servlet.ServletResponse, javax.servlet.FilterChain)
     */
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest srequest = (HttpServletRequest) request;
    if (srequest.getContentType() == null || !srequest.getContentType().startsWith("multipart/form-data")) {
        chain.doFilter(request, response);
        return;
    }
    String content_type = srequest.getContentType();
    //Get current parameters so we can merge into them
    MultiMap params = new MultiMap();
    for (Map.Entry<String, String[]> entry : request.getParameterMap().entrySet()) {
        Object value = entry.getValue();
        if (value instanceof String[])
            params.addValues(entry.getKey(), (String[]) value);
        else
            params.add(entry.getKey(), value);
    }
    MultipartConfigElement config = new MultipartConfigElement(tempdir.getCanonicalPath(), _maxFileSize, _maxRequestSize, _fileOutputBuffer);
    MultiPartInputStreamParser mpis = new MultiPartInputStreamParser(request.getInputStream(), content_type, config, tempdir);
    mpis.setDeleteOnExit(_deleteFiles);
    mpis.setWriteFilesWithFilenames(_writeFilesWithFilenames);
    request.setAttribute(MULTIPART, mpis);
    try {
        Collection<Part> parts = mpis.getParts();
        if (parts != null) {
            Iterator<Part> itor = parts.iterator();
            while (itor.hasNext() && params.size() < _maxFormKeys) {
                Part p = itor.next();
                if (LOG.isDebugEnabled())
                    LOG.debug("{}", p);
                MultiPartInputStreamParser.MultiPart mp = (MultiPartInputStreamParser.MultiPart) p;
                if (mp.getFile() != null) {
                    request.setAttribute(mp.getName(), mp.getFile());
                    if (mp.getContentDispositionFilename() != null) {
                        params.add(mp.getName(), mp.getContentDispositionFilename());
                        if (mp.getContentType() != null)
                            params.add(mp.getName() + CONTENT_TYPE_SUFFIX, mp.getContentType());
                    }
                } else {
                    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
                    IO.copy(p.getInputStream(), bytes);
                    params.add(p.getName(), bytes.toByteArray());
                    if (p.getContentType() != null)
                        params.add(p.getName() + CONTENT_TYPE_SUFFIX, p.getContentType());
                }
            }
        }
        // handle request
        chain.doFilter(new Wrapper(srequest, params), response);
    } finally {
        deleteFiles(request);
    }
}
Also used : HttpServletRequestWrapper(javax.servlet.http.HttpServletRequestWrapper) MultiPartInputStreamParser(org.eclipse.jetty.util.MultiPartInputStreamParser) ByteArrayOutputStream(java.io.ByteArrayOutputStream) HttpServletRequest(javax.servlet.http.HttpServletRequest) MultiMap(org.eclipse.jetty.util.MultiMap) MultipartConfigElement(javax.servlet.MultipartConfigElement) Part(javax.servlet.http.Part) HashMap(java.util.HashMap) Map(java.util.Map) MultiMap(org.eclipse.jetty.util.MultiMap)

Example 5 with MultiPartInputStreamParser

use of org.eclipse.jetty.util.MultiPartInputStreamParser in project jetty.project by eclipse.

the class Request method getParts.

private Collection<Part> getParts(MultiMap<String> params) throws IOException, ServletException {
    if (_multiPartInputStream == null)
        _multiPartInputStream = (MultiPartInputStreamParser) getAttribute(__MULTIPART_INPUT_STREAM);
    if (_multiPartInputStream == null) {
        MultipartConfigElement config = (MultipartConfigElement) getAttribute(__MULTIPART_CONFIG_ELEMENT);
        if (config == null)
            throw new IllegalStateException("No multipart config for servlet");
        _multiPartInputStream = new MultiPartInputStreamParser(getInputStream(), getContentType(), config, (_context != null ? (File) _context.getAttribute("javax.servlet.context.tempdir") : null));
        setAttribute(__MULTIPART_INPUT_STREAM, _multiPartInputStream);
        setAttribute(__MULTIPART_CONTEXT, _context);
        //causes parsing
        Collection<Part> parts = _multiPartInputStream.getParts();
        ByteArrayOutputStream os = null;
        for (Part p : parts) {
            MultiPartInputStreamParser.MultiPart mp = (MultiPartInputStreamParser.MultiPart) p;
            if (mp.getContentDispositionFilename() == null) {
                // Servlet Spec 3.0 pg 23, parts without filename must be put into params.
                String charset = null;
                if (mp.getContentType() != null)
                    charset = MimeTypes.getCharsetFromContentType(mp.getContentType());
                try (InputStream is = mp.getInputStream()) {
                    if (os == null)
                        os = new ByteArrayOutputStream();
                    IO.copy(is, os);
                    String content = new String(os.toByteArray(), charset == null ? StandardCharsets.UTF_8 : Charset.forName(charset));
                    if (_contentParameters == null)
                        _contentParameters = params == null ? new MultiMap<>() : params;
                    _contentParameters.add(mp.getName(), content);
                }
                os.reset();
            }
        }
    }
    return _multiPartInputStream.getParts();
}
Also used : MultipartConfigElement(javax.servlet.MultipartConfigElement) Part(javax.servlet.http.Part) ServletInputStream(javax.servlet.ServletInputStream) InputStream(java.io.InputStream) MultiPartInputStreamParser(org.eclipse.jetty.util.MultiPartInputStreamParser) ByteArrayOutputStream(java.io.ByteArrayOutputStream) File(java.io.File)

Aggregations

MultiPartInputStreamParser (org.eclipse.jetty.util.MultiPartInputStreamParser)6 File (java.io.File)3 Part (javax.servlet.http.Part)3 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2 IOException (java.io.IOException)2 MultipartConfigElement (javax.servlet.MultipartConfigElement)2 ServletRequestEvent (javax.servlet.ServletRequestEvent)2 ContextHandler (org.eclipse.jetty.server.handler.ContextHandler)2 Test (org.junit.Test)2 InputStream (java.io.InputStream)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 UnsupportedCharsetException (java.nio.charset.UnsupportedCharsetException)1 HashMap (java.util.HashMap)1 Map (java.util.Map)1 DataSource (javax.activation.DataSource)1 ServletException (javax.servlet.ServletException)1 ServletInputStream (javax.servlet.ServletInputStream)1 HttpServletRequest (javax.servlet.http.HttpServletRequest)1 HttpServletRequestWrapper (javax.servlet.http.HttpServletRequestWrapper)1 Attachment (org.apache.camel.Attachment)1