Search in sources :

Example 21 with WriteListener

use of javax.servlet.WriteListener in project knox by apache.

the class RMHaDispatchTest method testConnectivityFailover.

@Test
public void testConnectivityFailover() throws Exception {
    String serviceName = "RESOURCEMANAGER";
    HaDescriptor descriptor = HaDescriptorFactory.createDescriptor();
    descriptor.addServiceConfig(HaDescriptorFactory.createServiceConfig(serviceName, "true", "1", "1000", "2", "1000", null, null));
    HaProvider provider = new DefaultHaProvider(descriptor);
    URI uri1 = new URI("http://passive-host");
    URI uri2 = new URI("http://other-host");
    URI uri3 = new URI("http://active-host");
    ArrayList<String> urlList = new ArrayList<>();
    urlList.add(uri1.toString());
    urlList.add(uri2.toString());
    urlList.add(uri3.toString());
    provider.addHaService(serviceName, urlList);
    FilterConfig filterConfig = EasyMock.createNiceMock(FilterConfig.class);
    ServletContext servletContext = EasyMock.createNiceMock(ServletContext.class);
    EasyMock.expect(filterConfig.getServletContext()).andReturn(servletContext).anyTimes();
    EasyMock.expect(servletContext.getAttribute(HaServletContextListener.PROVIDER_ATTRIBUTE_NAME)).andReturn(provider).anyTimes();
    BasicHttpResponse inboundResponse = EasyMock.createNiceMock(BasicHttpResponse.class);
    EasyMock.expect(inboundResponse.getStatusLine()).andReturn(getStatusLine()).anyTimes();
    EasyMock.expect(inboundResponse.getEntity()).andReturn(getResponseEntity()).anyTimes();
    EasyMock.expect(inboundResponse.getFirstHeader(LOCATION)).andReturn(getFirstHeader(uri3.toString())).anyTimes();
    BasicHttpParams params = new BasicHttpParams();
    HttpUriRequest outboundRequest = EasyMock.createNiceMock(HttpRequestBase.class);
    EasyMock.expect(outboundRequest.getMethod()).andReturn("GET").anyTimes();
    EasyMock.expect(outboundRequest.getURI()).andReturn(uri1).anyTimes();
    EasyMock.expect(outboundRequest.getParams()).andReturn(params).anyTimes();
    HttpServletRequest inboundRequest = EasyMock.createNiceMock(HttpServletRequest.class);
    EasyMock.expect(inboundRequest.getRequestURL()).andReturn(new StringBuffer(uri2.toString())).once();
    EasyMock.expect(inboundRequest.getAttribute("dispatch.ha.failover.counter")).andReturn(new AtomicInteger(0)).once();
    EasyMock.expect(inboundRequest.getAttribute("dispatch.ha.failover.counter")).andReturn(new AtomicInteger(1)).once();
    HttpServletResponse outboundResponse = EasyMock.createNiceMock(HttpServletResponse.class);
    EasyMock.expect(outboundResponse.getOutputStream()).andAnswer(new IAnswer<ServletOutputStream>() {

        @Override
        public ServletOutputStream answer() throws Throwable {
            return new ServletOutputStream() {

                @Override
                public void write(int b) throws IOException {
                    throw new IOException("unreachable-host");
                }

                @Override
                public void setWriteListener(WriteListener arg0) {
                }

                @Override
                public boolean isReady() {
                    return false;
                }
            };
        }
    }).once();
    Assert.assertEquals(uri1.toString(), provider.getActiveURL(serviceName));
    EasyMock.replay(filterConfig, servletContext, inboundResponse, outboundRequest, inboundRequest, outboundResponse);
    RMHaDispatch dispatch = new RMHaDispatch();
    HttpClientBuilder builder = HttpClientBuilder.create();
    CloseableHttpClient client = builder.build();
    dispatch.setHttpClient(client);
    dispatch.setHaProvider(provider);
    dispatch.init();
    long startTime = System.currentTimeMillis();
    try {
        dispatch.setInboundResponse(inboundResponse);
        dispatch.executeRequest(outboundRequest, inboundRequest, outboundResponse);
    } catch (IOException e) {
    // this is expected after the failover limit is reached
    }
    Assert.assertEquals(uri3.toString(), dispatch.getUriFromInbound(inboundRequest, inboundResponse, null).toString());
    long elapsedTime = System.currentTimeMillis() - startTime;
    Assert.assertEquals(uri3.toString(), provider.getActiveURL(serviceName));
    // test to make sure the sleep took place
    Assert.assertTrue(elapsedTime > 1000);
}
Also used : HttpUriRequest(org.apache.http.client.methods.HttpUriRequest) DefaultHaProvider(org.apache.knox.gateway.ha.provider.impl.DefaultHaProvider) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) ServletOutputStream(javax.servlet.ServletOutputStream) ArrayList(java.util.ArrayList) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) URI(java.net.URI) HttpServletRequest(javax.servlet.http.HttpServletRequest) IAnswer(org.easymock.IAnswer) BasicHttpResponse(org.apache.http.message.BasicHttpResponse) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ServletContext(javax.servlet.ServletContext) FilterConfig(javax.servlet.FilterConfig) HaDescriptor(org.apache.knox.gateway.ha.provider.HaDescriptor) BasicHttpParams(org.apache.http.params.BasicHttpParams) WriteListener(javax.servlet.WriteListener) DefaultHaProvider(org.apache.knox.gateway.ha.provider.impl.DefaultHaProvider) HaProvider(org.apache.knox.gateway.ha.provider.HaProvider) Test(org.junit.Test)

