Example usage for javax.servlet.http HttpServletRequest startAsync

List of usage examples for javax.servlet.http HttpServletRequest startAsync

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest startAsync.

Prototype

public AsyncContext startAsync() throws IllegalStateException;

Source Link

Document

Puts this request into asynchronous mode, and initializes its AsyncContext with the original (unwrapped) ServletRequest and ServletResponse objects.

Usage

From source file:com.jsmartframework.web.manager.ServletControl.java

private boolean doAsync(String path, HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    try {//from w  w w.  j ava  2  s . c om
        // Only proceed if the AsyncContext was not started to avoid looping whe dispatch is called
        if (!request.isAsyncStarted()) {
            WebAsyncListener bean = (WebAsyncListener) HANDLER.instantiateAsyncBean(path);

            if (bean != null) {
                AsyncContext asyncContext = request.startAsync();
                bean.asyncContextCreated(asyncContext);
                asyncContext.addListener(new WebServletAsyncListener(path, bean));
                return true;
            }
        }
    } catch (Exception ex) {
        LOGGER.log(Level.SEVERE,
                "AsyncBean on path [" + path + "] could not be instantiated: " + ex.getMessage());
        throw new ServletException(ex);
    }
    return false;
}

From source file:io.fabric8.maven.proxy.impl.MavenProxyServletSupportTest.java

private void testDownload(Handler serverHandler) 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(serverHandler);//  w w  w  .  ja  v a2s . c o m
    server.start();

    try {
        int localPort = server.getConnectors()[0].getLocalPort();
        List<String> remoteRepos = Arrays.asList("http://relevant.not/maven2@id=central");
        RuntimeProperties props = new MockRuntimeProperties();
        // TODO: local repo should point to target/tmp
        MavenResolver resolver = createResolver("target/tmp", remoteRepos, "http", "localhost", localPort,
                "fuse", "fuse", null);
        MavenDownloadProxyServlet servlet = new MavenDownloadProxyServlet(resolver, props, projectDeployer, 5);

        AsyncContext context = EasyMock.createMock(AsyncContext.class);

        HttpServletRequest request = EasyMock.createMock(HttpServletRequest.class);
        EasyMock.expect(request.getPathInfo())
                .andReturn("org.apache.camel/camel-core/2.13.0/camel-core-2.13.0-sources.jar");
        EasyMock.expect(request.startAsync()).andReturn(context);
        context.setTimeout(EasyMock.anyInt());
        EasyMock.expectLastCall();

        HttpServletResponse response = EasyMock.createMock(HttpServletResponse.class);
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        EasyMock.expect(response.getOutputStream()).andReturn(new ServletOutputStream() {
            @Override
            public void write(int b) throws IOException {
                baos.write(b);
            }

            @Override
            public void write(byte[] b, int off, int len) throws IOException {
                baos.write(b, off, len);
            }
        }).anyTimes();
        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();

        final CountDownLatch latch = new CountDownLatch(1);
        context.complete();
        EasyMock.expectLastCall().andAnswer(new IAnswer<Object>() {
            @Override
            public Object answer() throws Throwable {
                latch.countDown();
                return null;
            }
        });

        EasyMock.makeThreadSafe(context, true);
        EasyMock.replay(request, response, context);

        servlet.start();
        servlet.doGet(request, response);

        latch.await();

        Assert.assertArrayEquals(new byte[] { 0x42 }, baos.toByteArray());

        EasyMock.verify(request, response, context);
    } finally {
        server.stop();
        if (old != null) {
            System.setProperty("karaf.data", old);
        }
    }
}

From source file:com.kurento.kmf.content.internal.base.AbstractContentHandlerServlet.java

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

    getLogger().info("POST request received: " + req.getRequestURI());

    if (!req.isAsyncSupported()) {
        // Async context could not be created. It is not necessary to
        // complete it. Just send error message to
        ServletUtils.sendHttpError(req, resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "AsyncContext could not be started. The application should add \"asyncSupported = true\" in all "
                        + this.getClass().getName() + " instances and in all filters in the associated chain");
        return;//from ww w.j  a va  2 s  . c om
    }
    if (handler == null) {
        ServletUtils.sendHttpError(req, resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                handler.getClass().getSimpleName() + " is null. This error means that you "
                        + "need to provide a valid implementation of interface "
                        + handler.getClass().getSimpleName());
        return;
    }

    String contentId = req.getPathInfo();
    if (contentId != null) {
        contentId = contentId.substring(1);
    }

    AsyncContext asyncCtx = req.startAsync();

    // Add listener for managing error conditions
    asyncCtx.addListener(new ContentAsyncListener());

    if (useControlProtocol) {
        doRequest4JsonControlProtocol(asyncCtx, contentId, resp);
    } else {
        // TODO: we should check that the content type correspond to
        // the ones we support. We should avoid receiving application/json
        // here and send a coherent error message in that case because this
        // case corresponds to using incorrectly annotations on handlers
        doRequest4SimpleHttpProtocol(asyncCtx, contentId, resp);
    }
}

