Example usage for org.apache.http.protocol HttpRequestHandler HttpRequestHandler

List of usage examples for org.apache.http.protocol HttpRequestHandler HttpRequestHandler

Introduction

In this page you can find the example usage for org.apache.http.protocol HttpRequestHandler HttpRequestHandler.

Prototype

HttpRequestHandler

Source Link

Usage

From source file:se.vgregion.pubsub.push.impl.DefaultPushSubscriberPublishTest.java

@Test
public void publish() throws Exception {

    subscriber = new DefaultPushSubscriber(UnitTestConstants.TOPIC, buildTestUrl("/"), UnitTestConstants.FUTURE,
            UnitTestConstants.UPDATED1, 100, "verify", UnitTestConstants.SECRET, true);

    final LinkedBlockingQueue<HttpRequest> issuedRequests = new LinkedBlockingQueue<HttpRequest>();
    final LinkedBlockingQueue<byte[]> issuedRequestBodies = new LinkedBlockingQueue<byte[]>();
    server.register("/*", new HttpRequestHandler() {
        @Override//from   www . ja va 2  s. c  o  m
        public void handle(HttpRequest request, HttpResponse response, HttpContext context)
                throws HttpException, IOException {
            issuedRequests.add(request);

            HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
            entity.writeTo(buffer);
            issuedRequestBodies.add(buffer.toByteArray());
        }
    });

    Feed feed = new FeedBuilder(ContentType.ATOM).id("e1")
            .entry(new EntryBuilder().id("f1").updated(new DateTime()).build())
            .entry(new EntryBuilder().id("f2").updated(UnitTestConstants.UPDATED1.minusHours(1)).build())
            .build();

    subscriber.publish(feed, null);

    // subscriber should be updated
    Assert.assertEquals(new DateTime(), subscriber.getLastUpdated());

    HttpRequest request = issuedRequests.poll(10000, TimeUnit.MILLISECONDS);
    Assert.assertNotNull(request);
    Assert.assertEquals(ContentType.ATOM.toString(), request.getFirstHeader("Content-Type").getValue());

    // verify HMAC header
    Assert.assertEquals("sha1=1356b52665408a17af46803a7988e48d40d1fb75",
            request.getFirstHeader("X-Hub-Signature").getValue());

    // verify content
    Assert.assertTrue(request instanceof HttpEntityEnclosingRequest);

    HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();

    Assert.assertNotNull(entity);

    Document actualAtom = new Builder().build(new ByteArrayInputStream(issuedRequestBodies.poll()));

    Assert.assertEquals(1, actualAtom.getRootElement().getChildElements("entry", Namespaces.ATOM).size());

}

From source file:nl.surfnet.sab.HttpClientTransportTest.java

@Test
public void testAuthorizationHeader() throws IOException {
    URI authUri = URI.create("http:/" + server.getServiceAddress().toString() + "/authorization");
    HttpClientTransport transport = new HttpClientTransport(credentials, credentials, authUri, authUri);

    server.register("/authorization", new HttpRequestHandler() {
        @Override//from  w  w w. j a  va  2s . c  o  m
        public void handle(HttpRequest request, HttpResponse response, HttpContext context)
                throws HttpException, IOException {

            String expectedAuthHeader = "Basic "
                    + new String(Base64.encodeBase64("theuser:thepass".getBytes()));
            if (request.getFirstHeader("Authorization") == null
                    || !expectedAuthHeader.equals(request.getFirstHeader("Authorization").getValue())) {
                String msg = "Authorization header is not set (correctly): "
                        + request.getFirstHeader("Authorization").getValue();
                LOG.error(msg);
                throw new IOException(msg);
            }
            response.setEntity(new StringEntity("Authorized!"));
            response.setStatusCode(200);
        }
    });

    String response = IOUtils.toString(transport.getResponse("foobarRequest"));
    assertEquals("Authorized!", response);
}

From source file:org.apromore.plugin.deployment.yawl.YAWLEngineClientUnitTest.java