Example 22 with WriteListener

use of javax.servlet.WriteListener in project teiid by teiid.

the class TestGzipMessageResponse method prepareResponse.

@Before
public void prepareResponse() throws IOException {
    streamBytes = new LinkedList<>();
    stream = new ServletOutputStream() {

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

        @Override
        public void setWriteListener(WriteListener writeListener) {
        }

        @Override
        public void write(int b) throws IOException {
            streamBytes.add((byte) b);
        }
    };
    response = new GzipMessageResponse(mockResponse(stream));
}
Also used : ServletOutputStream(javax.servlet.ServletOutputStream) IOException(java.io.IOException) WriteListener(javax.servlet.WriteListener) Before(org.junit.Before)

Example 23 with WriteListener

use of javax.servlet.WriteListener in project undertow by undertow-io.

the class ServletContextImpl method initDone.

public void initDone() {
    initialized = true;
    Set<SessionTrackingMode> trackingMethods = sessionTrackingModes;
    SessionConfig sessionConfig = sessionCookieConfig;
    if (trackingMethods != null && !trackingMethods.isEmpty()) {
        if (sessionTrackingModes.contains(SessionTrackingMode.SSL)) {
            sessionConfig = new SslSessionConfig(deployment.getSessionManager());
        } else {
            if (sessionTrackingModes.contains(SessionTrackingMode.COOKIE) && sessionTrackingModes.contains(SessionTrackingMode.URL)) {
                sessionCookieConfig.setFallback(new PathParameterSessionConfig(sessionCookieConfig.getName().toLowerCase(Locale.ENGLISH)));
            } else if (sessionTrackingModes.contains(SessionTrackingMode.URL)) {
                sessionConfig = new PathParameterSessionConfig(sessionCookieConfig.getName().toLowerCase(Locale.ENGLISH));
            }
        }
    }
    SessionConfigWrapper wrapper = deploymentInfo.getSessionConfigWrapper();
    if (wrapper != null) {
        sessionConfig = wrapper.wrap(sessionConfig, deployment);
    }
    this.sessionConfig = new ServletContextSessionConfig(sessionConfig);
    this.onWritePossibleTask = deployment.createThreadSetupAction(new ThreadSetupHandler.Action<Void, WriteListener>() {

        @Override
        public Void call(HttpServerExchange exchange, WriteListener context) throws Exception {
            context.onWritePossible();
            return null;
        }
    });
    this.runnableTask = deployment.createThreadSetupAction(new ThreadSetupHandler.Action<Void, Runnable>() {

        @Override
        public Void call(HttpServerExchange exchange, Runnable runnable) throws Exception {
            runnable.run();
            return null;
        }
    });
    this.onDataAvailableTask = deployment.createThreadSetupAction(new ThreadSetupHandler.Action<Void, ReadListener>() {

        @Override
        public Void call(HttpServerExchange exchange, ReadListener context) throws Exception {
            context.onDataAvailable();
            return null;
        }
    });
    this.onAllDataReadTask = deployment.createThreadSetupAction(new ThreadSetupHandler.Action<Void, ReadListener>() {

        @Override
        public Void call(HttpServerExchange exchange, ReadListener context) throws Exception {
            context.onAllDataRead();
            return null;
        }
    });
    this.invokeActionTask = deployment.createThreadSetupAction(new ThreadSetupHandler.Action<Void, ThreadSetupHandler.Action<Void, Object>>() {

        @Override
        public Void call(HttpServerExchange exchange, ThreadSetupHandler.Action<Void, Object> context) throws Exception {
            context.call(exchange, null);
            return null;
        }
    });
}
Also used : PrivilegedAction(java.security.PrivilegedAction) SessionTrackingMode(javax.servlet.SessionTrackingMode) PathParameterSessionConfig(io.undertow.server.session.PathParameterSessionConfig) SslSessionConfig(io.undertow.server.session.SslSessionConfig) PathParameterSessionConfig(io.undertow.server.session.PathParameterSessionConfig) SessionConfig(io.undertow.server.session.SessionConfig) ReadListener(javax.servlet.ReadListener) HttpServerExchange(io.undertow.server.HttpServerExchange) ThreadSetupHandler(io.undertow.servlet.api.ThreadSetupHandler) SslSessionConfig(io.undertow.server.session.SslSessionConfig) SessionConfigWrapper(io.undertow.servlet.api.SessionConfigWrapper) WriteListener(javax.servlet.WriteListener)

