Example usage for javax.servlet AsyncContext complete

List of usage examples for javax.servlet AsyncContext complete

Introduction

In this page you can find the example usage for javax.servlet AsyncContext complete.

Prototype

public void complete();

Source Link

Document

Completes the asynchronous operation that was started on the request that was used to initialze this AsyncContext, closing the response that was used to initialize this AsyncContext.

Usage

From source file:com.ibm.amc.feedback.FeedbackHandler.java

public void handleRequest(final HttpServletRequest request, final HttpServletResponse response) {
    if (logger.isEntryEnabled())
        logger.entry("handleRequest", request, response);

    final String user = request.getRemoteUser();
    final Queue<ActionStatusResponse> statuses = getActionStatuses(user);
    if (statuses.isEmpty()) {
        // No updates pending - register listener
        final AsyncContext asyncContext = request.startAsync(request, response);
        asyncContext.setTimeout(900000000L);
        logger.debug("handleRequest", "Registering new listener for user " + user);
        synchronized (feedbackListeners) {
            Set<AsyncContext> contexts = feedbackListeners.get(user);
            if (contexts == null) {
                contexts = new HashSet<AsyncContext>();
                feedbackListeners.put(user, contexts);
            }/*from ww w.  j av  a2s  .  co m*/
            contexts.add(asyncContext);
        }

        // Timeout listener
        executor.schedule(new Runnable() {

            @Override
            public void run() {
                synchronized (feedbackListeners) {
                    final Set<AsyncContext> contexts = feedbackListeners.get(user);
                    if (contexts.remove(asyncContext)) {
                        if (logger.isDebugEnabled())
                            logger.debug("handleRequest$Runnable.run", "Timing out listener for user " + user);
                        writeResponse(asyncContext.getResponse(), new LinkedList<ActionStatusResponse>());
                        asyncContext.complete();
                        if (contexts.isEmpty())
                            feedbackListeners.remove(user);
                    }
                }
            }

        }, POLLING_TIMEOUT, TimeUnit.SECONDS);
    } else {
        // Update pending - send response immediately
        writeResponse(response, statuses);
    }

    if (logger.isEntryEnabled())
        logger.exit("handleRequest");
}

From source file:com.kolich.havalo.controllers.api.ObjectApi.java

@RequestMapping(methods = GET, value = "/api/object/{key}", matcher = AntPathMatcher.class, filters = HavaloAuthenticationFilter.class)
public final void get(final ObjectKey key, final KeyPair userKp, final HttpServletResponse response,
        final AsyncContext context) throws Exception {
    final Repository repo = getRepository(userKp.getKey());
    new ReentrantReadWriteEntityLock<Void>(repo) {
        @Override// w ww  . j  a  va2  s.c o  m
        public Void transaction() throws Exception {
            final HashedFileObject hfo = getHashedFileObject(repo,
                    // The URL-decoded key of the object to delete.
                    key,
                    // Fail if not found.
                    true);
            new ReentrantReadWriteEntityLock<HashedFileObject>(hfo) {
                @Override
                public HashedFileObject transaction() throws Exception {
                    final DiskObject object = getCanonicalObject(repo, hfo);
                    // Validate that the object file exists on disk
                    // before we attempt to load it.
                    if (!object.getFile().exists()) {
                        throw new ObjectNotFoundException("Failed " + "to find canonical object on disk "
                                + "(key=" + key + ", file=" + object.getFile().getAbsolutePath() + ")");
                    }
                    streamHeaders(object, hfo, response);
                    streamObject(object, response);
                    return hfo;
                }
            }.read(); // Shared read lock on file object, wait
            return null;
        }

        @Override
        public void success(final Void v) throws Exception {
            context.complete();
        }
    }.read(false); // Shared read lock on repo, no wait
}

From source file:com.kolich.curacao.examples.controllers.StreamedChunkedResponseController.java