From source file:com.kurento.kmf.content.internal.base.AbstractContentHandlerServlet.java

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

    if (useControlProtocol) {
        ServletUtils.sendHttpError(req, resp, HttpServletResponse.SC_NOT_IMPLEMENTED,
                "Only POST request are supported for this service. You can enable GET requests "
                        + " by setting useControlProtocol to false on the appropriate handler annotation");
        return;/*from  w w w.j  a  va 2s.  co m*/
    }

    getLogger().info("GET request received: " + req.getRequestURI());

    if (!req.isAsyncSupported()) {
        // Async context could not be created. It is not necessary to
        // complete it. Just send error message to
        ServletUtils.sendHttpError(req, resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "AsyncContext could not be started. The application should add \"asyncSupported = true\" in all "
                        + this.getClass().getName() + " instances and in all filters in the associated chain");
        return;
    }
    if (handler == null) {
        ServletUtils.sendHttpError(req, resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                handler.getClass().getSimpleName() + " is null. This error means that you "
                        + "need to provide a valid implementation of interface "
                        + handler.getClass().getSimpleName());
        return;
    }

    String contentId = req.getPathInfo();
    if (contentId != null) {
        contentId = contentId.substring(1);
    }

    AsyncContext asyncCtx = req.startAsync();

    // Add listener for managing error conditions
    asyncCtx.addListener(new ContentAsyncListener());

    doRequest4SimpleHttpProtocol(asyncCtx, contentId, resp);

}

From source file:io.fabric8.maven.proxy.impl.MavenProxyServletSupportTest.java

@Test
public void testDownloadMetadata() 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//w  w  w  . j a va 2  s.  co  m
        public void handle(String target, Request baseRequest, HttpServletRequest request,
                HttpServletResponse response) throws IOException, ServletException {
            String result = null;
            if ("/repo1/org/apache/camel/camel-core/maven-metadata.xml".equals(target)) {
                result = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<metadata>\n"
                        + "  <groupId>org.apache.camel</groupId>\n" + "  <artifactId>camel-core</artifactId>\n"
                        + "  <versioning>\n" + "    <latest>2.14.0</latest>\n"
                        + "    <release>2.14.0</release>\n" + "    <versions>\n"
                        + "      <version>1.6.1</version>\n" + "      <version>1.6.2</version>\n"
                        + "      <version>1.6.3</version>\n" + "      <version>1.6.4</version>\n"
                        + "      <version>2.0-M2</version>\n" + "      <version>2.0-M3</version>\n"
                        + "      <version>2.0.0</version>\n" + "      <version>2.1.0</version>\n"
                        + "      <version>2.2.0</version>\n" + "      <version>2.3.0</version>\n"
                        + "      <version>2.4.0</version>\n" + "      <version>2.5.0</version>\n"
                        + "      <version>2.6.0</version>\n" + "      <version>2.7.0</version>\n"
                        + "      <version>2.7.1</version>\n" + "      <version>2.7.2</version>\n"
                        + "      <version>2.7.3</version>\n" + "      <version>2.7.4</version>\n"
                        + "      <version>2.7.5</version>\n" + "      <version>2.8.0</version>\n"
                        + "      <version>2.8.1</version>\n" + "      <version>2.8.2</version>\n"
                        + "      <version>2.8.3</version>\n" + "      <version>2.8.4</version>\n"
                        + "      <version>2.8.5</version>\n" + "      <version>2.8.6</version>\n"
                        + "      <version>2.9.0-RC1</version>\n" + "      <version>2.9.0</version>\n"
                        + "      <version>2.9.1</version>\n" + "      <version>2.9.2</version>\n"
                        + "      <version>2.9.3</version>\n" + "      <version>2.9.4</version>\n"
                        + "      <version>2.9.5</version>\n" + "      <version>2.9.6</version>\n"
                        + "      <version>2.9.7</version>\n" + "      <version>2.9.8</version>\n"
                        + "      <version>2.10.0</version>\n" + "      <version>2.10.1</version>\n"
                        + "      <version>2.10.2</version>\n" + "      <version>2.10.3</version>\n"
                        + "      <version>2.10.4</version>\n" + "      <version>2.10.5</version>\n"
                        + "      <version>2.10.6</version>\n" + "      <version>2.10.7</version>\n"
                        + "      <version>2.11.0</version>\n" + "      <version>2.11.1</version>\n"
                        + "      <version>2.11.2</version>\n" + "      <version>2.11.3</version>\n"
                        + "      <version>2.11.4</version>\n" + "      <version>2.12.0</version>\n"
                        + "      <version>2.12.1</version>\n" + "      <version>2.12.2</version>\n"
                        + "      <version>2.12.3</version>\n" + "      <version>2.12.4</version>\n"
                        + "      <version>2.13.0</version>\n" + "      <version>2.13.1</version>\n"
                        + "      <version>2.13.2</version>\n" + "      <version>2.14.0</version>\n"
                        + "    </versions>\n" + "    <lastUpdated>20140918132816</lastUpdated>\n"
                        + "  </versioning>\n" + "</metadata>\n" + "\n";
            } else if ("/repo2/org/apache/camel/camel-core/maven-metadata.xml".equals(target)) {
                result = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<metadata modelVersion=\"1.1.0\">\n"
                        + "  <groupId>org.apache.camel</groupId>\n" + "  <artifactId>camel-core</artifactId>\n"
                        + "  <versioning>\n" + "    <latest>2.14.0.redhat-620034</latest>\n"
                        + "    <release>2.14.0.redhat-620034</release>\n" + "    <versions>\n"
                        + "      <version>2.10.0.redhat-60074</version>\n"
                        + "      <version>2.12.0.redhat-610312</version>\n"
                        + "      <version>2.12.0.redhat-610328</version>\n"
                        + "      <version>2.12.0.redhat-610355</version>\n"
                        + "      <version>2.12.0.redhat-610378</version>\n"
                        + "      <version>2.12.0.redhat-610396</version>\n"
                        + "      <version>2.12.0.redhat-610399</version>\n"
                        + "      <version>2.12.0.redhat-610401</version>\n"
                        + "      <version>2.12.0.redhat-610402</version>\n"
                        + "      <version>2.12.0.redhat-611403</version>\n"
                        + "      <version>2.12.0.redhat-611405</version>\n"
                        + "      <version>2.12.0.redhat-611406</version>\n"
                        + "      <version>2.12.0.redhat-611408</version>\n"
                        + "      <version>2.12.0.redhat-611409</version>\n"
                        + "      <version>2.12.0.redhat-611410</version>\n"
                        + "      <version>2.12.0.redhat-611411</version>\n"
                        + "      <version>2.12.0.redhat-611412</version>\n"
                        + "      <version>2.14.0.redhat-620031</version>\n"
                        + "      <version>2.14.0.redhat-620033</version>\n"
                        + "      <version>2.14.0.redhat-620034</version>\n" + "    </versions>\n"
                        + "    <lastUpdated>20141019130841</lastUpdated>\n" + "  </versioning>\n"
                        + "</metadata>\n" + "\n";
            }
            if (result == null) {
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                baseRequest.setHandled(true);
                response.getOutputStream().close();
            } else {
                response.setStatus(HttpServletResponse.SC_OK);
                baseRequest.setHandled(true);
                response.getOutputStream().write(result.getBytes());
                response.getOutputStream().close();
            }
        }
    });
    server.start();

    try {
        int localPort = server.getConnectors()[0].getLocalPort();
        List<String> remoteRepos = Arrays
                .asList("http://relevant.not/repo1@id=repo1,http://relevant.not/repo2@id=repo2");
        RuntimeProperties props = new MockRuntimeProperties();
        // TODO: local repo should point to target/tmp
        MavenResolver resolver = createResolver("target/tmp", remoteRepos, "http", "localhost", localPort,
                "fuse", "fuse", null);
        MavenDownloadProxyServlet servlet = new MavenDownloadProxyServlet(resolver, props, projectDeployer, 5);

        AsyncContext context = EasyMock.createMock(AsyncContext.class);

        HttpServletRequest request = EasyMock.createMock(HttpServletRequest.class);
        EasyMock.expect(request.getPathInfo()).andReturn("org/apache/camel/camel-core/maven-metadata.xml");
        //            EasyMock.expect(request.getPathInfo()).andReturn("org/apache/camel/camel-core/LATEST/camel-core-LATEST.jar");
        EasyMock.expect(request.startAsync()).andReturn(context);
        context.setTimeout(EasyMock.anyInt());
        EasyMock.expectLastCall();

        HttpServletResponse response = EasyMock.createMock(HttpServletResponse.class);
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        EasyMock.expect(response.getOutputStream()).andReturn(new ServletOutputStream() {
            @Override
            public void write(int b) throws IOException {
                baos.write(b);
            }

            @Override
            public void write(byte[] b, int off, int len) throws IOException {
                baos.write(b, off, len);
            }
        }).anyTimes();
        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();

        final CountDownLatch latch = new CountDownLatch(1);
        context.complete();
        EasyMock.expectLastCall().andAnswer(new IAnswer<Object>() {
            @Override
            public Object answer() throws Throwable {
                latch.countDown();
                return null;
            }
        });

        EasyMock.makeThreadSafe(context, true);
        EasyMock.replay(request, response, context);

        servlet.start();
        servlet.doGet(request, response);

        latch.await();

        org.apache.maven.artifact.repository.metadata.Metadata m = new MetadataXpp3Reader()
                .read(new ByteArrayInputStream(baos.toByteArray()), false);
        assertEquals("2.14.0.redhat-620034", m.getVersioning().getLatest());
        assertTrue(m.getVersioning().getVersions().contains("2.10.4"));
        assertTrue(m.getVersioning().getVersions().contains("2.12.0.redhat-610399"));

        EasyMock.verify(request, response, context);
    } finally {
        server.stop();
        if (old != null) {
            System.setProperty("karaf.data", old);
        }
    }
}