@Test
public void testConnectToYAWL() throws DeploymentException {
    server.register("/yawl/*", new HttpRequestHandler() {

        @Override//www .  j a  va  2 s . co m
        public void handle(final HttpRequest request, final HttpResponse response, final HttpContext context)
                throws HttpException, IOException {
            String str = EntityUtils.toString(((HttpEntityEnclosingRequest) request).getEntity());
            if (str.contains("action=connect")) {
                if (str.contains("userID=test") && str.contains("password=qUqP5cyxm6YcTAhz05Hph5gvu9M%3D")) {
                    response.setEntity(new StringEntity("<response>test</response>", "UTF-8"));
                } else {
                    response.setStatusCode(500);
                }
            } else {
                response.setStatusCode(500);
            }
        }

    });
    assertNotNull(yawlEngineClient.connectToYAWL());
}

From source file:org.apromore.plugin.deployment.yawl.YAWLDeploymentPluginUnitTest.java

@Test
public void testDeployProcessCanonicalProcessType()
        throws IOException, JAXBException, SAXException, PluginException {
    server.register("/yawl/*", new HttpRequestHandler() {

        @Override// w ww  .j a v a  2 s.c  om
        public void handle(final HttpRequest request, final HttpResponse response, final HttpContext context)
                throws HttpException, IOException {
            String str = EntityUtils.toString(((HttpEntityEnclosingRequest) request).getEntity());
            if (str.contains("action=connect")) {
                if (str.contains("userID=admin") && str.contains("password=Se4tMaQCi9gr0Q2usp7P56Sk5vM%3D")) {
                    response.setEntity(
                            new StringEntity("<response>" + TESTSESSIONHANDLE + "</response>", "UTF-8"));
                } else {
                    response.setStatusCode(500);
                }
            } else if (str.contains("action=upload")) {
                if (str.contains("sessionHandle=" + TESTSESSIONHANDLE) && str.contains("specXML=")) {
                    response.setEntity(new StringEntity("<response>test</response>", "UTF-8"));
                } else {
                    response.setStatusCode(500);
                }
            } else {
                response.setStatusCode(500);
            }
        }

    });
    try (BufferedInputStream cpfInputStream = new BufferedInputStream(
            new FileInputStream("src/test/resources/SimpleMakeTripProcess.yawl.cpf"))) {
        CanonicalProcessType cpf = CPFSchema.unmarshalCanonicalFormat(cpfInputStream, true).getValue();
        PluginRequestImpl request = new PluginRequestImpl();
        request.addRequestProperty(new RequestParameterType<String>("yawlEngineUrl",
                "http://localhost:" + server.getServiceAddress().getPort() + "/yawl/ia"));
        request.addRequestProperty(new RequestParameterType<String>("yawlEngineUsername", "admin"));
        request.addRequestProperty(new RequestParameterType<String>("yawlEnginePassword", "YAWL"));
        request.addRequestProperty(new RequestParameterType<Boolean>("doAutoLaunch", true));
        PluginResult result = deploymentPlugin.deployProcess(cpf, request);
        assertEquals(1, result.getPluginMessage().size());
        assertEquals("YAWL Engine message: test", result.getPluginMessage().get(0).getMessage());
    }
}

From source file:se.vgregion.pubsub.push.impl.DefaultFeedRetrieverTest.java

/**
 * Fragments should only be used during retrievel and stripped before publication
 */// w  ww.ja v a  2 s  .c o m
@Test
public void retrievalWithFragment() throws Exception {
    final BlockingQueue<String> paths = new LinkedBlockingQueue<String>();

    server.register("/*", new HttpRequestHandler() {
        @Override
        public void handle(HttpRequest request, HttpResponse response, HttpContext context)
                throws HttpException, IOException {
            paths.add(request.getRequestLine().getUri());
            response.setEntity(testEntity);
        }
    });

    String retrivalPath = "/test#foo";
    URI publicationUrl = buildTestUrl("/test");
    URI url = buildTestUrl(retrivalPath);

    retriever.retrieve(url);

    String path = paths.poll(2000, TimeUnit.MILLISECONDS);

    // retrived URI must contain fragment
    Assert.assertEquals(retrivalPath, path);

    ArgumentCaptor<Feed> publishedFeed = ArgumentCaptor.forClass(Feed.class);

    // published URI must no contain fragment
    Mockito.verify(pushSubscriberManager).publish(Mockito.eq(publicationUrl), publishedFeed.capture());

    Assert.assertEquals("f1", publishedFeed.getValue().getFeedId());
}

