Search in sources :

Example 21 with ReadListener

use of javax.servlet.ReadListener in project jetty.project by eclipse.

the class HttpInput method run.

/*
     * <p> While this class is-a Runnable, it should never be dispatched in it's own thread. It is a runnable only so that the calling thread can use {@link
     * ContextHandler#handle(Runnable)} to setup classloaders etc. </p>
     */
@Override
public void run() {
    final ReadListener listener;
    Throwable error;
    boolean aeof = false;
    synchronized (_inputQ) {
        listener = _listener;
        if (_state == EOF)
            return;
        if (_state == AEOF) {
            _state = EOF;
            aeof = true;
        }
        error = _state.getError();
        if (!aeof && error == null) {
            Content content = nextInterceptedContent();
            if (content == null)
                return;
            // So -1 will never be read and only onAddDataRread or onError will be called
            if (content instanceof EofContent) {
                consume(content);
                if (_state == EARLY_EOF)
                    error = _state.getError();
                else if (_state == AEOF) {
                    aeof = true;
                    _state = EOF;
                }
            }
        }
    }
    try {
        if (error != null) {
            // TODO is this necessary to add here?
            _channelState.getHttpChannel().getResponse().getHttpFields().add(HttpConnection.CONNECTION_CLOSE);
            listener.onError(error);
        } else if (aeof) {
            listener.onAllDataRead();
        } else {
            listener.onDataAvailable();
        // If -1 was read, then HttpChannelState#onEOF will have been called and a subsequent
        // unhandle will call run again so onAllDataRead() can be called.
        }
    } catch (Throwable e) {
        LOG.warn(e.toString());
        LOG.debug(e);
        try {
            if (aeof || error == null) {
                _channelState.getHttpChannel().getResponse().getHttpFields().add(HttpConnection.CONNECTION_CLOSE);
                listener.onError(e);
            }
        } catch (Throwable e2) {
            LOG.warn(e2.toString());
            LOG.debug(e2);
            throw new RuntimeIOException(e2);
        }
    }
}
Also used : RuntimeIOException(org.eclipse.jetty.io.RuntimeIOException) ReadListener(javax.servlet.ReadListener)

Example 22 with ReadListener

use of javax.servlet.ReadListener in project portal by ixinportal.

the class GzipRequestWrapper method getInputStream.

@Override
public ServletInputStream getInputStream() throws IOException {
    ServletInputStream stream = request.getInputStream();
    String contentEncoding = request.getHeader("Content-Encoding");
    // 如果对内容进行了压缩,则解压
    if (null != contentEncoding && contentEncoding.indexOf("gzip") != -1) {
        try {
            final GZIPInputStream gzipInputStream = new GZIPInputStream(stream);
            ServletInputStream newStream = new ServletInputStream() {

                @Override
                public boolean isFinished() {
                    return false;
                }

                @Override
                public boolean isReady() {
                    return false;
                }

                @Override
                public void setReadListener(ReadListener readListener) {
                }

                @Override
                public int read() throws IOException {
                    return gzipInputStream.read();
                }
            };
            return newStream;
        } catch (Exception e) {
            LOGGER.debug("ungzip content fail.", e);
        }
    }
    return stream;
}
Also used : GZIPInputStream(java.util.zip.GZIPInputStream) ServletInputStream(javax.servlet.ServletInputStream) ReadListener(javax.servlet.ReadListener) IOException(java.io.IOException)

Example 23 with ReadListener

use of javax.servlet.ReadListener in project fabric8 by jboss-fuse.

the class MavenProxyServletSupportTest method testUpload.

