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

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

Introduction

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

Prototype

public BasicHttpProcessor() 

Source Link

Usage

From source file:wh.contrib.RewardOptimizerHttpClient.java

public static void main(String[] args) throws Exception {
    HttpParams params = new BasicHttpParams();
    params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 30000)
            .setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000)
            .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 64 * 1024)
            .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
            .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
            .setParameter(CoreProtocolPNames.USER_AGENT,
                    "HttpComponents/1.1 (RewardOptimizer - karlthepagan@gmail.com)");

    final ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor(2, params);

    BasicHttpProcessor httpproc = new BasicHttpProcessor();
    httpproc.addInterceptor(new RequestContent());
    httpproc.addInterceptor(new RequestTargetHost());
    httpproc.addInterceptor(new RequestConnControl());
    httpproc.addInterceptor(new RequestUserAgent());
    httpproc.addInterceptor(new RequestExpectContinue());

    // We are going to use this object to synchronize between the 
    // I/O event and main threads
    RequestCount requestCount = new RequestCount(1);

    BufferingHttpClientHandler handler = new BufferingHttpClientHandler(httpproc,
            new MyHttpRequestExecutionHandler(requestCount), new DefaultConnectionReuseStrategy(), params);

    handler.setEventListener(new EventLogger());

    final IOEventDispatch ioEventDispatch = new DefaultClientIOEventDispatch(handler, params);

    Thread t = new Thread(new Runnable() {

        public void run() {
            try {
                ioReactor.execute(ioEventDispatch);
            } catch (InterruptedIOException ex) {
                System.err.println("Interrupted");
            } catch (IOException e) {
                System.err.println("I/O error: " + e.getMessage());
            }//from  w w  w.  jav a  2  s  .c o m
            System.out.println("Shutdown");
        }

    });
    t.start();

    List<SessionRequest> reqs = new ArrayList<SessionRequest>();
    //        reqs.add(ioReactor.connect(
    //                new InetSocketAddress("www.yahoo.com", 80), 
    //                null, 
    //                new HttpHost("www.yahoo.com"),
    //                null));
    //        reqs.add(ioReactor.connect(
    //                new InetSocketAddress("www.google.com", 80), 
    //                null,
    //                new HttpHost("www.google.ch"),
    //                null));
    //        reqs.add(ioReactor.connect(
    //                new InetSocketAddress("www.apache.org", 80), 
    //                null,
    //                new HttpHost("www.apache.org"),
    //                null));

    reqs.add(ioReactor.connect(new InetSocketAddress("www.wowhead.com", 80), null,
            new HttpHost("www.wowhead.com"), null));

    // Block until all connections signal
    // completion of the request execution
    synchronized (requestCount) {
        while (requestCount.getValue() > 0) {
            requestCount.wait();
        }
    }

    System.out.println("Shutting down I/O reactor");

    ioReactor.shutdown();

    System.out.println("Done");
}

From source file:org.eclipse.ecf.provider.filetransfer.httpcore.NHttpClient.java

public static void main(String[] args) throws Exception {
    HttpParams params = new BasicHttpParams();
    params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000)
            .setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000)
            .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
            .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
            .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
            .setParameter(CoreProtocolPNames.USER_AGENT, "HttpComponents/1.1");

    final ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor(2, params);

    BasicHttpProcessor httpproc = new BasicHttpProcessor();
    httpproc.addInterceptor(new RequestContent());
    httpproc.addInterceptor(new RequestTargetHost());
    httpproc.addInterceptor(new RequestConnControl());
    httpproc.addInterceptor(new RequestUserAgent());
    httpproc.addInterceptor(new RequestExpectContinue());

    // We are going to use this object to synchronize between the 
    // I/O event and main threads
    //CountDownLatch requestCount = new CountDownLatch(3);
    CountDownLatch requestCount = new CountDownLatch(1);

    BufferingHttpClientHandler handler = new MyBufferingHttpClientHandler(httpproc,
            new MyHttpRequestExecutionHandler(requestCount), new DefaultConnectionReuseStrategy(), params);

    handler.setEventListener(new EventLogger());

    final IOEventDispatch ioEventDispatch = new DefaultClientIOEventDispatch(handler, params);

    Thread t = new Thread(new Runnable() {

        public void run() {
            try {
                ioReactor.execute(ioEventDispatch);
            } catch (InterruptedIOException ex) {
                System.err.println("Interrupted");
            } catch (IOException e) {
                System.err.println("I/O error: " + e.getMessage());
            }//from  w  ww . jav  a  2  s  .  c  o  m
            System.out.println("Shutdown");
        }

    });
    t.start();

    SessionRequest[] reqs = new SessionRequest[1];
    reqs[0] = ioReactor.connect(new InetSocketAddress("ftp.osuosl.org", 80), null,
            new HttpHost("ftp.osuosl.org"), new MySessionRequestCallback(requestCount));
    // Block until all connections signal
    // completion of the request execution
    requestCount.await();

    System.out.println("Shutting down I/O reactor");

    ioReactor.shutdown();

    System.out.println("Done");
}