From source file:org.whitesource.agent.client.WssServiceClientTest.java

@Test
public void testUpdateRequestSentOk() {
    final Collection<AgentProjectInfo> projects = new ArrayList<AgentProjectInfo>();
    final AgentProjectInfo projectInfo = new AgentProjectInfo();
    projectInfo.setProjectToken("projectToken");
    projectInfo.setCoordinates(new Coordinates("groupId", "artifactId", "version"));
    projectInfo.setParentCoordinates(new Coordinates("groupId", "parent-artifactId", "version"));
    final DependencyInfo dependencyInfo = new DependencyInfo("dep-groupId", "dep-artifactId", "dep-version");
    projectInfo.getDependencies().add(dependencyInfo);
    projects.add(projectInfo);//ww w  . j  a v  a 2s .c  om
    final UpdateInventoryRequest updateInventoryRequest = requestFactory.newUpdateInventoryRequest("orgToken",
            projects);

    HttpRequestHandler handler = new HttpRequestHandler() {
        @Override
        public void handle(HttpRequest request, HttpResponse response, HttpContext context)
                throws HttpException, IOException {
            HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
            List<NameValuePair> nvps = URLEncodedUtils.parse(entity);
            for (NameValuePair nvp : nvps) {
                if (nvp.getName().equals(APIConstants.PARAM_REQUEST_TYPE)) {
                    assertEquals(nvp.getValue(), updateInventoryRequest.type().toString());
                } else if (nvp.getName().equals(APIConstants.PARAM_AGENT)) {
                    assertEquals(nvp.getValue(), updateInventoryRequest.agent());
                } else if (nvp.getName().equals(APIConstants.PARAM_AGENT_VERSION)) {
                    assertEquals(nvp.getValue(), updateInventoryRequest.agentVersion());
                } else if (nvp.getName().equals(APIConstants.PARAM_TOKEN)) {
                    assertEquals(nvp.getValue(), updateInventoryRequest.orgToken());
                } else if (nvp.getName().equals(APIConstants.PARAM_TIME_STAMP)) {
                    assertEquals(nvp.getValue(), Long.toString(updateInventoryRequest.timeStamp()));
                } else if (nvp.getName().equals(APIConstants.PARAM_DIFF)) {
                    Gson gson = new Gson();
                    Type type = new TypeToken<Collection<AgentProjectInfo>>() {
                    }.getType();
                    final Collection<AgentProjectInfo> tmpProjects = gson.fromJson(nvp.getValue(), type);
                    assertEquals(tmpProjects.size(), 1);
                    final AgentProjectInfo info = tmpProjects.iterator().next();
                    assertEquals(info.getProjectToken(), projectInfo.getProjectToken());
                    assertEquals(info.getCoordinates(), projectInfo.getCoordinates());
                    assertEquals(info.getParentCoordinates(), projectInfo.getParentCoordinates());
                    assertEquals(info.getDependencies().size(), 1);
                    assertEquals(info.getDependencies().iterator().next(), dependencyInfo);
                }
            }
        }
    };
    server.register("/agent", handler);
    try {
        client.updateInventory(updateInventoryRequest);
    } catch (WssServiceException e) {
        // suppress exception
    }
}

From source file:se.vgregion.pubsub.push.impl.DefaultPushSubscriberVerifyTest.java