private Map<String, String> testUpload(String path, final byte[] contents, String location, String profile, String version, boolean hasLocationHeader) throws Exception {
    final String old = System.getProperty("karaf.data");
    System.setProperty("karaf.data", new File("target").getCanonicalPath());
    FileUtils.deleteDirectory(new File("target/tmp"));
    Server server = new Server(0);
    server.setHandler(new AbstractHandler() {

        @Override
        public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
            response.setStatus(HttpServletResponse.SC_NO_CONTENT);
        }
    });
    server.start();
    try {
        int localPort = ((ServerConnector) server.getConnectors()[0]).getLocalPort();
        List<String> remoteRepos = Arrays.asList("http://relevant.not/maven2@id=central");
        RuntimeProperties props = new MockRuntimeProperties();
        MavenResolver resolver = createResolver("target/tmp", remoteRepos, "http", "localhost", localPort, "fuse", "fuse", null);
        MavenUploadProxyServlet servlet = new MavenUploadProxyServlet(resolver, props, projectDeployer, new File("target/upload"), 0);
        HttpServletRequest request = EasyMock.createMock(HttpServletRequest.class);
        EasyMock.expect(request.getPathInfo()).andReturn(path);
        EasyMock.expect(request.getContentType()).andReturn("text/plain").anyTimes();
        EasyMock.expect(request.getInputStream()).andReturn(new ServletInputStream() {

            private int i;

            @Override
            public int read() throws IOException {
                if (i >= contents.length) {
                    return -1;
                }
                return (contents[i++] & 0xFF);
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener readListener) {
            }
        });
        EasyMock.expect(request.getHeader("X-Location")).andReturn(location);
        EasyMock.expect(request.getParameter("profile")).andReturn(profile);
        EasyMock.expect(request.getParameter("version")).andReturn(version);
        final Map<String, String> headers = new HashMap<>();
        HttpServletResponse rm = EasyMock.createMock(HttpServletResponse.class);
        HttpServletResponse response = new HttpServletResponseWrapper(rm) {

            @Override
            public void addHeader(String name, String value) {
                headers.put(name, value);
            }
        };
        response.setStatus(EasyMock.anyInt());
        EasyMock.expectLastCall().anyTimes();
        response.setContentLength(EasyMock.anyInt());
        EasyMock.expectLastCall().anyTimes();
        response.setContentType((String) EasyMock.anyObject());
        EasyMock.expectLastCall().anyTimes();
        response.setDateHeader((String) EasyMock.anyObject(), EasyMock.anyLong());
        EasyMock.expectLastCall().anyTimes();
        response.setHeader((String) EasyMock.anyObject(), (String) EasyMock.anyObject());
        EasyMock.expectLastCall().anyTimes();
        EasyMock.replay(request, rm);
        servlet.start();
        servlet.doPut(request, response);
        EasyMock.verify(request, rm);
        Assert.assertEquals(hasLocationHeader, headers.containsKey("X-Location"));
        return headers;
    } finally {
        server.stop();
        if (old != null) {
            System.setProperty("karaf.data", old);
        }
    }
}
Also used : Server(org.eclipse.jetty.server.Server) HashMap(java.util.HashMap) Request(org.eclipse.jetty.server.Request) HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpServletResponseWrapper(javax.servlet.http.HttpServletResponseWrapper) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) ReadListener(javax.servlet.ReadListener) AbstractHandler(org.eclipse.jetty.server.handler.AbstractHandler) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) ServerConnector(org.eclipse.jetty.server.ServerConnector) ServletInputStream(javax.servlet.ServletInputStream) MavenResolver(io.fabric8.maven.MavenResolver) File(java.io.File) AbstractRuntimeProperties(io.fabric8.api.scr.AbstractRuntimeProperties) RuntimeProperties(io.fabric8.api.RuntimeProperties)

Example 24 with ReadListener

use of javax.servlet.ReadListener in project fabric8 by jboss-fuse.

the class MavenProxyServletSupportTest method testUploadWithMimeMultipartFormData.