@RequestMapping("^\\/api\\/chunked$")
public final void streamChunked(final AsyncContext context, final HttpServletResponse response) {
    // Tell the Servlet container the request was successful
    // and that the client/browser should expect some chunked
    // plain text data back.
    response.setStatus(SC_OK);//from  ww w .j  av a 2  s .  co  m
    response.setContentType(PLAIN_TEXT_UTF_8.toString());
    // Grab a new writer, actually OutputStreamWriter, and write
    // the chunked data to the output stream.
    try (final Writer writer = new OutputStreamWriter(response.getOutputStream(), UTF_8.toString())) {
        // It's unclear why this is important, but in order for the
        // browser to show the data chunks "streamed in" from the
        // server side (this Servlet) as they are delivered, we
        // have to send 2KB of empty characters (spaces) first and
        // then the browser will automatically refresh/update the
        // page as bytes are delivered.  If this is omitted, then
        // the browser will wait for all bytes to be delivered in
        // the chunked response before it attempts to "render"
        // something visible to the user.  Seems like this might
        // have something to do with the "server side buffer" that
        // needs flushing before the browser will show anything:
        // http://stackoverflow.com/q/13565952
        writer.write(CHUNKED_RESPONSE_PADDING);
        writer.write(LINE_SEPARATOR_UNIX);
        // For X in N, send some data followed by a new line and
        // then flush the stream.
        for (int i = 1; i <= CHUNKS_TO_SEND; i++) {
            writer.write(String.format("Chunk %d of %d: ", i, CHUNKS_TO_SEND));
            writer.write(new Date().toString() + LINE_SEPARATOR_UNIX);
            writer.flush();
            // Wait for almost a second to simulate "work" going
            // on behind the scenes that's actually streaming down bytes.
            Thread.sleep(700L);
        }
    } catch (Exception e) {
        logger__.warn("Unexpected exception occurred while sending " + "data to client.", e);
    } finally {
        context.complete();
    }
}

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);/*from   w w  w  .  j  a  va2s.  co 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: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/*from   w  w w .ja va 2 s . 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 = 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//  w  w  w  .  j a  v  a 2  s . 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);/*  ww  w.j av 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  w w w .j  a  v a  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 = ((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);/*from w w w .  ja v a 2s. 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.nifi.processors.standard.HandleHttpRequest.java

private synchronized void initializeServer(final ProcessContext context) throws Exception {
    if (initialized.get()) {
        return;/*  w  w w . jav a2 s.  c  om*/
    }
    this.containerQueue = new LinkedBlockingQueue<>(context.getProperty(CONTAINER_QUEUE_SIZE).asInteger());
    final String host = context.getProperty(HOSTNAME).getValue();
    final int port = context.getProperty(PORT).asInteger();
    final SSLContextService sslService = context.getProperty(SSL_CONTEXT)
            .asControllerService(SSLContextService.class);

    final String clientAuthValue = context.getProperty(CLIENT_AUTH).getValue();
    final boolean need;
    final boolean want;
    if (CLIENT_NEED.equals(clientAuthValue)) {
        need = true;
        want = false;
    } else if (CLIENT_WANT.equals(clientAuthValue)) {
        need = false;
        want = true;
    } else {
        need = false;
        want = false;
    }

    final SslContextFactory sslFactory = (sslService == null) ? null : createSslFactory(sslService, need, want);
    final Server server = new Server(port);

    // create the http configuration
    final HttpConfiguration httpConfiguration = new HttpConfiguration();
    if (sslFactory == null) {
        // create the connector
        final ServerConnector http = new ServerConnector(server, new HttpConnectionFactory(httpConfiguration));

        // set host and port
        if (StringUtils.isNotBlank(host)) {
            http.setHost(host);
        }
        http.setPort(port);

        // add this connector
        server.setConnectors(new Connector[] { http });
    } else {
        // add some secure config
        final HttpConfiguration httpsConfiguration = new HttpConfiguration(httpConfiguration);
        httpsConfiguration.setSecureScheme("https");
        httpsConfiguration.setSecurePort(port);
        httpsConfiguration.addCustomizer(new SecureRequestCustomizer());

        // build the connector
        final ServerConnector https = new ServerConnector(server,
                new SslConnectionFactory(sslFactory, "http/1.1"),
                new HttpConnectionFactory(httpsConfiguration));

        // set host and port
        if (StringUtils.isNotBlank(host)) {
            https.setHost(host);
        }
        https.setPort(port);

        // add this connector
        server.setConnectors(new Connector[] { https });
    }

    final Set<String> allowedMethods = new HashSet<>();
    if (context.getProperty(ALLOW_GET).asBoolean()) {
        allowedMethods.add("GET");
    }
    if (context.getProperty(ALLOW_POST).asBoolean()) {
        allowedMethods.add("POST");
    }
    if (context.getProperty(ALLOW_PUT).asBoolean()) {
        allowedMethods.add("PUT");
    }
    if (context.getProperty(ALLOW_DELETE).asBoolean()) {
        allowedMethods.add("DELETE");
    }
    if (context.getProperty(ALLOW_HEAD).asBoolean()) {
        allowedMethods.add("HEAD");
    }
    if (context.getProperty(ALLOW_OPTIONS).asBoolean()) {
        allowedMethods.add("OPTIONS");
    }

    final String additionalMethods = context.getProperty(ADDITIONAL_METHODS).getValue();
    if (additionalMethods != null) {
        for (final String additionalMethod : additionalMethods.split(",")) {
            final String trimmed = additionalMethod.trim();
            if (!trimmed.isEmpty()) {
                allowedMethods.add(trimmed.toUpperCase());
            }
        }
    }

    final String pathRegex = context.getProperty(PATH_REGEX).getValue();
    final Pattern pathPattern = (pathRegex == null) ? null : Pattern.compile(pathRegex);

    server.setHandler(new AbstractHandler() {
        @Override
        public void handle(final String target, final Request baseRequest, final HttpServletRequest request,
                final HttpServletResponse response) throws IOException, ServletException {

            final String requestUri = request.getRequestURI();
            if (!allowedMethods.contains(request.getMethod().toUpperCase())) {
                getLogger().info(
                        "Sending back METHOD_NOT_ALLOWED response to {}; method was {}; request URI was {}",
                        new Object[] { request.getRemoteAddr(), request.getMethod(), requestUri });
                response.sendError(Status.METHOD_NOT_ALLOWED.getStatusCode());
                return;
            }

            if (pathPattern != null) {
                final URI uri;
                try {
                    uri = new URI(requestUri);
                } catch (final URISyntaxException e) {
                    throw new ServletException(e);
                }

                if (!pathPattern.matcher(uri.getPath()).matches()) {
                    response.sendError(Status.NOT_FOUND.getStatusCode());
                    getLogger().info("Sending back NOT_FOUND response to {}; request was {} {}",
                            new Object[] { request.getRemoteAddr(), request.getMethod(), requestUri });
                    return;
                }
            }

            // If destination queues full, send back a 503: Service Unavailable.
            if (context.getAvailableRelationships().isEmpty()) {
                response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
                return;
            }

            // Right now, that information, though, is only in the ProcessSession, not the ProcessContext,
            // so it is not known to us. Should see if it can be added to the ProcessContext.
            final AsyncContext async = baseRequest.startAsync();
            async.setTimeout(Long.MAX_VALUE); // timeout is handled by HttpContextMap
            final boolean added = containerQueue.offer(new HttpRequestContainer(request, response, async));

            if (added) {
                getLogger().debug("Added Http Request to queue for {} {} from {}",
                        new Object[] { request.getMethod(), requestUri, request.getRemoteAddr() });
            } else {
                getLogger().info("Sending back a SERVICE_UNAVAILABLE response to {}; request was {} {}",
                        new Object[] { request.getRemoteAddr(), request.getMethod(), request.getRemoteAddr() });

                response.sendError(Status.SERVICE_UNAVAILABLE.getStatusCode());
                response.flushBuffer();
                async.complete();
            }
        }
    });

    this.server = server;
    server.start();

    getLogger().info("Server started and listening on port " + getPort());

    initialized.set(true);
}