@Test(expected = FailedSubscriberVerificationException.class)
@Transactional//from  w ww. j a  v  a  2 s  .  com
@Rollback
public void verifyWithMissingChallenge() throws Exception {
    server.register("/*", new HttpRequestHandler() {
        @Override
        public void handle(HttpRequest request, HttpResponse response, HttpContext context)
                throws HttpException, IOException {
            // do not return challenge
        }
    });

    subscriber.verify(SubscriptionMode.SUBSCRIBE);
}

From source file:nl.surfnet.sab.HttpClientTransportTest.java

@Test
public void testGetRestResponse() throws Exception {
    final String expectedResult = "{\"message\": \"OK\", \"code\": 0, \"profiles\": []}";
    server.register("/test/profile", new HttpRequestHandler() {
        @Override//w w  w  .ja  va  2s. c  om
        public void handle(HttpRequest request, HttpResponse response, HttpContext context)
                throws HttpException, IOException {
            assertTrue(request.getRequestLine().getUri().contains("abbrev=organisation&role=theRole"));
            response.setEntity(new StringEntity(expectedResult));
            response.setStatusCode(200);
        }
    });
    InputStream inputStream = transport.getRestResponse("organisation", "theRole");
    assertEquals(expectedResult, IOUtils.toString(inputStream));

}

From source file:com.android.unit_tests.TestHttpService.java

/**
 * This test case executes a series of simple GET requests 
 *///from   www .  jav a 2  s. co  m
@LargeTest
public void testSimpleBasicHttpRequests() throws Exception {

    int reqNo = 20;

    Random rnd = new Random();

    // Prepare some random data
    final List testData = new ArrayList(reqNo);
    for (int i = 0; i < reqNo; i++) {
        int size = rnd.nextInt(5000);
        byte[] data = new byte[size];
        rnd.nextBytes(data);
        testData.add(data);
    }

    // Initialize the server-side request handler
    this.server.registerHandler("*", new HttpRequestHandler() {

        public void handle(final HttpRequest request, final HttpResponse response, final HttpContext context)
                throws HttpException, IOException {

            String s = request.getRequestLine().getUri();
            if (s.startsWith("/?")) {
                s = s.substring(2);
            }
            int index = Integer.parseInt(s);
            byte[] data = (byte[]) testData.get(index);
            ByteArrayEntity entity = new ByteArrayEntity(data);
            response.setEntity(entity);
        }

    });

    this.server.start();

    DefaultHttpClientConnection conn = new DefaultHttpClientConnection();
    HttpHost host = new HttpHost("localhost", this.server.getPort());

    try {
        for (int r = 0; r < reqNo; r++) {
            if (!conn.isOpen()) {
                Socket socket = new Socket(host.getHostName(), host.getPort());
                conn.bind(socket, this.client.getParams());
            }

            BasicHttpRequest get = new BasicHttpRequest("GET", "/?" + r);
            HttpResponse response = this.client.execute(get, host, conn);
            byte[] received = EntityUtils.toByteArray(response.getEntity());
            byte[] expected = (byte[]) testData.get(r);

            assertEquals(expected.length, received.length);
            for (int i = 0; i < expected.length; i++) {
                assertEquals(expected[i], received[i]);
            }
            if (!this.client.keepAlive(response)) {
                conn.close();
            }
        }

        //Verify the connection metrics
        HttpConnectionMetrics cm = conn.getMetrics();
        assertEquals(reqNo, cm.getRequestCount());
        assertEquals(reqNo, cm.getResponseCount());

    } finally {
        conn.close();
        this.server.shutdown();
    }
}

From source file:se.vgregion.pubsub.push.impl.DefaultPushSubscriberVerifyTest.java

@Test(expected = FailedSubscriberVerificationException.class)
@Transactional/*from   www.j av a  2  s .co  m*/
@Rollback
public void verifyWithInvalidChallenge() throws Exception {
    server.register("/*", new HttpRequestHandler() {
        @Override
        public void handle(HttpRequest request, HttpResponse response, HttpContext context)
                throws HttpException, IOException {
            response.setEntity(HttpUtil.createEntity("dummy"));
        }
    });

    subscriber.verify(SubscriptionMode.SUBSCRIBE);
}