From source file:org.apache.karaf.cave.server.maven.MavenProxyServletTest.java

@Test
public void testDownloadMetadata() 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/*from   w w w.  j a  v a 2s  . c o  m*/
        public void handle(String target, Request baseRequest, HttpServletRequest request,
                HttpServletResponse response) throws IOException, ServletException {
            String result = null;
            if ("/repo1/org/apache/camel/camel-core/maven-metadata.xml".equals(target)) {
                result = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<metadata>\n"
                        + "  <groupId>org.apache.camel</groupId>\n" + "  <artifactId>camel-core</artifactId>\n"
                        + "  <versioning>\n" + "    <latest>2.14.0</latest>\n"
                        + "    <release>2.14.0</release>\n" + "    <versions>\n"
                        + "      <version>1.6.1</version>\n" + "      <version>1.6.2</version>\n"
                        + "      <version>1.6.3</version>\n" + "      <version>1.6.4</version>\n"
                        + "      <version>2.0-M2</version>\n" + "      <version>2.0-M3</version>\n"
                        + "      <version>2.0.0</version>\n" + "      <version>2.1.0</version>\n"
                        + "      <version>2.2.0</version>\n" + "      <version>2.3.0</version>\n"
                        + "      <version>2.4.0</version>\n" + "      <version>2.5.0</version>\n"
                        + "      <version>2.6.0</version>\n" + "      <version>2.7.0</version>\n"
                        + "      <version>2.7.1</version>\n" + "      <version>2.7.2</version>\n"
                        + "      <version>2.7.3</version>\n" + "      <version>2.7.4</version>\n"
                        + "      <version>2.7.5</version>\n" + "      <version>2.8.0</version>\n"
                        + "      <version>2.8.1</version>\n" + "      <version>2.8.2</version>\n"
                        + "      <version>2.8.3</version>\n" + "      <version>2.8.4</version>\n"
                        + "      <version>2.8.5</version>\n" + "      <version>2.8.6</version>\n"
                        + "      <version>2.9.0-RC1</version>\n" + "      <version>2.9.0</version>\n"
                        + "      <version>2.9.1</version>\n" + "      <version>2.9.2</version>\n"
                        + "      <version>2.9.3</version>\n" + "      <version>2.9.4</version>\n"
                        + "      <version>2.9.5</version>\n" + "      <version>2.9.6</version>\n"
                        + "      <version>2.9.7</version>\n" + "      <version>2.9.8</version>\n"
                        + "      <version>2.10.0</version>\n" + "      <version>2.10.1</version>\n"
                        + "      <version>2.10.2</version>\n" + "      <version>2.10.3</version>\n"
                        + "      <version>2.10.4</version>\n" + "      <version>2.10.5</version>\n"
                        + "      <version>2.10.6</version>\n" + "      <version>2.10.7</version>\n"
                        + "      <version>2.11.0</version>\n" + "      <version>2.11.1</version>\n"
                        + "      <version>2.11.2</version>\n" + "      <version>2.11.3</version>\n"
                        + "      <version>2.11.4</version>\n" + "      <version>2.12.0</version>\n"
                        + "      <version>2.12.1</version>\n" + "      <version>2.12.2</version>\n"
                        + "      <version>2.12.3</version>\n" + "      <version>2.12.4</version>\n"
                        + "      <version>2.13.0</version>\n" + "      <version>2.13.1</version>\n"
                        + "      <version>2.13.2</version>\n" + "      <version>2.14.0</version>\n"
                        + "    </versions>\n" + "    <lastUpdated>20140918132816</lastUpdated>\n"
                        + "  </versioning>\n" + "</metadata>\n" + "\n";
            } else if ("/repo2/org/apache/camel/camel-core/maven-metadata.xml".equals(target)) {
                result = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<metadata modelVersion=\"1.1.0\">\n"
                        + "  <groupId>org.apache.camel</groupId>\n" + "  <artifactId>camel-core</artifactId>\n"
                        + "  <versioning>\n" + "    <latest>2.14.0.redhat-620034</latest>\n"
                        + "    <release>2.14.0.redhat-620034</release>\n" + "    <versions>\n"
                        + "      <version>2.10.0.redhat-60074</version>\n"
                        + "      <version>2.12.0.redhat-610312</version>\n"
                        + "      <version>2.12.0.redhat-610328</version>\n"
                        + "      <version>2.12.0.redhat-610355</version>\n"
                        + "      <version>2.12.0.redhat-610378</version>\n"
                        + "      <version>2.12.0.redhat-610396</version>\n"
                        + "      <version>2.12.0.redhat-610399</version>\n"
                        + "      <version>2.12.0.redhat-610401</version>\n"
                        + "      <version>2.12.0.redhat-610402</version>\n"
                        + "      <version>2.12.0.redhat-611403</version>\n"
                        + "      <version>2.12.0.redhat-611405</version>\n"
                        + "      <version>2.12.0.redhat-611406</version>\n"
                        + "      <version>2.12.0.redhat-611408</version>\n"
                        + "      <version>2.12.0.redhat-611409</version>\n"
                        + "      <version>2.12.0.redhat-611410</version>\n"
                        + "      <version>2.12.0.redhat-611411</version>\n"
                        + "      <version>2.12.0.redhat-611412</version>\n"
                        + "      <version>2.14.0.redhat-620031</version>\n"
                        + "      <version>2.14.0.redhat-620033</version>\n"
                        + "      <version>2.14.0.redhat-620034</version>\n" + "    </versions>\n"
                        + "    <lastUpdated>20141019130841</lastUpdated>\n" + "  </versioning>\n"
                        + "</metadata>\n" + "\n";
            }
            if (result == null) {
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                baseRequest.setHandled(true);
                response.getOutputStream().close();
            } else {
                response.setStatus(HttpServletResponse.SC_OK);
                baseRequest.setHandled(true);
                response.getOutputStream().write(result.getBytes());
                response.getOutputStream().close();
            }
        }
    });
    server.start();

    try {
        int localPort = ((NetworkConnector) server.getConnectors()[0]).getLocalPort();
        // TODO: local repo should point to target/tmp
        MavenResolver resolver = createResolver("target/tmp",
                "http://relevant.not/repo1@id=repo1,http://relevant.not/repo2@id=repo2", "http", "localhost",
                localPort, "fuse", "fuse", null);
        CaveMavenServlet servlet = new CaveMavenServlet(resolver, 5, null, null, null);

        AsyncContext context = EasyMock.createMock(AsyncContext.class);

        HttpServletRequest request = EasyMock.createMock(HttpServletRequest.class);
        EasyMock.expect(request.getPathInfo()).andReturn("org/apache/camel/camel-core/maven-metadata.xml");
        //            EasyMock.expect(request.getPathInfo()).andReturn("org/apache/camel/camel-core/LATEST/camel-core-LATEST.jar");
        EasyMock.expect(request.startAsync()).andReturn(context);
        context.setTimeout(EasyMock.anyInt());
        EasyMock.expectLastCall();

        HttpServletResponse response = EasyMock.createMock(HttpServletResponse.class);
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        EasyMock.expect(response.getOutputStream()).andReturn(new ServletOutputStream() {
            @Override
            public void write(int b) throws IOException {
                baos.write(b);
            }

            @Override
            public void write(byte[] b, int off, int len) throws IOException {
                baos.write(b, off, len);
            }

            @Override
            public boolean isReady() {
                // TODO Auto-generated method stub
                return true;
            }

            @Override
            public void setWriteListener(WriteListener writeListener) {
                // TODO Auto-generated method stub

            }
        }).anyTimes();
        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();

        final CountDownLatch latch = new CountDownLatch(1);
        context.complete();
        EasyMock.expectLastCall().andAnswer(new IAnswer<Object>() {
            @Override
            public Object answer() throws Throwable {
                latch.countDown();
                return null;
            }
        });

        EasyMock.makeThreadSafe(context, true);
        EasyMock.replay(request, response, context);

        servlet.init();
        servlet.doGet(request, response);

        latch.await();

        shaded.org.apache.maven.artifact.repository.metadata.Metadata m = new MetadataXpp3Reader()
                .read(new ByteArrayInputStream(baos.toByteArray()), false);
        assertEquals("2.14.0.redhat-620034", m.getVersioning().getLatest());
        assertTrue(m.getVersioning().getVersions().contains("2.10.4"));
        assertTrue(m.getVersioning().getVersions().contains("2.12.0.redhat-610399"));

        EasyMock.verify(request, response, context);
    } finally {
        server.stop();
        if (old != null) {
            System.setProperty("karaf.data", old);
        }
    }
}