From source file:NHttpClient.java

public static void main(String[] args) throws Exception {
    HttpParams params = new BasicHttpParams();
    params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000)
            .setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000)
            .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
            .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
            .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
            .setParameter(CoreProtocolPNames.USER_AGENT, "HttpComponents/1.1");

    final ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor(2, params);

    BasicHttpProcessor httpproc = new BasicHttpProcessor();
    httpproc.addInterceptor(new RequestContent());
    httpproc.addInterceptor(new RequestTargetHost());
    httpproc.addInterceptor(new RequestConnControl());
    httpproc.addInterceptor(new RequestUserAgent());
    httpproc.addInterceptor(new RequestExpectContinue());

    // We are going to use this object to synchronize between the 
    // I/O event and main threads
    CountDownLatch requestCount = new CountDownLatch(3);

    BufferingHttpClientHandler handler = new BufferingHttpClientHandler(httpproc,
            new MyHttpRequestExecutionHandler(requestCount), new DefaultConnectionReuseStrategy(), params);

    handler.setEventListener(new EventLogger());

    final IOEventDispatch ioEventDispatch = new DefaultClientIOEventDispatch(handler, params);

    Thread t = new Thread(new Runnable() {

        public void run() {
            try {
                ioReactor.execute(ioEventDispatch);
            } catch (InterruptedIOException ex) {
                System.err.println("Interrupted");
            } catch (IOException e) {
                System.err.println("I/O error: " + e.getMessage());
            }/* w w w  .  j  a  v a2  s  .c om*/
            System.out.println("Shutdown");
        }

    });
    t.start();

    SessionRequest[] reqs = new SessionRequest[3];
    reqs[0] = ioReactor.connect(new InetSocketAddress("www.yahoo.com", 80), null, new HttpHost("www.yahoo.com"),
            new MySessionRequestCallback(requestCount));
    reqs[1] = ioReactor.connect(new InetSocketAddress("www.google.com", 80), null,
            new HttpHost("www.google.ch"), new MySessionRequestCallback(requestCount));
    reqs[2] = ioReactor.connect(new InetSocketAddress("www.apache.org", 80), null,
            new HttpHost("www.apache.org"), new MySessionRequestCallback(requestCount));

    // Block until all connections signal
    // completion of the request execution
    requestCount.await();

    System.out.println("Shutting down I/O reactor");

    ioReactor.shutdown();

    System.out.println("Done");
}

From source file:neembuu.httpserver.VFStoHttpServer.java

private void create(int port) throws IOException {

    HttpProcessor httpproc = new BasicHttpProcessor();

    HttpRequestHandlerRegistry registry = new HttpRequestHandlerRegistry();
    registry.register("*", new VFSHandler(fs));
    HttpService httpService = new HttpService(httpproc, new DefaultConnectionReuseStrategy(),
            new DefaultHttpResponseFactory());
    httpService.setHandlerResolver(registry);
    SSLServerSocketFactory sf = null;

    Thread t = new RequestListenerThread(port, httpService, sf);
    t.setDaemon(false);/*  w  w w  .  ja v a 2 s  .c om*/
    t.start();
}

From source file:com.wondershare.http.core.Dispatcher.java

protected void initHttpService() {
    BasicHttpProcessor proc = new BasicHttpProcessor();
    ConnectionReuseStrategy connStrategy = new DefaultConnectionReuseStrategy();
    HttpResponseFactory responseFactory = new DefaultHttpResponseFactory();

    proc.addInterceptor(new ResponseDate());
    proc.addInterceptor(new ResponseServer());
    proc.addInterceptor(new ResponseContent());
    proc.addInterceptor(new ResponseConnControl());
    httpService = new HttpService(proc, connStrategy, responseFactory);
}

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