Example 24 with WriteListener

use of javax.servlet.WriteListener in project undertow by undertow-io.

the class AsyncOutputStreamServlet method doGet.

@Override
protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
    final boolean flush = req.getParameter("flush") != null;
    final boolean close = req.getParameter("close") != null;
    final boolean preable = req.getParameter("preamble") != null;
    final boolean offIoThread = req.getParameter("offIoThread") != null;
    final int reps = Integer.parseInt(req.getParameter("reps"));
    final AtomicInteger count = new AtomicInteger();
    final AsyncContext context = req.startAsync();
    final ServletOutputStream outputStream = resp.getOutputStream();
    if (preable) {
        for (int i = 0; i < reps; ++i) {
            outputStream.write(ServletOutputStreamTestCase.message.getBytes());
        }
    }
    WriteListener listener = new WriteListener() {

        @Override
        public synchronized void onWritePossible() throws IOException {
            while (outputStream.isReady() && count.get() < reps) {
                count.incrementAndGet();
                outputStream.write(ServletOutputStreamTestCase.message.getBytes());
            }
            if (count.get() == reps) {
                if (flush) {
                    outputStream.flush();
                }
                if (close) {
                    outputStream.close();
                }
                context.complete();
            }
        }

        @Override
        public void onError(final Throwable t) {
        }
    };
    outputStream.setWriteListener(offIoThread ? new WriteListener() {

        @Override
        public void onWritePossible() throws IOException {
            context.start(new Runnable() {

                @Override
                public void run() {
                    try {
                        listener.onWritePossible();
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
            });
        }

        @Override
        public void onError(Throwable throwable) {
        }
    } : listener);
}
Also used : AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ServletOutputStream(javax.servlet.ServletOutputStream) AsyncContext(javax.servlet.AsyncContext) IOException(java.io.IOException) WriteListener(javax.servlet.WriteListener)

Example 25 with WriteListener

use of javax.servlet.WriteListener in project undertow by undertow-io.

the class ConnectionTerminationServlet method doPost.

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    req.startAsync();
    resp.getOutputStream().print("hi");
    resp.getOutputStream().setWriteListener(new WriteListener() {

        @Override
        public void onWritePossible() throws IOException {
        }

        @Override
        public void onError(Throwable t) {
        }
    });
    ServletRequestContext.current().getExchange().getConnection().close();
}
Also used : IOException(java.io.IOException) WriteListener(javax.servlet.WriteListener)

Aggregations

WriteListener (javax.servlet.WriteListener)31 ServletOutputStream (javax.servlet.ServletOutputStream)27 IOException (java.io.IOException)22 HttpServletRequest (javax.servlet.http.HttpServletRequest)17 HttpServletResponse (javax.servlet.http.HttpServletResponse)17 AsyncContext (javax.servlet.AsyncContext)12 Test (org.junit.Test)11 ServletException (javax.servlet.ServletException)10 CountDownLatch (java.util.concurrent.CountDownLatch)8 ByteArrayOutputStream (java.io.ByteArrayOutputStream)7 HttpServlet (javax.servlet.http.HttpServlet)6 InterruptedIOException (java.io.InterruptedIOException)5 ByteBuffer (java.nio.ByteBuffer)5 ReadListener (javax.servlet.ReadListener)5 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)4 Request (org.eclipse.jetty.server.Request)4 Before (org.junit.Before)4 ByteArrayInputStream (java.io.ByteArrayInputStream)3 UncheckedIOException (java.io.UncheckedIOException)3 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)3