From source file:org.apache.karaf.cave.server.maven.MavenProxyServletTest.java

private void testDownload(Handler serverHandler) 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(serverHandler);//from w ww.  j a v  a2s  .  c o  m
    server.start();

    try {
        int localPort = ((NetworkConnector) server.getConnectors()[0]).getLocalPort();
        // TODO: local repo should point to target/tmp
        MavenResolver resolver = createResolver("target/tmp", "http://relevant.not/maven2@id=central", "http",
                "localhost", localPort, "fuse", "fuse", null);
        CaveMavenServlet servlet = new CaveMavenServlet(resolver, 5, null, null, null);

        AsyncContext context = EasyMock.createMock(AsyncContext.class);

        HttpServletRequest request = EasyMock.createMock(HttpServletRequest.class);
        EasyMock.expect(request.getPathInfo())
                .andReturn("org.apache.camel/camel-core/2.13.0/camel-core-2.13.0-sources.jar");
        EasyMock.expect(request.startAsync()).andReturn(context);
        context.setTimeout(EasyMock.anyInt());
        EasyMock.expectLastCall();

        HttpServletResponse response = EasyMock.createMock(HttpServletResponse.class);
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        EasyMock.expect(response.getOutputStream()).andReturn(new ServletOutputStream() {
            @Override
            public void write(int b) throws IOException {
                baos.write(b);
            }

            @Override
            public void write(byte[] b, int off, int len) throws IOException {
                baos.write(b, off, len);
            }

            @Override
            public boolean isReady() {
                // TODO Auto-generated method stub
                return true;
            }

            @Override
            public void setWriteListener(WriteListener writeListener) {
                // TODO Auto-generated method stub

            }
        }).anyTimes();
        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();

        final CountDownLatch latch = new CountDownLatch(1);
        context.complete();
        EasyMock.expectLastCall().andAnswer(new IAnswer<Object>() {
            @Override
            public Object answer() throws Throwable {
                latch.countDown();
                return null;
            }
        });

        EasyMock.makeThreadSafe(context, true);
        EasyMock.replay(request, response, context);

        servlet.init();
        servlet.doGet(request, response);

        latch.await();

        Assert.assertArrayEquals(new byte[] { 0x42 }, baos.toByteArray());

        EasyMock.verify(request, response, context);
    } finally {
        server.stop();
        if (old != null) {
            System.setProperty("karaf.data", old);
        }
    }
}

