Example usage for org.apache.http.localserver LocalTestServer LocalTestServer

List of usage examples for org.apache.http.localserver LocalTestServer LocalTestServer

Introduction

In this page you can find the example usage for org.apache.http.localserver LocalTestServer LocalTestServer.

Prototype

public LocalTestServer(BasicHttpProcessor proc, HttpParams params) 

Source Link

Document

Creates a new test server.

Usage

From source file:org.phenotips.pingback.internal.client.data.IPPingDataProviderTest.java

@Before
public void before() throws Exception {
    server = new LocalTestServer(null, null);
    server.start();/*from   www .  j  a v a  2 s. c om*/
    serverURL = "http:/" + server.getServiceAddress();
}

From source file:org.dataconservancy.access.connector.AbstractHttpConnectorTest.java

@BeforeClass
public static void setUp() throws Exception {

    XMLUnit.setIgnoreComments(true);//from  w  ww. j a v  a  2  s .c  om
    XMLUnit.setIgnoreWhitespace(true);

    final BasicHttpProcessor httpProc = new BasicHttpProcessor();
    testServer = new LocalTestServer(httpProc, null);

    testServer.register("/entity/*", new HttpRequestHandler() {
        @Override
        public void handle(HttpRequest request, HttpResponse response, HttpContext context)
                throws HttpException, IOException {
            final String requestURI = request.getRequestLine().getUri();
            final String requestedEntity = requestURI.substring(requestURI.lastIndexOf("/") + 1);
            log.trace("processing request for entity {}", requestedEntity);
            final File requestedEntityFile = new File(entitiesDir, requestedEntity + ".xml");
            if (!requestedEntityFile.exists()) {
                response.setStatusCode(HttpStatus.SC_NOT_FOUND);
            } else {
                response.setStatusCode(HttpStatus.SC_OK);
                response.setHeader("content-type", "application/xml");
                response.setEntity(new InputStreamEntity(new FileInputStream(requestedEntityFile), -1));
            }
        }
    });

    testServer.register("/query/*", new HttpRequestHandler() {
        @Override
        public void handle(HttpRequest request, HttpResponse response, HttpContext context)
                throws HttpException, IOException {
            final String requestURI = request.getRequestLine().getUri();
            final String query = requestURI.substring(requestURI.lastIndexOf("/") + 1);

            int max = -1;
            int offset = 0;

            //For some reason request.getParams wasn't working so parse the string
            String[] params = query.split("&");

            for (String param : params) {
                String name = param.split("=")[0];
                if (name.equalsIgnoreCase("max")) {
                    max = Integer.parseInt(param.split("=")[1]);
                } else if (name.equalsIgnoreCase("offset")) {
                    offset = Integer.parseInt(param.split("=")[1]);
                }
            }

            if (max == -1) {
                max = allTestEntities.size();
            }

            log.trace(
                    "processing request for query {} (note that the query itself is ignored and the response is hardcoded)",
                    query);
            // basically we iterate over all the entities in the file system and return a DCP of Files.  The actual query is ignored

            final Dcp dcp = new Dcp();
            int count = 0;
            for (DcsEntity e : allTestEntities) {
                if (e instanceof DcsFile) {
                    if (count >= offset) {
                        dcp.addFile((DcsFile) e);
                    }
                    count++;
                    if (count == max) {
                        break;
                    }
                }
            }

            count = dcp.getFiles().size();

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            mb.buildSip(dcp, baos);

            response.setStatusCode(HttpStatus.SC_OK);
            response.setHeader("content-type", "application/xml");
            response.setHeader("X-TOTAL-MATCHES", String.valueOf(count));
            response.setEntity(new BufferedHttpEntity(new ByteArrayEntity(baos.toByteArray())));
        }
    });

    testServer.register("/deposit/file", new HttpRequestHandler() {
        @Override
        public void handle(HttpRequest request, HttpResponse response, HttpContext context)
                throws HttpException, IOException {
            log.trace("file upload");

            response.setStatusCode(HttpStatus.SC_ACCEPTED);
            response.setHeader("content-type", "application/atom+xml;type=entry");
            response.setHeader("Location", "http://dataconservancy.org/deposit/003210.atom");
            response.setHeader("X-dcs-src", "http://dataconservancy.org/deposit/003210.file");
            response.setEntity(new StringEntity("<?xml version='1.0'?>"
                    + "<entry xmlns='http://www.w3.org/2005/Atom' xmlns:dc='http://dataconservancy.org/ns/'>"
                    + "</entry>", "UTF-8"));
        }
    });

    testServer.register("/deposit/sip", new HttpRequestHandler() {
        @Override
        public void handle(HttpRequest request, HttpResponse response, HttpContext context)
                throws HttpException, IOException {
            log.trace("sip upload");

            response.setStatusCode(HttpStatus.SC_ACCEPTED);
            response.setHeader("content-type", "application/atom+xml;type=entry");
            response.setHeader("Location", "http://dcservice.moo.org:8080/dcs/content/sipDeposit/4331419");
            response.setEntity(new StringEntity("<?xml version='1.0'?>"
                    + "<entry xmlns='http://www.w3.org/2005/Atom' xmlns:sword='http://purl.org/net/sword/'><id>deposit:/sipDeposit/4331419</id><content type='application/xml' src='http://dcservice.moo.org:8080/dcs/content/sipDeposit/4331419' /><title type='text'>Deposit 4331419</title><updated>2011-10-28T18:12:50.171Z</updated><author><name>Depositor</name></author><summary type='text'>ingesting</summary><link href='http://dcservice.moo.org:8080/dcs/status/sipDeposit/4331419' type='application/atom+xml; type=feed' rel='alternate' title='Processing Status' /><sword:treatment>Deposit processing</sword:treatment></entry>"));
        }
    });

    testServer.start();
    log.info("Test HTTP server listening on {}:{}", testServer.getServiceHostName(),
            testServer.getServicePort());
}

