@Test(expected=ClientProtocolException.class) public void testRejectInvalidRedirectLocation() throws Exception { final UriHttpRequestHandlerMapper reqistry = new UriHttpRequestHandlerMapper(); this.serverBootstrap.setHandlerMapper(reqistry); final HttpHost target = start(); reqistry.register("*", new BogusRedirectService("http://" + target.toHostString() + "/newlocation/?p=I have spaces")); final HttpGet httpget = new HttpGet("/oldlocation/"); try { this.httpclient.execute(target, httpget); } catch (final ClientProtocolException e) { Assert.assertTrue(e.getCause() instanceof ProtocolException); throw e; } }
public static void main(String[] args) throws Exception { int port = 8080; String docRoot = "D:\\svn_file\\TEST2\\150503\\web-customer"; // Set up the HTTP protocol processor HttpProcessor httpproc = HttpProcessorBuilder.create().add(new ResponseDate()) .add(new ResponseServer("Haogrgr/1.1")).add(new ResponseContent()) .add(new ResponseConnControl()).build(); // Set up request handlers UriHttpRequestHandlerMapper reqistry = new UriHttpRequestHandlerMapper(); reqistry.register("*", new HttpFileHandler(docRoot)); // Set up the HTTP service HttpService httpService = new HttpService(httpproc, reqistry); Thread t = new RequestListenerThread(port, httpService, null); t.setDaemon(false); t.start(); }
/** * Default constructor which specifies the <code>port</code> to listen to * for requests and the <code>handlers</code>, which specify how to handle * the request. * * @param port * the port to listen to * @param handlers * the handlers, which specify how to handle the different * requests * * @throws IOException * if some IO operation fails */ public RequestListenerThread(final int port, final Map<String, IHandler> handlers) throws IOException { super(port); // Set up the HTTP protocol processor final HttpProcessor httpproc = new ImmutableHttpProcessor( new HttpResponseInterceptor[] { new ResponseDate(), new ResponseServer(), new ResponseContent(), new ResponseConnControl() }); // Set up request handlers UriHttpRequestHandlerMapper registry = new UriHttpRequestHandlerMapper(); for (final Entry<String, IHandler> entry : handlers.entrySet()) { registry.register(entry.getKey(), entry.getValue()); } // Set up the HTTP service httpService = new HttpService(httpproc, registry); connFactory = DefaultBHttpServerConnectionFactory.INSTANCE; }
@Test public void test() throws ExecutionException, InterruptedException { HttpHost target = new HttpHost("localhost"); BasicConnPool connpool = new BasicConnPool(); connpool.setMaxTotal(200); connpool.setDefaultMaxPerRoute(10); connpool.setMaxPerRoute(target, 20); Future<BasicPoolEntry> future = connpool.lease(target, null); BasicPoolEntry poolEntry = future.get(); HttpClientConnection conn = poolEntry.getConnection(); HttpProcessor httpproc = HttpProcessorBuilder.create() .add(new ResponseDate()) .add(new ResponseServer("MyServer-HTTP/1.1")) .add(new ResponseContent()) .add(new ResponseConnControl()) .build(); HttpRequestHandler myRequestHandler = new HttpRequestHandler() { public void handle( HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException { response.setStatusCode(HttpStatus.SC_OK); response.setEntity( new StringEntity("some important message", ContentType.TEXT_PLAIN)); } }; UriHttpRequestHandlerMapper handlerMapper = new UriHttpRequestHandlerMapper(); handlerMapper.register("/service/*", myRequestHandler); HttpService httpService = new HttpService(httpproc, handlerMapper); }
public RequestListenerThread(final int port, final HttpHost target) throws IOException { this.target = target; this.serversocket = new ServerSocket(port); // Set up HTTP protocol processor for incoming connections final HttpProcessor inhttpproc = new ImmutableHttpProcessor( new HttpRequestInterceptor[] { new RequestContent(), new RequestTargetHost(), new RequestConnControl(), new RequestUserAgent("Test/1.1"), new RequestExpectContinue(true) }); // Set up HTTP protocol processor for outgoing connections final HttpProcessor outhttpproc = new ImmutableHttpProcessor( new HttpResponseInterceptor[] { new ResponseDate(), new ResponseServer("Test/1.1"), new ResponseContent(), new ResponseConnControl() }); // Set up outgoing request executor final HttpRequestExecutor httpexecutor = new HttpRequestExecutor(); // Set up incoming request handler final UriHttpRequestHandlerMapper reqistry = new UriHttpRequestHandlerMapper(); reqistry.register("*", new ProxyHandler( this.target, outhttpproc, httpexecutor)); // Set up the HTTP service this.httpService = new HttpService(inhttpproc, reqistry); }
public RequestListenerThread(final int port, final HttpHost target, final TransportHandler handler) throws IOException { this.target = target; this.serversocket = new ServerSocket(port); // Set up HTTP protocol processor for incoming connections final HttpProcessor inhttpproc = new ImmutableHttpProcessor( new HttpRequestInterceptor[] { new RequestContent(), new RequestTargetHost(), new RequestConnControl(), new RequestUserAgent("Test/1.1"), new RequestExpectContinue(true) }); // Set up HTTP protocol processor for outgoing connections final HttpProcessor outhttpproc = new ImmutableHttpProcessor( new HttpResponseInterceptor[] { new ResponseDate(), new ResponseServer("Test/1.1"), new ResponseContent(), new ResponseConnControl() }); // Set up outgoing request executor final HttpRequestExecutor httpexecutor = new HttpRequestExecutor(); // Set up incoming request handler final UriHttpRequestHandlerMapper reqistry = new UriHttpRequestHandlerMapper(); reqistry.register("*", new ProxyHandler( this.target, outhttpproc, httpexecutor, handler)); // Set up the HTTP service this.httpService = new HttpService(inhttpproc, reqistry); }
public static void startServer(int port) { // 设置端口号 后期需要对端口号进行判断是否已经被占用,并把端口号信息写进模板中 isRun = true; // Set up the HTTP protocol processor HttpProcessor httpproc = HttpProcessorBuilder.create() .add(new ResponseDate()) .add(new ResponseServer("Test/1.1")) .add(new ResponseContent()) .add(new ResponseConnControl()).build(); // Set up request handlers UriHttpRequestHandlerMapper reqistry = new UriHttpRequestHandlerMapper(); reqistry.register("*", new HttpFileHandler(null)); // Set up the HTTP service httpService = new HttpService(httpproc, reqistry); SSLServerSocketFactory sf = null; try { t = new RequestListenerThread(port, httpService, sf); } catch (IOException e) { e.printStackTrace(); } t.setDaemon(true); t.start(); }
ProxyProxy(int listenPort, InetAddress listenAddress, HttpHost proxy) throws IOException { this.serversocket = new ServerSocket(listenPort, 0, listenAddress); HttpProcessor httpproc = HttpProcessorBuilder.create().add(new ResponseConnControl()).build(); UriHttpRequestHandlerMapper reqistry = new UriHttpRequestHandlerMapper(); reqistry.register("*", new HttpForwardingHandler(proxy)); this.httpService = new HttpService(httpproc, new UpgradedConnectionAwareReusingStrategy(), null, reqistry); }
/** * Tests that an abort called after a redirect has found a new host * still aborts in the correct place (while trying to get the new * host's route, not while doing the subsequent request). */ @Test public void testAbortAfterRedirectedRoute() throws Exception { final UriHttpRequestHandlerMapper reqistry = new UriHttpRequestHandlerMapper(); this.serverBootstrap.setHandlerMapper(reqistry); final CountDownLatch connLatch = new CountDownLatch(1); final CountDownLatch awaitLatch = new CountDownLatch(1); final ConnMan4 conMan = new ConnMan4(connLatch, awaitLatch); final AtomicReference<Throwable> throwableRef = new AtomicReference<Throwable>(); final CountDownLatch getLatch = new CountDownLatch(1); this.clientBuilder.setConnectionManager(conMan); final HttpContext context = new BasicHttpContext(); final HttpGet httpget = new HttpGet("a"); final HttpHost target = start(); reqistry.register("*", new BasicRedirectService(target.getPort())); new Thread(new Runnable() { @Override public void run() { try { final HttpHost host = new HttpHost("127.0.0.1", target.getPort()); httpclient.execute(host, httpget, context); } catch(final Throwable t) { throwableRef.set(t); } finally { getLatch.countDown(); } } }).start(); Assert.assertTrue("should have tried to get a connection", connLatch.await(1, TimeUnit.SECONDS)); httpget.abort(); Assert.assertTrue("should have finished get request", getLatch.await(1, TimeUnit.SECONDS)); Assert.assertTrue("should be instanceof IOException, was: " + throwableRef.get(), throwableRef.get() instanceof IOException); Assert.assertTrue("cause should be InterruptedException, was: " + throwableRef.get().getCause(), throwableRef.get().getCause() instanceof InterruptedException); }
/** * @param args the command line arguments * @throws java.lang.Exception */ public static void main(String[] args) throws Exception { int fixedExecutorSize = 4; if (args.length != 2) { System.err.println("Invalid command line parameters for worker"); System.exit(-1); } // Set worker mode String mode = args[1]; // Creating fixed size executor ThreadPoolExecutor taskExecutor = new ThreadPoolExecutor(fixedExecutorSize, fixedExecutorSize, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()); int port = Integer.parseInt(args[0]); // Set up the HTTP protocol processor HttpProcessor httpproc = HttpProcessorBuilder.create() .add(new ResponseDate()) .add(new ResponseServer("Test/1.1")) .add(new ResponseContent()) .add(new ResponseConnControl()).build(); // Set up request handler (either generic or late binding) UriHttpRequestHandlerMapper reqistry = new UriHttpRequestHandlerMapper(); if (mode.equals("--late")) reqistry.register("*", new LateBindingRequestHandler(taskExecutor)); else reqistry.register("*", new GenericRequestHandler(taskExecutor)); // Set up the HTTP service HttpService httpService = new HttpService(httpproc, reqistry); SSLServerSocketFactory sf = null; // SSL code removed as it is not needed // create a thread to listen for possible scheduler available connections Thread t = new RequestListenerThread(port, httpService, sf); System.out.println("Request Listener Thread created"); t.setDaemon(false); t.start(); // main thread should wait for the listener to exit before shutdown the // task executor pool t.join(); // shutdown task executor pool and wait for any taskExecutor thread // still running taskExecutor.shutdown(); while (!taskExecutor.isTerminated()) {} System.out.println("Finished all task executor threads"); }
/** * @param args the command line arguments * @throws java.lang.Exception */ public static void main(String[] args) throws Exception{ if (args.length != 2) { System.err.println("Invalid command line parameters for worker"); System.exit(-1); } int fixedExecutorSize = 4; //Creating fixed size executor ThreadPoolExecutor taskCommExecutor = new ThreadPoolExecutor(fixedExecutorSize, fixedExecutorSize, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()); // Used for late binding JobMap jobMap = new JobMap(); // Set port number int port = Integer.parseInt(args[0]); // Set worker mode String mode = args[1].substring(2); // Set up the HTTP protocol processor HttpProcessor httpproc = HttpProcessorBuilder.create() .add(new ResponseDate()) .add(new ResponseServer("Test/1.1")) .add(new ResponseContent()) .add(new ResponseConnControl()).build(); // Set up request handlers UriHttpRequestHandlerMapper reqistry = new UriHttpRequestHandlerMapper(); // Different handlers for late binding and generic cases if (mode.equals("late")) reqistry.register("*", new LateBindingRequestHandler(taskCommExecutor, jobMap)); else reqistry.register("*", new GenericRequestHandler(taskCommExecutor, mode)); // Set up the HTTP service HttpService httpService = new HttpService(httpproc, reqistry); SSLServerSocketFactory sf = null; // create a thread to listen for possible client available connections Thread t; if (mode.equals("late")) t = new LateBindingRequestListenerThread(port, httpService, sf); else t = new GenericRequestListenerThread(port, httpService, sf); System.out.println("Request Listener Thread created"); t.setDaemon(false); t.start(); // main thread should wait for the listener to exit before shutdown the // task executor pool t.join(); // shutdown task executor pool and wait for any taskCommExecutor thread // still running taskCommExecutor.shutdown(); while (!taskCommExecutor.isTerminated()) {} System.out.println("Finished all task communication executor threads"); System.out.println("Finished all tasks"); }
public SimpleHttpServer(int port, ConnectedAddressesProvider connectedAddressesProvider){ this.connFactory = DefaultBHttpServerConnectionFactory.INSTANCE; // Set up the HTTP protocol processor HttpProcessor httpproc = HttpProcessorBuilder.create() .add(new ResponseDate()) .add(new ResponseServer("Test/1.1")) .add(new ResponseContent()) .add(new ResponseConnControl()).build(); // Set up request handlers UriHttpRequestHandlerMapper reqistry = new UriHttpRequestHandlerMapper(); reqistry.register("*", new HttpRequestHandlerNew(connectedAddressesProvider)); // Set up the HTTP service httpService = new HttpService(httpproc, reqistry); try { serversocket = new ServerSocket(port, 1, InetAddress.getByName("127.0.0.1")); System.out.println("Listening on port " + serversocket.getLocalPort()); while (!Thread.interrupted()) { try { // Set up HTTP connection Socket socket = serversocket.accept(); System.out.println("Incoming connection from " + socket.getInetAddress()); HttpServerConnection conn = connFactory.createConnection(socket); // Start worker thread Thread t = new WorkerThread(httpService, conn); t.setDaemon(true); t.start(); } catch (InterruptedIOException ex) { break; } catch (IOException e) { System.err.println("I/O error initialising connection thread: " + e.getMessage()); break; } } } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } }
public static void start(String[] args) throws Exception { int port = 8082; if (args.length >= 1) { port = Integer.parseInt(args[0]); } ActorSystem system = ActorSystem.create("Application-System"); Properties config = new Properties(); config.load(HttpServer.class.getResourceAsStream("/megapode.conf")); ActorRef master = system.actorOf( Props.create(CoordinatingActor.class, config), "Coordinator"); // Set up the HTTP protocol processor HttpProcessor httpproc = HttpProcessorBuilder.create() .add(new ResponseDate()).add(new ResponseServer("Test/1.1")) .add(new ResponseContent()).add(new ResponseConnControl()) .build(); // Set up request handlers UriHttpRequestHandlerMapper reqistry = new UriHttpRequestHandlerMapper(); reqistry.register("*", new HttpHandler(system, master)); // Set up the HTTP service HttpService httpService = new HttpService(httpproc, reqistry); SSLServerSocketFactory sf = null; if (port == 8443) { // Initialize SSL context ClassLoader cl = HttpServer.class.getClassLoader(); URL url = cl.getResource("my.keystore"); if (url == null) { System.out.println("Keystore not found"); System.exit(1); } KeyStore keystore = KeyStore.getInstance("jks"); keystore.load(url.openStream(), "secret".toCharArray()); KeyManagerFactory kmfactory = KeyManagerFactory .getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmfactory.init(keystore, "secret".toCharArray()); KeyManager[] keymanagers = kmfactory.getKeyManagers(); SSLContext sslcontext = SSLContext.getInstance("TLS"); sslcontext.init(keymanagers, null, null); sf = sslcontext.getServerSocketFactory(); } RequestListenerThread t = new RequestListenerThread(port, httpService, sf); t.setDaemon(false); t.start(); t.join(); }