From source file:org.apache.karaf.services.mavenproxy.internal.MavenProxyServletTest.java

@Test
public void testDownloadMetadata() 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//from   ww w  . j ava 2s .c om
        public void handle(String target, Request baseRequest, HttpServletRequest request,
                HttpServletResponse response) throws IOException, ServletException {
            String result = null;
            if ("/repo1/org/apache/camel/camel-core/maven-metadata.xml".equals(target)) {
                result = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<metadata>\n"
                        + "  <groupId>org.apache.camel</groupId>\n" + "  <artifactId>camel-core</artifactId>\n"
                        + "  <versioning>\n" + "    <latest>2.14.0</latest>\n"
                        + "    <release>2.14.0</release>\n" + "    <versions>\n"
                        + "      <version>1.6.1</version>\n" + "      <version>1.6.2</version>\n"
                        + "      <version>1.6.3</version>\n" + "      <version>1.6.4</version>\n"
                        + "      <version>2.0-M2</version>\n" + "      <version>2.0-M3</version>\n"
                        + "      <version>2.0.0</version>\n" + "      <version>2.1.0</version>\n"
                        + "      <version>2.2.0</version>\n" + "      <version>2.3.0</version>\n"
                        + "      <version>2.4.0</version>\n" + "      <version>2.5.0</version>\n"
                        + "      <version>2.6.0</version>\n" + "      <version>2.7.0</version>\n"
                        + "      <version>2.7.1</version>\n" + "      <version>2.7.2</version>\n"
                        + "      <version>2.7.3</version>\n" + "      <version>2.7.4</version>\n"
                        + "      <version>2.7.5</version>\n" + "      <version>2.8.0</version>\n"
                        + "      <version>2.8.1</version>\n" + "      <version>2.8.2</version>\n"
                        + "      <version>2.8.3</version>\n" + "      <version>2.8.4</version>\n"
                        + "      <version>2.8.5</version>\n" + "      <version>2.8.6</version>\n"
                        + "      <version>2.9.0-RC1</version>\n" + "      <version>2.9.0</version>\n"
                        + "      <version>2.9.1</version>\n" + "      <version>2.9.2</version>\n"
                        + "      <version>2.9.3</version>\n" + "      <version>2.9.4</version>\n"
                        + "      <version>2.9.5</version>\n" + "      <version>2.9.6</version>\n"
                        + "      <version>2.9.7</version>\n" + "      <version>2.9.8</version>\n"
                        + "      <version>2.10.0</version>\n" + "      <version>2.10.1</version>\n"
                        + "      <version>2.10.2</version>\n" + "      <version>2.10.3</version>\n"
                        + "      <version>2.10.4</version>\n" + "      <version>2.10.5</version>\n"
                        + "      <version>2.10.6</version>\n" + "      <version>2.10.7</version>\n"
                        + "      <version>2.11.0</version>\n" + "      <version>2.11.1</version>\n"
                        + "      <version>2.11.2</version>\n" + "      <version>2.11.3</version>\n"
                        + "      <version>2.11.4</version>\n" + "      <version>2.12.0</version>\n"
                        + "      <version>2.12.1</version>\n" + "      <version>2.12.2</version>\n"
                        + "      <version>2.12.3</version>\n" + "      <version>2.12.4</version>\n"
                        + "      <version>2.13.0</version>\n" + "      <version>2.13.1</version>\n"
                        + "      <version>2.13.2</version>\n" + "      <version>2.14.0</version>\n"
                        + "    </versions>\n" + "    <lastUpdated>20140918132816</lastUpdated>\n"
                        + "  </versioning>\n" + "</metadata>\n" + "\n";
            } else if ("/repo2/org/apache/camel/camel-core/maven-metadata.xml".equals(target)) {
                result = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<metadata modelVersion=\"1.1.0\">\n"
                        + "  <groupId>org.apache.camel</groupId>\n" + "  <artifactId>camel-core</artifactId>\n"
                        + "  <versioning>\n" + "    <latest>2.14.0.redhat-620034</latest>\n"
                        + "    <release>2.14.0.redhat-620034</release>\n" + "    <versions>\n"
                        + "      <version>2.10.0.redhat-60074</version>\n"
                        + "      <version>2.12.0.redhat-610312</version>\n"
                        + "      <version>2.12.0.redhat-610328</version>\n"
                        + "      <version>2.12.0.redhat-610355</version>\n"
                        + "      <version>2.12.0.redhat-610378</version>\n"
                        + "      <version>2.12.0.redhat-610396</version>\n"
                        + "      <version>2.12.0.redhat-610399</version>\n"
                        + "      <version>2.12.0.redhat-610401</version>\n"
                        + "      <version>2.12.0.redhat-610402</version>\n"
                        + "      <version>2.12.0.redhat-611403</version>\n"
                        + "      <version>2.12.0.redhat-611405</version>\n"
                        + "      <version>2.12.0.redhat-611406</version>\n"
                        + "      <version>2.12.0.redhat-611408</version>\n"
                        + "      <version>2.12.0.redhat-611409</version>\n"
                        + "      <version>2.12.0.redhat-611410</version>\n"
                        + "      <version>2.12.0.redhat-611411</version>\n"
                        + "      <version>2.12.0.redhat-611412</version>\n"
                        + "      <version>2.14.0.redhat-620031</version>\n"
                        + "      <version>2.14.0.redhat-620033</version>\n"
                        + "      <version>2.14.0.redhat-620034</version>\n" + "    </versions>\n"
                        + "    <lastUpdated>20141019130841</lastUpdated>\n" + "  </versioning>\n"
                        + "</metadata>\n" + "\n";
            }
            if (result == null) {
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                baseRequest.setHandled(true);
                response.getOutputStream().close();
            } else {
                response.setStatus(HttpServletResponse.SC_OK);
                baseRequest.setHandled(true);
                response.getOutputStream().write(result.getBytes());
                response.getOutputStream().close();
            }
        }
    });
    server.start();

    try {
        int localPort = ((NetworkConnector) server.getConnectors()[0]).getLocalPort();
        // TODO: local repo should point to target/tmp
        MavenResolver resolver = createResolver("target/tmp",
                "http://relevant.not/repo1@id=repo1,http://relevant.not/repo2@id=repo2", "http", "localhost",
                localPort, "fuse", "fuse", null);
        MavenProxyServlet servlet = new MavenProxyServlet(resolver, 5, null, null, null);

        AsyncContext context = EasyMock.createMock(AsyncContext.class);

        HttpServletRequest request = EasyMock.createMock(HttpServletRequest.class);
        EasyMock.expect(request.getPathInfo()).andReturn("org/apache/camel/camel-core/maven-metadata.xml");
        //            EasyMock.expect(request.getPathInfo()).andReturn("org/apache/camel/camel-core/LATEST/camel-core-LATEST.jar");
        EasyMock.expect(request.startAsync()).andReturn(context);
        context.setTimeout(EasyMock.anyInt());
        EasyMock.expectLastCall();

        HttpServletResponse response = EasyMock.createMock(HttpServletResponse.class);
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        EasyMock.expect(response.getOutputStream()).andReturn(new ServletOutputStream() {
            @Override
            public void write(int b) throws IOException {
                baos.write(b);
            }

            @Override
            public void write(byte[] b, int off, int len) throws IOException {
                baos.write(b, off, len);
            }
        }).anyTimes();
        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();

        final CountDownLatch latch = new CountDownLatch(1);
        context.complete();
        EasyMock.expectLastCall().andAnswer(new IAnswer<Object>() {
            @Override
            public Object answer() throws Throwable {
                latch.countDown();
                return null;
            }
        });

        EasyMock.makeThreadSafe(context, true);
        EasyMock.replay(request, response, context);

        servlet.init();
        servlet.doGet(request, response);

        latch.await();

        shaded.org.apache.maven.artifact.repository.metadata.Metadata m = new MetadataXpp3Reader()
                .read(new ByteArrayInputStream(baos.toByteArray()), false);
        assertEquals("2.14.0.redhat-620034", m.getVersioning().getLatest());
        assertTrue(m.getVersioning().getVersions().contains("2.10.4"));
        assertTrue(m.getVersioning().getVersions().contains("2.12.0.redhat-610399"));

        EasyMock.verify(request, response, context);
    } finally {
        server.stop();
        if (old != null) {
            System.setProperty("karaf.data", old);
        }
    }
}

