List of usage examples for org.apache.http.impl.nio.reactor IOReactorConfig setIoThreadCount
@Deprecated public void setIoThreadCount(final int ioThreadCount)
From source file:com.weibo.wesync.client.NHttpClient2.java
public static void main(String[] args) throws Exception { RSAPublicKey publicKey = RSAEncrypt.loadPublicKey("D:\\weibo\\meyou_gw\\conf\\public.pem"); // //from w w w. ja v a 2 s . com byte[] cipher = RSAEncrypt.encrypt(publicKey, password.getBytes()); password = RSAEncrypt.toHexString(cipher); // HTTP parameters for the client HttpParams params = new SyncBasicHttpParams(); params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 30000) .setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 30000) .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024) .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true); // Create HTTP protocol processing chain HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] { // Use standard client-side protocol interceptors new RequestContent(), new RequestTargetHost(), new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue() }); // Create client-side HTTP protocol handler HttpAsyncRequestExecutor protocolHandler = new HttpAsyncRequestExecutor(); // Create client-side I/O event dispatch final IOEventDispatch ioEventDispatch = new DefaultHttpClientIODispatch(protocolHandler, params); // Create client-side I/O reactor IOReactorConfig config = new IOReactorConfig(); config.setIoThreadCount(1); final ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor(config); // Create HTTP connection pool BasicNIOConnPool pool = new BasicNIOConnPool(ioReactor, params); // Limit total number of connections to just two pool.setDefaultMaxPerRoute(2); pool.setMaxTotal(1); // Run the I/O reactor in a separate thread Thread t = new Thread(new Runnable() { public void run() { try { // Ready to go! ioReactor.execute(ioEventDispatch); } catch (InterruptedIOException ex) { System.err.println("Interrupted"); } catch (IOException e) { System.err.println("I/O error: " + e.getMessage()); } System.out.println("Shutdown"); } }); // Start the client thread t.start(); // Create HTTP requester // HttpAsyncRequester requester = new HttpAsyncRequester( // httpproc, new DefaultConnectionReuseStrategy(), params); // Execute HTTP GETs to the following hosts and HttpHost[] targets = new HttpHost[] { // new HttpHost("123.125.106.28", 8093, "http"), // new HttpHost("123.125.106.28", 8093, "http"), // new HttpHost("123.125.106.28", 8093, "http"), // new HttpHost("123.125.106.28", 8093, "http"), // new HttpHost("123.125.106.28", 8093, "http"), // new HttpHost("123.125.106.28", 8093, "http"), // new HttpHost("123.125.106.28", 8093, "http"), // new HttpHost("123.125.106.28", 8093, "http"), // new HttpHost("123.125.106.28", 8093, "http"), // new HttpHost("123.125.106.28", 8093, "http"), // new HttpHost("123.125.106.28", 8093, "http"), new HttpHost("123.125.106.28", 8082, "http") }; final CountDownLatch latch = new CountDownLatch(targets.length); int callbackId = 0; for (int i = 0; i < 1; i++) { for (final HttpHost target : targets) { BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", "/wesync"); // String usrpwd = Base64.encodeBase64String((username + ":" + password).getBytes()); // request.setHeader("authorization", "Basic " + usrpwd); request.setHeader("uid", "2565640713"); Meyou.MeyouPacket packet = null; if (callbackId == 0) { packet = Meyou.MeyouPacket.newBuilder().setCallbackId(String.valueOf(callbackId++)) .setSort(MeyouSort.notice).build(); } else { packet = Meyou.MeyouPacket.newBuilder().setCallbackId(String.valueOf(callbackId++)) .setSort(MeyouSort.wesync).build(); } ByteArrayEntity entity = new ByteArrayEntity(packet.toByteArray()); request.setEntity(entity); // BasicHttpRequest request = new BasicHttpRequest("GET", "/test.html"); System.out.println("send ..."); HttpAsyncRequester requester = new HttpAsyncRequester(httpproc, new DefaultConnectionReuseStrategy(), params); requester.execute(new BasicAsyncRequestProducer(target, request), new BasicAsyncResponseConsumer(), pool, new BasicHttpContext(), // Handle HTTP response from a callback new FutureCallback<HttpResponse>() { public void completed(final HttpResponse response) { StatusLine status = response.getStatusLine(); int code = status.getStatusCode(); if (code == 200) { try { latch.countDown(); DataInputStream in; in = new DataInputStream(response.getEntity().getContent()); int packetLength = in.readInt(); int start = 0; while (packetLength > 0) { ByteArrayOutputStream outstream = new ByteArrayOutputStream( packetLength); byte[] buffer = new byte[1024]; int len = 0; while (start < packetLength && (len = in.read(buffer, start, packetLength)) > 0) { outstream.write(buffer, 0, len); start += len; } Meyou.MeyouPacket packet0 = Meyou.MeyouPacket .parseFrom(outstream.toByteArray()); System.out.println(target + "->" + packet0); if ((len = in.read(buffer, start, 4)) > 0) { packetLength = Util.readPacketLength(buffer); } else { break; } } } catch (IllegalStateException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { System.out.println("error code=" + code + "|" + status.getReasonPhrase()); } } public void failed(final Exception ex) { latch.countDown(); System.out.println(target + "->" + ex); } public void cancelled() { latch.countDown(); System.out.println(target + " cancelled"); } }); Thread.sleep((long) (Math.random() * 10000)); } } // latch.await(); // System.out.println("Shutting down I/O reactor"); // ioReactor.shutdown(); // System.out.println("Done"); }
From source file:org.apache.synapse.transport.passthru.config.BaseConfiguration.java
protected IOReactorConfig buildIOReactorConfig() { IOReactorConfig config = new IOReactorConfig(); config.setIoThreadCount(conf.getIOThreadsPerReactor()); config.setSoTimeout(conf.getIntProperty(HttpConnectionParams.SO_TIMEOUT, 60000)); config.setConnectTimeout(conf.getIntProperty(HttpConnectionParams.CONNECTION_TIMEOUT, 0)); config.setTcpNoDelay(conf.getBooleanProperty(HttpConnectionParams.TCP_NODELAY, true)); config.setSoLinger(conf.getIntProperty(HttpConnectionParams.SO_LINGER, -1)); config.setSoReuseAddress(conf.getBooleanProperty(HttpConnectionParams.SO_REUSEADDR, false)); config.setInterestOpQueued(conf.getBooleanProperty("http.nio.interest-ops-queueing", false)); config.setSelectInterval(conf.getIntProperty("http.nio.select-interval", 1000)); return config; }
From source file:com.aptana.webserver.internal.core.builtin.LocalWebServer.java
private void runServer(InetSocketAddress socketAddress, HttpAsyncRequestHandler httpRequestHandler) { HttpParams params = new BasicHttpParams(); params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, SOCKET_TIMEOUT) .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false) .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, SOCKET_BUFFER_SIZE) .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true) .setParameter(CoreProtocolPNames.ORIGIN_SERVER, "HttpComponents/" + EclipseUtil.getPluginVersion("org.apache.httpcomponents.httpcore")); //$NON-NLS-1$ //$NON-NLS-2$ BasicHttpProcessor httpProcessor = new BasicHttpProcessor(); httpProcessor.addInterceptor(new ResponseDate()); httpProcessor.addInterceptor(new ResponseServer()); httpProcessor.addInterceptor(new ResponseContent()); httpProcessor.addInterceptor(new ResponseConnControl()); HttpAsyncRequestHandlerRegistry handlerRegistry = new HttpAsyncRequestHandlerRegistry(); handlerRegistry.register("*", httpRequestHandler); //$NON-NLS-1$ HttpAsyncService serviceHandler = new HttpAsyncService(httpProcessor, new DefaultConnectionReuseStrategy(), handlerRegistry, params);/* www. j a v a 2 s . c o m*/ // serviceHandler.setEventListener(new LocalWebServerLogger()); IOReactorConfig config = new IOReactorConfig(); config.setIoThreadCount(WORKER_COUNT); config.setConnectTimeout(SOCKET_TIMEOUT); config.setTcpNoDelay(true); config.setSoKeepalive(true); DefaultHttpServerIODispatch eventDispatch = new DefaultHttpServerIODispatch(serviceHandler, params); try { reactor = new DefaultListeningIOReactor(config); reactor.listen(socketAddress); reactor.execute(eventDispatch); } catch (InterruptedIOException e) { return; } catch (IOReactorException e) { IdeLog.logWarning(WebServerCorePlugin.getDefault(), e); } catch (IOException e) { IdeLog.logError(WebServerCorePlugin.getDefault(), e); } }
From source file:com.googlecode.jsonrpc4j.JsonRpcHttpAsyncClient.java
private void initialize() { if (initialized.getAndSet(true)) { return;// w w w.jav a2s. c om } // HTTP parameters for the client final HttpParams params = new BasicHttpParams(); params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, Integer.getInteger("com.googlecode.jsonrpc4j.async.socket.timeout", 30000)); params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, Integer.getInteger("com.googlecode.jsonrpc4j.async.connect.timeout", 30000)); params.setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, Integer.getInteger("com.googlecode.jsonrpc4j.async.socket.buffer", 8 * 1024)); params.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, Boolean.valueOf(System.getProperty("com.googlecode.jsonrpc4j.async.tcp.nodelay", "true"))); params.setParameter(CoreProtocolPNames.USER_AGENT, "jsonrpc4j/1.0"); // Create client-side I/O reactor final ConnectingIOReactor ioReactor; try { IOReactorConfig config = new IOReactorConfig(); config.setIoThreadCount(Integer.getInteger("com.googlecode.jsonrpc4j.async.reactor.threads", 1)); ioReactor = new DefaultConnectingIOReactor(config); } catch (IOReactorException e) { throw new RuntimeException("Exception initializing asynchronous Apache HTTP Client", e); } // Create a default SSLSetupHandler that accepts any certificate if (sslContext == null) { try { sslContext = SSLContext.getDefault(); } catch (Exception e) { throw new RuntimeException(e); } } // Create HTTP connection pool BasicNIOConnFactory nioConnFactory = new BasicNIOConnFactory(sslContext, null, params); pool = new BasicNIOConnPool(ioReactor, nioConnFactory, params); // Limit total number of connections to 500 by default pool.setDefaultMaxPerRoute(Integer.getInteger("com.googlecode.jsonrpc4j.async.max.inflight.route", 500)); pool.setMaxTotal(Integer.getInteger("com.googlecode.jsonrpc4j.async.max.inflight.total", 500)); // Run the I/O reactor in a separate thread Thread t = new Thread(new Runnable() { public void run() { try { // Create client-side HTTP protocol handler HttpAsyncRequestExecutor protocolHandler = new HttpAsyncRequestExecutor(); // Create client-side I/O event dispatch IOEventDispatch ioEventDispatch = new DefaultHttpClientIODispatch(protocolHandler, sslContext, params); // Ready to go! ioReactor.execute(ioEventDispatch); } catch (InterruptedIOException ex) { System.err.println("Interrupted"); } catch (IOException e) { System.err.println("I/O error: " + e.getMessage()); } } }, "jsonrpc4j HTTP IOReactor"); // Start the client thread t.setDaemon(true); t.start(); // Create HTTP protocol processing chain HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] { // Use standard client-side protocol interceptors new RequestContent(), new RequestTargetHost(), new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue() }); // Create HTTP requester requester = new HttpAsyncRequester(httpproc, new DefaultConnectionReuseStrategy(), params); }
From source file:org.apache.synapse.transport.nhttp.HttpCoreNIOListener.java
/** * Initialize the transport listener, and execute reactor in new separate thread * @param "cfgCtx" the Axis2 configuration context * @param transportIn the description of the http/s transport from Axis2 configuration * @throws AxisFault on error//from w ww .j a v a2 s . c o m */ public void init(ConfigurationContext ctx, TransportInDescription transportIn) throws AxisFault { cfgCtx = ctx; Map<String, String> o = (Map<String, String>) cfgCtx.getProperty(NhttpConstants.EPR_TO_SERVICE_NAME_MAP); if (o != null) { this.eprToServiceNameMap = o; } else { eprToServiceNameMap = new HashMap<String, String>(); cfgCtx.setProperty(NhttpConstants.EPR_TO_SERVICE_NAME_MAP, eprToServiceNameMap); } NHttpConfiguration cfg = NHttpConfiguration.getInstance(); // Initialize connection factory params = new BasicHttpParams(); params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, cfg.getProperty(NhttpConstants.SO_TIMEOUT_RECEIVER, 60000)) .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, cfg.getProperty(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)) .setParameter(CoreProtocolPNames.ORIGIN_SERVER, "Synapse-HttpComponents-NIO"); // .setParameter(CoreProtocolPNames.HTTP_ELEMENT_CHARSET, // cfg.getStringValue(CoreProtocolPNames.HTTP_ELEMENT_CHARSET, HTTP.DEFAULT_PROTOCOL_CHARSET)); //TODO:This does not works with HTTPCore 4.3 name = transportIn.getName().toUpperCase(Locale.US) + " Listener"; scheme = initScheme(); // Setup listener context listenerContext = new ListenerContextBuilder(transportIn).parse().build(); System.setProperty(transportIn.getName() + ".nio.port", String.valueOf(listenerContext.getPort())); // Setup connection factory HttpHost host = new HttpHost(listenerContext.getHostname(), listenerContext.getPort(), scheme.getName()); connFactory = initConnFactoryBuilder(transportIn, host).build(params); // configure the IO reactor on the specified port try { String prefix = name + " I/O dispatcher"; IOReactorConfig ioReactorConfig = new IOReactorConfig(); ioReactorConfig.setIoThreadCount(cfg.getServerIOWorkers()); ioReactorConfig.setSoTimeout(cfg.getProperty(NhttpConstants.SO_TIMEOUT_RECEIVER, 60000)); ioReactorConfig.setTcpNoDelay(cfg.getProperty(CoreConnectionPNames.TCP_NODELAY, 1) == 1); if (cfg.getBooleanValue("http.nio.interest-ops-queueing", false)) { ioReactorConfig.setInterestOpQueued(true); } ioReactorConfig.setSoReuseAddress(cfg.getBooleanValue(CoreConnectionPNames.SO_REUSEADDR, false)); ioReactor = new DefaultListeningIOReactor(ioReactorConfig, new NativeThreadFactory(new ThreadGroup(prefix + " thread group"), prefix)); ioReactor.setExceptionHandler(new IOReactorExceptionHandler() { public boolean handle(IOException ioException) { log.warn("System may be unstable: IOReactor encountered a checked exception : " + ioException.getMessage(), ioException); return true; } public boolean handle(RuntimeException runtimeException) { log.warn("System may be unstable: IOReactor encountered a runtime exception : " + runtimeException.getMessage(), runtimeException); return true; } }); } catch (IOException e) { handleException("Error creating IOReactor", e); } metrics = new NhttpMetricsCollector(true, transportIn.getName()); handler = new ServerHandler(cfgCtx, scheme, listenerContext, metrics); iodispatch = new ServerIODispatch(handler, connFactory); Parameter param = transportIn.getParameter(NhttpConstants.WSDL_EPR_PREFIX); if (param != null) { serviceEPRPrefix = getServiceEPRPrefix(cfgCtx, (String) param.getValue()); customEPRPrefix = (String) param.getValue(); EPRPrefixCheck = false; } else { serviceEPRPrefix = getServiceEPRPrefix(cfgCtx, listenerContext.getHostname(), listenerContext.getPort()); customEPRPrefix = scheme.getName() + "://" + listenerContext.getHostname() + ":" + (listenerContext.getPort() == scheme.getDefaultPort() ? "" : listenerContext.getPort()) + "/"; } // register to receive updates on services for lifetime management cfgCtx.getAxisConfiguration().addObservers(axisObserver); // register with JMX mbeanSupport = new TransportMBeanSupport(this, "nio-" + transportIn.getName()); mbeanSupport.register(); }
From source file:org.apache.synapse.transport.nhttp.HttpCoreNIOSender.java
/** * Initialize the transport sender, and execute reactor in new separate thread * @param cfgCtx the Axis2 configuration context * @param transportOut the description of the http/s transport from Axis2 configuration * @throws AxisFault thrown on an error//from w w w .j a v a 2 s . co m */ public void init(ConfigurationContext cfgCtx, TransportOutDescription transportOut) throws AxisFault { this.configurationContext = cfgCtx; cfg = NHttpConfiguration.getInstance(); params = new BasicHttpParams(); params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, cfg.getProperty(NhttpConstants.SO_TIMEOUT_SENDER, 60000)) .setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, cfg.getProperty(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000)) .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, cfg.getProperty(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)) .setParameter(CoreProtocolPNames.USER_AGENT, "Synapse-HttpComponents-NIO"); // .setParameter(CoreProtocolPNames.HTTP_ELEMENT_CHARSET, // cfg.getStringValue(CoreProtocolPNames.HTTP_ELEMENT_CHARSET,HTTP.DEFAULT_PROTOCOL_CHARSET)); //TODO:This does not works with HTTPCore 4.3 name = transportOut.getName().toUpperCase(Locale.US) + " Sender"; ClientConnFactoryBuilder contextBuilder = initConnFactoryBuilder(transportOut); connFactory = contextBuilder.createConnFactory(params); connpool = new ConnectionPool(); proxyConfig = new ProxyConfigBuilder().parse(transportOut).build(); if (log.isInfoEnabled() && proxyConfig.getProxy() != null) { log.info("HTTP Sender using Proxy " + proxyConfig.getProxy() + " bypassing " + proxyConfig.getProxyBypass()); } Parameter param = transportOut.getParameter("warnOnHTTP500"); if (param != null) { String[] warnOnHttp500 = ((String) param.getValue()).split("\\|"); cfgCtx.setNonReplicableProperty("warnOnHTTP500", warnOnHttp500); } IOReactorConfig ioReactorConfig = new IOReactorConfig(); ioReactorConfig.setIoThreadCount(NHttpConfiguration.getInstance().getClientIOWorkers()); ioReactorConfig.setSoTimeout(cfg.getProperty(NhttpConstants.SO_TIMEOUT_RECEIVER, 60000)); ioReactorConfig.setConnectTimeout(cfg.getProperty(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000)); ioReactorConfig.setTcpNoDelay(cfg.getProperty(CoreConnectionPNames.TCP_NODELAY, 1) == 1); if (cfg.getBooleanValue("http.nio.interest-ops-queueing", false)) { ioReactorConfig.setInterestOpQueued(true); } try { String prefix = name + " I/O dispatcher"; ioReactor = new DefaultConnectingIOReactor(ioReactorConfig, new NativeThreadFactory(new ThreadGroup(prefix + " thread group"), prefix)); ioReactor.setExceptionHandler(new IOReactorExceptionHandler() { public boolean handle(IOException ioException) { log.warn("System may be unstable: IOReactor encountered a checked exception : " + ioException.getMessage(), ioException); return true; } public boolean handle(RuntimeException runtimeException) { log.warn("System may be unstable: IOReactor encountered a runtime exception : " + runtimeException.getMessage(), runtimeException); return true; } }); } catch (IOException e) { log.error("Error starting the IOReactor", e); throw new AxisFault(e.getMessage(), e); } metrics = new NhttpMetricsCollector(false, transportOut.getName()); handler = new ClientHandler(connpool, connFactory, proxyConfig.getCreds(), cfgCtx, params, metrics); iodispatch = new ClientIODispatch(handler, connFactory); final IOEventDispatch ioEventDispatch = iodispatch; // start the Sender in a new seperate thread Thread t = new Thread(new Runnable() { public void run() { try { ioReactor.execute(ioEventDispatch); } catch (InterruptedIOException ex) { log.fatal("Reactor Interrupted"); } catch (IOException e) { log.fatal("Encountered an I/O error: " + e.getMessage(), e); } log.info(name + " Shutdown"); } }, "HttpCoreNIOSender"); t.start(); log.info(name + " starting"); // register with JMX mbeanSupport = new TransportMBeanSupport(this, "nio-" + transportOut.getName()); mbeanSupport.register(); state = BaseConstants.STARTED; }