@Test
public void testUploadWithMimeMultipartFormData() throws Exception {
    new File("target/maven/proxy/tmp/multipart").mkdirs();
    System.setProperty("karaf.data", new File("target").getCanonicalPath());
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    JarOutputStream jas = new JarOutputStream(baos);
    addEntry(jas, "META-INF/MANIFEST.MF", "Manifest-Version: 1.0\n".getBytes());
    addEntry(jas, "META-INF/maven/io.fabric8/mybundle/pom.properties", "groupId=io.fabric8\nartifactId=mybundle\nversion=1.0\n".getBytes());
    jas.close();
    byte[] jarBytes = baos.toByteArray();
    RuntimeProperties props = new MockRuntimeProperties();
    MavenResolver resolver = EasyMock.createMock(MavenResolver.class);
    MavenUploadProxyServlet servlet = new MavenUploadProxyServlet(resolver, props, projectDeployer, new File("target/upload"), 0);
    servlet.setFileItemFactory(new DiskFileItemFactory(0, new File("target/maven/proxy/tmp/multipart")));
    HttpServletRequest request = EasyMock.createMock(HttpServletRequest.class);
    HttpServletResponse response = EasyMock.createMock(HttpServletResponse.class);
    FilePart part = new FilePart("file[]", new ByteArrayPartSource("mybundle-1.0.jar", jarBytes));
    MultipartRequestEntity entity = new MultipartRequestEntity(new Part[] { part }, new HttpMethodParams());
    final ByteArrayOutputStream requestBytes = new ByteArrayOutputStream();
    entity.writeRequest(requestBytes);
    final byte[] multipartRequestBytes = requestBytes.toByteArray();
    EasyMock.expect(request.getPathInfo()).andReturn("/mybundle-1.0.jar");
    EasyMock.expect(request.getHeader(MavenProxyServletSupport.LOCATION_HEADER)).andReturn(null);
    EasyMock.expect(request.getParameter("profile")).andReturn("my");
    EasyMock.expect(request.getParameter("version")).andReturn("1.0");
    EasyMock.expect(request.getContentType()).andReturn(entity.getContentType()).anyTimes();
    EasyMock.expect(request.getHeader("Content-length")).andReturn(Long.toString(entity.getContentLength())).anyTimes();
    EasyMock.expect(request.getContentLength()).andReturn((int) entity.getContentLength()).anyTimes();
    EasyMock.expect(request.getCharacterEncoding()).andReturn("ISO-8859-1").anyTimes();
    Capture<String> location = EasyMock.newCapture(CaptureType.ALL);
    response.setStatus(HttpServletResponse.SC_ACCEPTED);
    EasyMock.expect(request.getInputStream()).andReturn(new ServletInputStream() {

        private int pos = 0;

        @Override
        public int read() throws IOException {
            return pos >= multipartRequestBytes.length ? -1 : (multipartRequestBytes[pos++] & 0xFF);
        }

        @Override
        public boolean isFinished() {
            return false;
        }

        @Override
        public boolean isReady() {
            return true;
        }

        @Override
        public void setReadListener(ReadListener readListener) {
        }
    });
    Capture<ProjectRequirements> requirementsCapture = EasyMock.newCapture(CaptureType.FIRST);
    EasyMock.expect(projectDeployer.deployProject(EasyMock.capture(requirementsCapture), EasyMock.eq(true))).andReturn(null);
    EasyMock.replay(resolver, request, response, projectDeployer);
    servlet.doPut(request, response);
    FileInputStream fis = new FileInputStream("target/upload/io.fabric8/mybundle/1.0/mybundle-1.0.jar");
    ByteArrayOutputStream storedBundleBytes = new ByteArrayOutputStream();
    IOUtils.copy(fis, storedBundleBytes);
    fis.close();
    Assert.assertArrayEquals(jarBytes, storedBundleBytes.toByteArray());
    ProjectRequirements pr = requirementsCapture.getValue();
    List<String> bundles = pr.getBundles();
    assertThat(bundles.size(), equalTo(1));
    assertThat(bundles.get(0), equalTo("mvn:io.fabric8/mybundle/1.0"));
    assertThat(pr.getProfileId(), equalTo("my"));
    assertThat(pr.getVersion(), equalTo("1.0"));
    assertThat(pr.getGroupId(), nullValue());
    assertThat(pr.getArtifactId(), nullValue());
    EasyMock.verify(resolver, request, response, projectDeployer);
}
Also used : ReadListener(javax.servlet.ReadListener) ByteArrayPartSource(org.apache.commons.httpclient.methods.multipart.ByteArrayPartSource) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletInputStream(javax.servlet.ServletInputStream) MavenResolver(io.fabric8.maven.MavenResolver) ProjectRequirements(io.fabric8.deployer.dto.ProjectRequirements) AbstractRuntimeProperties(io.fabric8.api.scr.AbstractRuntimeProperties) RuntimeProperties(io.fabric8.api.RuntimeProperties) JarOutputStream(java.util.jar.JarOutputStream) HttpServletResponse(javax.servlet.http.HttpServletResponse) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) HttpMethodParams(org.apache.commons.httpclient.params.HttpMethodParams) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) MultipartRequestEntity(org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity) FilePart(org.apache.commons.httpclient.methods.multipart.FilePart) FileInputStream(java.io.FileInputStream) File(java.io.File)