From source file:co.cask.cdap.client.rest.RestTest.java

@Before
public void setUp() throws Exception {
    localTestServer = new LocalTestServer(null, null);
    localTestServer.register("*/config", configHandler);
    localTestServer.register("*/truncate", truncateHandler);
    localTestServer.register("*/info", infoHandler);
    localTestServer.register("*", streamsHandler);
    localTestServer.start();/*www  .j a v  a  2  s .c om*/
    testServerHost = localTestServer.getServiceAddress().getHostName();
    testServerPort = localTestServer.getServiceAddress().getPort();
}

From source file:org.surfnet.oaaas.selenium.SeleniumSupport.java

protected String startAuthorizationCallbackServer(String clientId, String secret) throws Exception {
    this.oauthClientServer = new LocalTestServer(null, null);
    oauthClientServer.start();/*w  w w. j  a v  a 2s  .c o  m*/
    // report how to access the server
    String oauthClientBaseUri = String.format("http://%s:%d",
            oauthClientServer.getServiceAddress().getHostName(),
            oauthClientServer.getServiceAddress().getPort());

    String accessTokenRedirectUri = oauthClientBaseUri + "/codeCatcher";

    authorizationCodeRequestHandler = new AuthorizationCodeRequestHandler(accessTokenRedirectUri, baseUrl(),
            clientId, secret, OAuth2Validator.GRANT_TYPE_AUTHORIZATION_CODE);
    oauthClientServer.register("/codeCatcher", authorizationCodeRequestHandler);
    return accessTokenRedirectUri;
}

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

@Before
public void setUp() throws Exception {
    server = new LocalTestServer(null, null);
    server.start();/* w ww  .j a v a 2  s.  com*/

    String serviceUrl = "http:/" + server.getServiceAddress().toString() + "/agent";
    client = new WssServiceClientImpl(serviceUrl);
    log.info("Local test server is available at " + serviceUrl);

    requestFactory = new RequestFactory("Client Test", "1.0");
}

From source file:ddf.security.samlp.MetadataConfigurationParserTest.java

@Before
public void before() throws Exception {
    MockitoAnnotations.initMocks(this);
    OpenSAMLUtil.initSamlEngine();/*from w w  w . ja  v a2s .  co m*/

    descriptorPath = Paths.get(getClass().getResource("/etc/metadata/entityDescriptor.xml").toURI());
    System.setProperty("ddf.home", "");

    server = new LocalTestServer(null, null);
    server.register("/*", handler);
    server.start();

    serverAddress = server.getServiceAddress().getHostString() + ":" + server.getServiceAddress().getPort();
}

From source file:org.neo4j.ext.udc.impl.PingerTest.java

@Before
public void setUp() throws Exception {
    handler = new PingerHandler();
    server = new LocalTestServer(null, null);
    server.register("/*", handler);
    server.start();//from  ww w .ja v a2 s .co m

    hostname = server.getServiceAddress().getHostName();
    serverUrl = "http://" + hostname + ":" + server.getServiceAddress().getPort();
}

From source file:se.vgregion.pubsub.inttest.Subscriber.java

public Subscriber(String localServerName, final SubscriberResult result) throws Exception {
    this.localServerName = localServerName;
    server = new LocalTestServer(null, null);

    server.register("/*", new HttpRequestHandler() {
        @Override//w  w  w . j  a v a  2 s .c o m
        public void handle(HttpRequest request, HttpResponse response, HttpContext context)
                throws HttpException, IOException {
            String challenge = getQueryParamValue(request.getRequestLine().getUri(), "hub.challenge");

            if (challenge != null) {
                doVerify();
                // subscription verification, confirm
                response.setEntity(new StringEntity(challenge));
            } else if (request instanceof HttpEntityEnclosingRequest) {
                if (result != null && result.fail()) {
                    response.setStatusCode(500);
                }
                HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
                doPublish(entity);
            } else {
                System.err.println("Unknown request");
            }
        }
    });
    server.start();
}

From source file:nl.esciencecenter.osmium.mac.MacITCase.java

@Before
public void setUp() throws Exception {
    server = new LocalTestServer(null, null);
    server.register("/status", new AuthHandler());
    server.start();/*w  ww  .  j a  v  a2s  . c  om*/
    LOGGER.info("Started webserver on {}", getServerURI());
}

From source file:io.joynr.messaging.bounceproxy.controller.RemoteBounceProxyFacadeTest.java

@Before
public void setUp() throws Exception {

    // use local test server to intercept http requests sent by the reporter
    server = new LocalTestServer(null, null);
    server.register("*", handler);
    server.start();// ww  w. j  ava  2s.com

    serverUrl = "http://localhost:" + server.getServiceAddress().getPort() + "/";

    Properties properties = new Properties();
    properties.put(BounceProxyControllerPropertyKeys.PROPERTY_BPC_SEND_CREATE_CHANNEL_MAX_RETRY_COUNT, "3");
    properties.put(BounceProxyControllerPropertyKeys.PROPERTY_BPC_SEND_CREATE_CHANNEL_RETRY_INTERVAL_MS, "100");

    Injector injector = Guice.createInjector(new PropertyLoadingModule(properties), new AbstractModule() {

        @Override
        protected void configure() {
            bind(CloseableHttpClient.class).toInstance(HttpClients.createDefault());
        }
    });

    bpFacade = injector.getInstance(RemoteBounceProxyFacade.class);
}