@BeforeClass
public static void setUp() throws Exception {

    XMLUnit.setIgnoreComments(true);/*  w  w w .  jav  a  2 s . c o  m*/
    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:org.hydracache.server.httpd.HttpServiceHandlerFactory.java

public NHttpServiceHandler create() throws Exception {
    BasicHttpProcessor httpproc = new BasicHttpProcessor();

    // Required protocol interceptors
    httpproc.addInterceptor(new ResponseDate());
    httpproc.addInterceptor(new ResponseServer());
    httpproc.addInterceptor(new ResponseContent());
    httpproc.addInterceptor(new ResponseConnControl());

    httpproc.addInterceptor(new ParameterFetchRequestIntercepter());

    BufferingHttpServiceHandler handler = new BufferingHttpServiceHandler(httpproc,
            new DefaultHttpResponseFactory(), new DefaultConnectionReuseStrategy(), httpParams);

    HttpRequestHandlerRegistry reqistry = new HttpRequestHandlerRegistry();

    reqistry.register("*", requestHandler);

    handler.setHandlerResolver(reqistry);

    handler.setEventListener(protocolEventListener);

    return handler;
}

From source file:se.inera.certificate.proxy.filter.HttpProxyClient.java

@Override
protected BasicHttpProcessor createHttpProcessor() {
    BasicHttpProcessor httpproc = new BasicHttpProcessor();
    httpproc.addInterceptor(new RequestDefaultHeaders());
    // Required protocol interceptors
    httpproc.addInterceptor(new RequestContent(true));
    httpproc.addInterceptor(new RequestTargetHost());
    // Recommended protocol interceptors
    httpproc.addInterceptor(new RequestClientConnControl());
    httpproc.addInterceptor(new RequestUserAgent());
    httpproc.addInterceptor(new RequestExpectContinue());
    // HTTP state management interceptors
    httpproc.addInterceptor(new RequestAddCookies());
    httpproc.addInterceptor(new ResponseProcessCookies());
    // HTTP authentication interceptors
    httpproc.addInterceptor(new RequestAuthCache());
    httpproc.addInterceptor(new RequestTargetAuthentication());
    httpproc.addInterceptor(new RequestProxyAuthentication());
    return httpproc;
}

From source file:mpv5.utils.http.HttpClient.java

/**
 * Connects to the given host/*from   w ww .j a  v  a  2s.c om*/
 * @param toHost
 * @param port
 * @throws UnknownHostException
 * @throws IOException
 * @throws HttpException
 */
public HttpClient(String toHost, int port) throws UnknownHostException, IOException, HttpException {
    params = new BasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, "UTF-8");
    HttpProtocolParams.setUserAgent(params, "HttpComponents/1.1");
    HttpProtocolParams.setUseExpectContinue(params, true);

    httpproc = new BasicHttpProcessor();
    // Required protocol interceptors
    httpproc.addInterceptor(new RequestContent());
    httpproc.addInterceptor(new RequestTargetHost());
    // Recommended protocol interceptors
    httpproc.addInterceptor(new RequestConnControl());
    httpproc.addInterceptor(new RequestUserAgent());
    httpproc.addInterceptor(new RequestExpectContinue());
    httpexecutor = new HttpRequestExecutor();
    context = new BasicHttpContext(null);
    host = new HttpHost(toHost, port);
    conn = new DefaultHttpClientConnection();
    connStrategy = new DefaultConnectionReuseStrategy();
    context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
    context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host);
}

From source file:edu.wisc.commons.httpclient.HrsDefaultHttpClient.java

/**
 * Override just to set RequestContent(true)
 *//*from w w  w . j  a  v  a 2  s.c o m*/
@Override
protected BasicHttpProcessor createHttpProcessor() {
    BasicHttpProcessor httpproc = new BasicHttpProcessor();
    httpproc.addInterceptor(new RequestDefaultHeaders());
    // Required protocol interceptors
    httpproc.addInterceptor(new RequestContent(true));
    httpproc.addInterceptor(new RequestTargetHost());
    // Recommended protocol interceptors
    httpproc.addInterceptor(new RequestClientConnControl());
    httpproc.addInterceptor(new RequestUserAgent());
    httpproc.addInterceptor(new RequestExpectContinue());
    // HTTP state management interceptors
    httpproc.addInterceptor(new RequestAddCookies());
    httpproc.addInterceptor(new ResponseProcessCookies());
    // HTTP authentication interceptors
    httpproc.addInterceptor(new RequestAuthCache());
    httpproc.addInterceptor(new RequestTargetAuthentication());
    httpproc.addInterceptor(new RequestProxyAuthentication());
    return httpproc;
}