From source file:org.apache.karaf.services.mavenproxy.internal.MavenProxyServletTest.java

private void testDownload(Handler serverHandler) 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(serverHandler);/*www  .  j a  v a 2 s  .  co  m*/
    server.start();

    try {
        int localPort = ((NetworkConnector) server.getConnectors()[0]).getLocalPort();
        // TODO: local repo should point to target/tmp
        MavenResolver resolver = createResolver("target/tmp", "http://relevant.not/maven2@id=central", "http",
                "localhost", localPort, "fuse", "fuse", null);
        MavenProxyServlet servlet = new MavenProxyServlet(resolver, 5, null, null, null);

        AsyncContext context = EasyMock.createMock(AsyncContext.class);

        HttpServletRequest request = EasyMock.createMock(HttpServletRequest.class);
        EasyMock.expect(request.getPathInfo())
                .andReturn("org.apache.camel/camel-core/2.13.0/camel-core-2.13.0-sources.jar");
        EasyMock.expect(request.startAsync()).andReturn(context);
        context.setTimeout(EasyMock.anyInt());
        EasyMock.expectLastCall();

        HttpServletResponse response = EasyMock.createMock(HttpServletResponse.class);
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        EasyMock.expect(response.getOutputStream()).andReturn(new ServletOutputStream() {
            @Override
            public void write(int b) throws IOException {
                baos.write(b);
            }

            @Override
            public void write(byte[] b, int off, int len) throws IOException {
                baos.write(b, off, len);
            }
        }).anyTimes();
        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();

        final CountDownLatch latch = new CountDownLatch(1);
        context.complete();
        EasyMock.expectLastCall().andAnswer(new IAnswer<Object>() {
            @Override
            public Object answer() throws Throwable {
                latch.countDown();
                return null;
            }
        });

        EasyMock.makeThreadSafe(context, true);
        EasyMock.replay(request, response, context);

        servlet.init();
        servlet.doGet(request, response);

        latch.await();

        Assert.assertArrayEquals(new byte[] { 0x42 }, baos.toByteArray());

        EasyMock.verify(request, response, context);
    } finally {
        server.stop();
        if (old != null) {
            System.setProperty("karaf.data", old);
        }
    }
}