Example 25 with ReadListener

use of javax.servlet.ReadListener in project async-http-client by AsyncHttpClient.

the class ReactiveStreamsTest method setUpGlobal.

@SuppressWarnings("serial")
@BeforeClass(alwaysRun = true)
public void setUpGlobal() throws Exception {
    String path = new File(".").getAbsolutePath() + "/target";
    tomcat = new Tomcat();
    tomcat.setHostname("localhost");
    tomcat.setPort(0);
    tomcat.setBaseDir(path);
    Context ctx = tomcat.addContext("", path);
    Wrapper wrapper = Tomcat.addServlet(ctx, "webdav", new HttpServlet() {

        @Override
        public void service(HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws IOException {
            LOGGER.debug("Echo received request {} on path {}", httpRequest, httpRequest.getServletContext().getContextPath());
            if (httpRequest.getHeader("X-HEAD") != null) {
                httpResponse.setContentLength(1);
            }
            if (httpRequest.getHeader("X-ISO") != null) {
                httpResponse.setContentType(TestUtils.TEXT_HTML_CONTENT_TYPE_WITH_ISO_8859_1_CHARSET);
            } else {
                httpResponse.setContentType(TestUtils.TEXT_HTML_CONTENT_TYPE_WITH_UTF_8_CHARSET);
            }
            if (httpRequest.getMethod().equalsIgnoreCase("OPTIONS")) {
                httpResponse.addHeader("Allow", "GET,HEAD,POST,OPTIONS,TRACE");
            }
            Enumeration<String> e = httpRequest.getHeaderNames();
            String headerName;
            while (e.hasMoreElements()) {
                headerName = e.nextElement();
                if (headerName.startsWith("LockThread")) {
                    final int sleepTime = httpRequest.getIntHeader(headerName);
                    try {
                        Thread.sleep(sleepTime == -1 ? 40 : sleepTime * 1000);
                    } catch (InterruptedException ex) {
                    // 
                    }
                }
                if (headerName.startsWith("X-redirect")) {
                    httpResponse.sendRedirect(httpRequest.getHeader("X-redirect"));
                    return;
                }
                httpResponse.addHeader("X-" + headerName, httpRequest.getHeader(headerName));
            }
            String pathInfo = httpRequest.getPathInfo();
            if (pathInfo != null)
                httpResponse.addHeader("X-pathInfo", pathInfo);
            String queryString = httpRequest.getQueryString();
            if (queryString != null)
                httpResponse.addHeader("X-queryString", queryString);
            httpResponse.addHeader("X-KEEP-ALIVE", httpRequest.getRemoteAddr() + ":" + httpRequest.getRemotePort());
            Cookie[] cs = httpRequest.getCookies();
            if (cs != null) {
                for (Cookie c : cs) {
                    httpResponse.addCookie(c);
                }
            }
            Enumeration<String> i = httpRequest.getParameterNames();
            if (i.hasMoreElements()) {
                StringBuilder requestBody = new StringBuilder();
                while (i.hasMoreElements()) {
                    headerName = i.nextElement();
                    httpResponse.addHeader("X-" + headerName, httpRequest.getParameter(headerName));
                    requestBody.append(headerName);
                    requestBody.append("_");
                }
                if (requestBody.length() > 0) {
                    String body = requestBody.toString();
                    httpResponse.getOutputStream().write(body.getBytes());
                }
            }
            final AsyncContext context = httpRequest.startAsync();
            final ServletInputStream input = httpRequest.getInputStream();
            final ByteArrayOutputStream baos = new ByteArrayOutputStream();
            input.setReadListener(new ReadListener() {

                byte[] buffer = new byte[5 * 1024];

                @Override
                public void onError(Throwable t) {
                    t.printStackTrace();
                    httpResponse.setStatus(io.netty.handler.codec.http.HttpResponseStatus.INTERNAL_SERVER_ERROR.code());
                    context.complete();
                }

                @Override
                public void onDataAvailable() throws IOException {
                    int len;
                    while (input.isReady() && (len = input.read(buffer)) != -1) {
                        baos.write(buffer, 0, len);
                    }
                }

                @Override
                public void onAllDataRead() throws IOException {
                    byte[] requestBodyBytes = baos.toByteArray();
                    int total = requestBodyBytes.length;
                    httpResponse.addIntHeader("X-" + CONTENT_LENGTH, total);
                    String md5 = TestUtils.md5(requestBodyBytes, 0, total);
                    httpResponse.addHeader(CONTENT_MD5.toString(), md5);
                    httpResponse.getOutputStream().write(requestBodyBytes, 0, total);
                    context.complete();
                }
            });
        }
    });
    wrapper.setAsyncSupported(true);
    ctx.addServletMappingDecoded("/*", "webdav");
    tomcat.start();
    port1 = tomcat.getConnector().getLocalPort();
    executor = Executors.newSingleThreadExecutor();
}
Also used : AsyncContext(javax.servlet.AsyncContext) Context(org.apache.catalina.Context) Cookie(javax.servlet.http.Cookie) Wrapper(org.apache.catalina.Wrapper) Tomcat(org.apache.catalina.startup.Tomcat) HttpServlet(javax.servlet.http.HttpServlet) HttpServletResponse(javax.servlet.http.HttpServletResponse) AsyncContext(javax.servlet.AsyncContext) IOException(java.io.IOException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ReadListener(javax.servlet.ReadListener) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletInputStream(javax.servlet.ServletInputStream) File(java.io.File) BeforeClass(org.testng.annotations.BeforeClass)

Aggregations

ReadListener (javax.servlet.ReadListener)27 ServletInputStream (javax.servlet.ServletInputStream)22 HttpServletRequest (javax.servlet.http.HttpServletRequest)19 IOException (java.io.IOException)18 HttpServletResponse (javax.servlet.http.HttpServletResponse)18 ServletException (javax.servlet.ServletException)14 Test (org.junit.Test)14 AsyncContext (javax.servlet.AsyncContext)13 HttpServlet (javax.servlet.http.HttpServlet)12 InterruptedIOException (java.io.InterruptedIOException)11 UncheckedIOException (java.io.UncheckedIOException)11 CountDownLatch (java.util.concurrent.CountDownLatch)10 ContentResponse (org.eclipse.jetty.client.api.ContentResponse)9 DeferredContentProvider (org.eclipse.jetty.client.util.DeferredContentProvider)7 Matchers.containsString (org.hamcrest.Matchers.containsString)7 ByteArrayInputStream (java.io.ByteArrayInputStream)6 ServletOutputStream (javax.servlet.ServletOutputStream)5 Response (org.eclipse.jetty.client.api.Response)4 Result (org.eclipse.jetty.client.api.Result)4 BufferingResponseListener (org.eclipse.jetty.client.util.BufferingResponseListener)4