From source file:org.apache.vysper.xmpp.extension.xep0124.BoshBackedSessionContext.java

/**
 * Suspends and enqueues an HTTP request to be used later when an asynchronous message needs to be sent from
 * the connection manager to the BOSH client.
 * //from ww w . j a  va 2  s .  c o  m
 * @param req the HTTP request
 */
public void insertRequest(final BoshRequest br) {

    final Stanza boshOuterBody = br.getBody();
    final Long rid = br.getRid();
    LOGGER.debug("SID = " + getSessionId() + " - rid = {} - inserting new BOSH request", rid);

    // reset the inactivity
    currentInactivitySeconds = inactivitySeconds;

    final HttpServletRequest request = br.getHttpServletRequest();
    request.setAttribute(BOSH_REQUEST_ATTRIBUTE, br);
    final AsyncContext context = request.startAsync();
    addContinuationExpirationListener(context);
    context.setTimeout(this.wait * 1000);

    // allow two more parallel request, be generous in what you receive
    final int maxToleratedParallelRequests = parallelRequestsCount + 2;
    synchronized (requestsWindow) {

        // only allow 'parallelRequestsCount' request to be queued
        final long highestContinuousRid = requestsWindow.getHighestContinuousRid();
        if (highestContinuousRid != -1 && rid > highestContinuousRid + maxToleratedParallelRequests) {
            LOGGER.warn(
                    "SID = " + getSessionId()
                            + " - rid = {} - received RID >= the permitted window of concurrent requests ({})",
                    rid, highestContinuousRid);
            // don't queue // queueRequest(br);
            sendError(br, "item-not-found");
            return;
        }

        // resend missed responses
        final boolean resend = rid <= requestsWindow.getCurrentProcessingRequest();
        if (resend) {
            // OLD: if (highestContinuousRid != null && rid <= highestContinuousRid) {                
            synchronized (sentResponses) {
                if (LOGGER.isInfoEnabled()) {
                    final String pendingRids = requestsWindow.logRequestWindow();
                    final String sentRids = logSentResponsesBuffer();
                    LOGGER.info("SID = " + getSessionId()
                            + " - rid = {} - resend request. sent buffer: {} - req.win.: " + pendingRids, rid,
                            sentRids);
                }
                if (sentResponses.containsKey(rid)) {
                    LOGGER.info("SID = " + getSessionId() + " - rid = {} (re-sending)", rid);
                    // Resending the old response
                    resendResponse(br);
                } else {
                    // not in sent responses, try alternatives: backlog and requestWindow

                    final BoshResponse response = sentResponsesBacklog.lookup(rid);
                    if (response != null) {
                        LOGGER.warn(
                                "SID = " + getSessionId()
                                        + " - rid = {} - BOSH response retrieved from sentResponsesBacklog",
                                rid);
                        resendResponse(br, rid, response);
                        return; // no error
                    }

                    // rid not in sent responses, nor backlog. check to see if rid is still in requests window
                    boolean inRequestsWindow = requestsWindow.containsRid(rid);
                    if (!inRequestsWindow) {
                        if (LOGGER.isWarnEnabled()) {
                            final String sentRids = logSentResponsesBuffer();
                            LOGGER.warn(
                                    "SID = " + getSessionId()
                                            + " - rid = {} - BOSH response not in buffer error - " + sentRids,
                                    rid);
                        }
                    } else {
                        if (LOGGER.isWarnEnabled()) {
                            final String sentRids = logSentResponsesBuffer();
                            LOGGER.warn("SID = " + getSessionId()
                                    + " - rid = {} - BOSH response still in requests window - " + sentRids,
                                    rid);
                        }
                    }
                    sendError(br, "item-not-found");
                }
            }
            return;
        }
        // check for too many parallel requests
        final boolean terminate = "terminate".equals(boshOuterBody.getAttributeValue("type"));
        final boolean pause = boshOuterBody.getAttributeValue("pause") != null;
        final boolean bodyIsEmpty = boshOuterBody.getInnerElements().isEmpty();
        final int distinctRIDs = requestsWindow.getDistinctRIDs();

        if (distinctRIDs >= maxToleratedParallelRequests && !terminate && !pause) {
            LOGGER.warn("SID = " + getSessionId()
                    + " - rid = {} - BOSH Overactivity: Too many simultaneous requests, max = {} "
                    + logRIDSequence(), rid, maxToleratedParallelRequests);
            sendError(br, "policy-violation");
            return;
        }
        // check for new request comes early
        if (distinctRIDs + 1 == maxToleratedParallelRequests && !terminate && !pause && bodyIsEmpty) {
            final long millisSinceLastCalls = Math
                    .abs(br.getTimestamp() - requestsWindow.getLatestAddionTimestamp());
            if (millisSinceLastCalls < pollingSeconds * 1000 && !rid.equals(requestsWindow.getLatestRID())) {
                LOGGER.warn("SID = " + getSessionId()
                        + " - rid = {} - BOSH Overactivity: Too frequent requests, millis since requests = {}, "
                        + logRIDSequence(), rid, millisSinceLastCalls);
                sendError(br, "policy-violation");
                return;
            }
        }
        // check 
        if ((wait == 0 || hold == 0) && bodyIsEmpty) {
            final long millisBetweenEmptyReqs = Math
                    .abs(br.getTimestamp() - latestEmptyPollingRequestTimestamp);
            if (millisBetweenEmptyReqs < pollingSeconds * 1000 && !rid.equals(requestsWindow.getLatestRID())) {
                LOGGER.warn("SID = " + getSessionId()
                        + " - rid = {} - BOSH Overactivity for polling: Too frequent requests, millis since requests = {}, "
                        + logRIDSequence(), rid, millisBetweenEmptyReqs);
                sendError(br, "policy-violation");
                return;
            }
            latestEmptyPollingRequestTimestamp = br.getTimestamp();
        }

        queueRequest(br);
    }

    if (isClientAcknowledgements()) {
        synchronized (sentResponses) {
            if (boshOuterBody.getAttribute("ack") == null) {
                // if there is no ack attribute present then the client confirmed it received all the responses to all the previous requests
                // and we clear the cache
                sentResponsesBacklog.addAll(sentResponses);
                sentResponses.clear();
            } else if (!sentResponses.isEmpty()) {
                // After receiving a request with an 'ack' value less than the 'rid' of the last request that it has already responded to,
                // the connection manager MAY inform the client of the situation. In this case it SHOULD include a 'report' attribute set
                // to one greater than the 'ack' attribute it received from the client, and a 'time' attribute set to the number of milliseconds
                // since it sent the response associated with the 'report' attribute.
                long ack = Long.parseLong(boshOuterBody.getAttributeValue("ack"));
                if (ack < sentResponses.lastKey() && sentResponses.containsKey(ack + 1)) {
                    long delta = System.currentTimeMillis() - sentResponses.get(ack + 1).getTimestamp();
                    if (delta >= brokenConnectionReportTimeoutMillis) {
                        sendBrokenConnectionReport(ack + 1, delta);
                        return;
                    }
                }
            }
        }
    }

    // we cannot pause if there are missing requests, this is tested with
    // br.getRid().equals(requestsWindow.lastKey()) && highestContinuousRid.equals(br.getRid())
    synchronized (requestsWindow) {
        final String pauseAttribute = boshOuterBody.getAttributeValue("pause");
        if (pauseAttribute != null && rid.equals(requestsWindow.getLatestRID())
                && rid.equals(requestsWindow.getHighestContinuousRid())) {
            int pause;
            try {
                pause = Integer.parseInt(pauseAttribute);
            } catch (NumberFormatException e) {
                queueRequest(br);
                sendError("bad-request");
                return;
            }
            pause = Math.max(0, pause);
            pause = Math.min(pause, maxpauseSeconds);
            respondToPause(pause);
            return;
        }
    }

    // If there are delayed responses waiting to be sent to the BOSH client, then we wrap them all in
    // a <body/> element and send them as a HTTP response to the current HTTP request.
    Stanza delayedResponse;
    ArrayList<Stanza> mergeCandidates = null; // do not create until there is a delayed response
    while ((delayedResponse = delayedResponseQueue.poll()) != null) {
        if (mergeCandidates == null)
            mergeCandidates = new ArrayList<Stanza>();
        mergeCandidates.add(delayedResponse);
    }
    Stanza mergedResponse = BoshStanzaUtils.mergeResponses(mergeCandidates);
    if (mergedResponse != null) {
        LOGGER.debug("SID = " + getSessionId() + " - writing merged response. stanzas merged = "
                + mergeCandidates.size());
        writeBoshResponse(mergedResponse);
        return;
    }

    // If there are more suspended enqueued requests than it is allowed by the BOSH 'hold' parameter,
    // than we release the oldest one by sending an empty response.
    if (requestsWindow.size() > hold) {
        writeBoshResponse(BoshStanzaUtils.EMPTY_BOSH_RESPONSE);
    }
}