geronimo-scm mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From pra...@apache.org
Subject svn commit: r599057 - in /geronimo/samples/trunk/samples/async-http/http-local-app: pom.xml src/main/java/org/apache/geronimo/NIOServlet.java src/main/webapp/WEB-INF/geronimo-web.xml src/main/webapp/WEB-INF/web.xml
Date Wed, 28 Nov 2007 16:38:23 GMT
Author: prasad
Date: Wed Nov 28 08:38:23 2007
New Revision: 599057

URL: http://svn.apache.org/viewvc?rev=599057&view=rev
Log:
* NIOServlet to use HttpComponents

Added:
    geronimo/samples/trunk/samples/async-http/http-local-app/src/main/java/org/apache/geronimo/NIOServlet.java
  (with props)
Modified:
    geronimo/samples/trunk/samples/async-http/http-local-app/pom.xml
    geronimo/samples/trunk/samples/async-http/http-local-app/src/main/webapp/WEB-INF/geronimo-web.xml
    geronimo/samples/trunk/samples/async-http/http-local-app/src/main/webapp/WEB-INF/web.xml

Modified: geronimo/samples/trunk/samples/async-http/http-local-app/pom.xml
URL: http://svn.apache.org/viewvc/geronimo/samples/trunk/samples/async-http/http-local-app/pom.xml?rev=599057&r1=599056&r2=599057&view=diff
==============================================================================
--- geronimo/samples/trunk/samples/async-http/http-local-app/pom.xml (original)
+++ geronimo/samples/trunk/samples/async-http/http-local-app/pom.xml Wed Nov 28 08:38:23 2007
@@ -46,6 +46,11 @@
             <version>6.0.8-SNAPSHOT</version>
             <scope>provided</scope>
         </dependency>
+        <dependency>
+            <groupId>org.apache.httpcomponents</groupId>
+            <artifactId>httpcore-nio</artifactId>
+            <version>4.0-alpha6</version>
+        </dependency>
     </dependencies>
     
     <build>

Added: geronimo/samples/trunk/samples/async-http/http-local-app/src/main/java/org/apache/geronimo/NIOServlet.java
URL: http://svn.apache.org/viewvc/geronimo/samples/trunk/samples/async-http/http-local-app/src/main/java/org/apache/geronimo/NIOServlet.java?rev=599057&view=auto
==============================================================================
--- geronimo/samples/trunk/samples/async-http/http-local-app/src/main/java/org/apache/geronimo/NIOServlet.java
(added)
+++ geronimo/samples/trunk/samples/async-http/http-local-app/src/main/java/org/apache/geronimo/NIOServlet.java
Wed Nov 28 08:38:23 2007
@@ -0,0 +1,383 @@
+package org.apache.geronimo;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.io.PrintWriter;
+import java.net.URL;
+import java.util.Random;
+import java.io.OutputStream;
+import java.util.Date;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServlet;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import java.io.InterruptedIOException;
+import java.net.InetSocketAddress;
+import org.apache.catalina.CometEvent;
+import org.apache.catalina.CometProcessor;
+
+import org.apache.http.HttpEntity;
+import org.apache.http.HttpException;
+import org.apache.http.HttpHost;
+import org.apache.http.HttpRequest;
+import org.apache.http.HttpResponse;
+import org.apache.http.impl.DefaultConnectionReuseStrategy;
+import org.apache.http.params.BasicHttpParams;
+import org.apache.http.impl.nio.DefaultClientIOEventDispatch;
+import org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor;
+import org.apache.http.message.BasicHttpRequest;
+import org.apache.http.nio.NHttpConnection;
+import org.apache.http.nio.protocol.BufferingHttpClientHandler;
+import org.apache.http.nio.protocol.EventListener;
+import org.apache.http.nio.protocol.HttpRequestExecutionHandler;
+import org.apache.http.nio.reactor.ConnectingIOReactor;
+import org.apache.http.nio.reactor.IOEventDispatch;
+import org.apache.http.nio.reactor.IOReactorException;
+import org.apache.http.nio.reactor.SessionRequest;
+import org.apache.http.params.CoreConnectionPNames;
+import org.apache.http.params.HttpParams;
+import org.apache.http.params.CoreProtocolPNames;
+import org.apache.http.protocol.BasicHttpProcessor;
+import org.apache.http.protocol.HttpContext;
+import org.apache.http.protocol.ExecutionContext;
+import org.apache.http.protocol.RequestConnControl;
+import org.apache.http.protocol.RequestContent;
+import org.apache.http.protocol.RequestExpectContinue;
+import org.apache.http.protocol.RequestTargetHost;
+import org.apache.http.protocol.RequestUserAgent;
+import org.apache.http.util.EntityUtils;
+
+/**
+ * Servlet implementation class for Servlet: AsyncServlet
+ * 
+ * @web.servlet name="NIOServlet" display-name="NIOServlet"
+ * 
+ * @web.servlet-mapping url-pattern="/nio"
+ * 
+ */
+public class NIOServlet extends HttpServlet implements CometProcessor {
+    static final long serialVersionUID = 1L;
+
+    private String remoteUrl;
+    private HttpParams httpParams = new BasicHttpParams(null);
+    //private BasicHttpProcessor httpproc = new BasicHttpProcessor();
+    private static ConnectingIOReactor ioReactor;
+    private static ExecutorService threadPool = Executors.newFixedThreadPool(8);
+
+    public void init() throws ServletException {
+        getServletContext().log("getinit init");
+        // Get the value of an initialization parameter
+        remoteUrl = getServletConfig().getInitParameter("remoteUrl");
+
+        httpParams
+        .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");
+
+
+        /*
+        httpproc.addInterceptor(new RequestContent());
+        httpproc.addInterceptor(new RequestTargetHost());
+        httpproc.addInterceptor(new RequestConnControl());
+        httpproc.addInterceptor(new RequestUserAgent());
+        httpproc.addInterceptor(new RequestExpectContinue());
+        */
+
+        try {
+            ioReactor = new DefaultConnectingIOReactor(1, httpParams);
+        }
+        catch ( IOReactorException e ) {
+            throw new ServletException(e);
+        }
+
+    }
+
+    /*
+    @Override
+    public void destroy() {
+        // TODO Auto-generated method stub
+        super.destroy();
+        System.out.println("Shutting down I/O reactor");
+        try {
+            ioReactor.shutdown();
+            threadPool.shutdown();
+        }
+        catch ( Exception e ) {
+            e.printStackTrace();
+        }
+    }
+    */
+
+    /**
+     * Process the given Comet event.
+     * 
+     * @param event
+     *            The Comet event that will be processed
+     * @throws IOException
+     * @throws ServletException
+     */
+
+    public void event(CometEvent event) throws IOException, ServletException {
+        HttpServletRequest request = event.getHttpServletRequest();
+
+        String sessionId = request.getSession(true).getId();
+        System.out.println("");
+        System.out.println("Session id: " + sessionId + " "
+                           + event.getEventType().toString());
+
+        if ( event.getEventType() == CometEvent.EventType.BEGIN ) {
+            event.getHttpServletRequest().setAttribute("org.apache.tomcat.comet.timeout",
new Integer(100 * 1000));
+            event.setTimeout(100 * 1000);
+
+            if ( request.getParameter("remoteUrl") != null ) {
+                remoteUrl = request.getParameter("remoteUrl");        
+            }
+
+            String remoteUri = request.getParameter("remoteUri");
+            if ( remoteUri == null ) {
+                remoteUri = "/remoteApp/page";
+            }
+
+            Integer[] params = generateRandomParams();
+            System.out.println("sessionId:" + sessionId + "; delay:" + params[0]
+                               + "; code:" + params[1]);
+
+            String url_string = remoteUri + "?sessionId=" + sessionId + "&delay=" + params[0]
+ "&code=" + params[1];       
+
+            BasicHttpProcessor httpproc = new BasicHttpProcessor();
+            httpproc.addInterceptor(new RequestContent());
+            httpproc.addInterceptor(new RequestTargetHost());
+            httpproc.addInterceptor(new RequestConnControl());
+            httpproc.addInterceptor(new RequestUserAgent());
+            httpproc.addInterceptor(new RequestExpectContinue());
+
+            /*
+            try {
+                ioReactor = new DefaultConnectingIOReactor(8, httpParams);
+            }
+            catch ( IOReactorException e ) {
+                throw new ServletException(e);
+            }
+            */
+
+            BufferingHttpClientHandler handler = new BufferingHttpClientHandler(httpproc,
new MyHttpRequestExecutionHandler(event, sessionId, url_string),
+                                                                                new DefaultConnectionReuseStrategy(),
httpParams);
+
+            handler.setEventListener(new EventLogger());
+
+            final IOEventDispatch ioEventDispatch = new DefaultClientIOEventDispatch(handler,
httpParams);
+
+            Thread t = new Thread(new Runnable() {
+
+                                      public void run() {
+                                          try {
+                                              System.out.println("Running...");
+                                              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");
+                                      }
+
+                                  });
+            t.start();
+            
+            /*
+            threadPool.execute(new Runnable() {
+
+                                      public void run() {
+                                          try {
+                                              System.out.println("Running...");
+                                              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");
+                                      }
+
+                                  });
+            */
+
+            SessionRequest reqs = ioReactor.connect(new InetSocketAddress(remoteUrl, 8080),
null, new HttpHost(remoteUrl), null);
+
+        }
+        else if ( (event.getEventType() == CometEvent.EventType.ERROR)  || (event.getEventType()
== CometEvent.EventType.END) ) {
+            event.close();
+            //ioReactor.shutdown();
+        }
+
+        System.out.println("doGet processed");
+    }
+
+    protected Integer[] generateRandomParams() {
+        Integer[] params = new Integer[2];
+        final int[] codes = new int[] { 200, 302, 403, 404, 500};
+
+        Random generator = new Random();
+
+        // generate a random delay between 10ms and 250 ms
+        int delay = generator.nextInt(250) + 10;
+        params[0] = new Integer(delay);
+
+        // generate randomly one of http status codes.
+        int index = generator.nextInt(codes.length);
+        params[1] = new Integer(codes[index]);
+
+        return params;
+    }
+
+    static class MyHttpRequestExecutionHandler implements HttpRequestExecutionHandler {
+
+        private final static String REQUEST_SENT       = "request-sent";
+        private final static String RESPONSE_RECEIVED  = "response-received";
+        private long time;
+        private String sessionId;
+        private String uri;
+        private CometEvent event;
+
+
+        public MyHttpRequestExecutionHandler(CometEvent event, String sessionId, String uri)
{
+            super();
+            this.sessionId = sessionId;
+            this.uri = uri;
+            this.event=event;
+        }
+
+        public void initalizeContext(final HttpContext context, final Object attachment)
{
+            System.out.println("Initializing Context");
+            HttpHost targetHost = (HttpHost) attachment;
+            context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, targetHost);
+            this.time=new Date().getTime();
+        }
+
+        public void finalizeContext(final HttpContext context) {
+            System.out.println("Finalizing Context");
+            Object flag = context.getAttribute(RESPONSE_RECEIVED);
+            if ( flag == null ) {
+                // Signal completion of the request execution
+                /*
+                synchronized (this.requestCount) {
+                    this.requestCount.decrement();
+                    this.requestCount.notifyAll();
+                }
+                try {
+                    event.close();
+                }
+                catch (IOException e) {
+                    e.printStackTrace();
+                }
+                */
+            }
+        }
+
+        public HttpRequest submitRequest(final HttpContext context) {
+            System.out.println("Submitting request");
+            HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
+            Object flag = context.getAttribute(REQUEST_SENT);
+            if ( flag == null ) {
+                // Stick some object into the context
+                context.setAttribute(REQUEST_SENT, Boolean.TRUE);
+
+                System.out.println("--------------");
+                System.out.println("Sending request to " + targetHost + " with sessionId:
" + this.sessionId);
+                System.out.println("--------------");
+
+                return new BasicHttpRequest("GET", uri);
+            }
+            else {
+                // No new request to submit
+                return null;
+            }
+        }
+
+        public void handleResponse(final HttpResponse res, final HttpContext context) {
+            System.out.println("Handle response");
+            HttpServletResponse response = event.getHttpServletResponse();
+            HttpEntity entity = res.getEntity();
+            try {
+                String content = EntityUtils.toString(entity);
+
+                System.out.println("--------------");
+                System.out.println(res.getStatusLine());
+                System.out.println("--------------");
+                System.out.println("Document length: " + content.length());
+                System.out.println("--------------");
+
+                response.setContentType("text/html");
+                if ( content.length() > 0 ) {
+                    response.setContentLength(content.length());
+                    OutputStream out = null;
+                    try {
+                        out = response.getOutputStream();
+                        out.write(content.getBytes());
+                        out.flush();
+                        out.close();
+                    }
+                    catch ( IOException e ) {
+                        // TODO Auto-generated catch block
+                        e.printStackTrace();
+                    }
+                }
+                System.out.println("  Responded to " + this.sessionId + " in " + (new Date().getTime()
- this.time));
+
+                //event.close();
+            }
+            catch ( IOException ex ) {
+                System.err.println("I/O error: " + ex.getMessage());
+            }
+
+            context.setAttribute(RESPONSE_RECEIVED, Boolean.TRUE);
+
+            // Signal completion of the request execution
+            /*
+            synchronized (this.requestCount) {
+                this.requestCount.decrement();
+                this.requestCount.notifyAll();
+            }
+            */
+        }
+
+    }
+
+    static class EventLogger implements EventListener {
+
+        public void connectionOpen(final NHttpConnection conn) {
+            System.out.println("Connection open: " + conn);
+        }
+
+        public void connectionTimeout(final NHttpConnection conn) {
+            System.out.println("Connection timed out: " + conn);
+        }
+
+        public void connectionClosed(final NHttpConnection conn) {
+            System.out.println("Connection closed: " + conn);
+        }
+
+        public void fatalIOException(final IOException ex, final NHttpConnection conn) {
+            System.err.println("I/O error: " + ex.getMessage());
+        }
+
+        public void fatalProtocolException(final HttpException ex, final NHttpConnection
conn) {
+            System.err.println("HTTP error: " + ex.getMessage());
+        }
+
+    }
+
+
+}

Propchange: geronimo/samples/trunk/samples/async-http/http-local-app/src/main/java/org/apache/geronimo/NIOServlet.java
------------------------------------------------------------------------------
    svn:eol-style = native

Propchange: geronimo/samples/trunk/samples/async-http/http-local-app/src/main/java/org/apache/geronimo/NIOServlet.java
------------------------------------------------------------------------------
    svn:keywords = Date Revision

Propchange: geronimo/samples/trunk/samples/async-http/http-local-app/src/main/java/org/apache/geronimo/NIOServlet.java
------------------------------------------------------------------------------
    svn:mime-type = text/plain

Modified: geronimo/samples/trunk/samples/async-http/http-local-app/src/main/webapp/WEB-INF/geronimo-web.xml
URL: http://svn.apache.org/viewvc/geronimo/samples/trunk/samples/async-http/http-local-app/src/main/webapp/WEB-INF/geronimo-web.xml?rev=599057&r1=599056&r2=599057&view=diff
==============================================================================
--- geronimo/samples/trunk/samples/async-http/http-local-app/src/main/webapp/WEB-INF/geronimo-web.xml
(original)
+++ geronimo/samples/trunk/samples/async-http/http-local-app/src/main/webapp/WEB-INF/geronimo-web.xml
Wed Nov 28 08:38:23 2007
@@ -30,6 +30,10 @@
             <version>2.1-SNAPSHOT</version>
             <type>war</type>
         </moduleId>
+        
+        <hidden-classes>
+          <filter>org.apache.http</filter>
+        </hidden-classes>
     </environment>
     
     <context-root>/localApp</context-root>

Modified: geronimo/samples/trunk/samples/async-http/http-local-app/src/main/webapp/WEB-INF/web.xml
URL: http://svn.apache.org/viewvc/geronimo/samples/trunk/samples/async-http/http-local-app/src/main/webapp/WEB-INF/web.xml?rev=599057&r1=599056&r2=599057&view=diff
==============================================================================
--- geronimo/samples/trunk/samples/async-http/http-local-app/src/main/webapp/WEB-INF/web.xml
(original)
+++ geronimo/samples/trunk/samples/async-http/http-local-app/src/main/webapp/WEB-INF/web.xml
Wed Nov 28 08:38:23 2007
@@ -17,7 +17,6 @@
   	    </init-param>      
 	</servlet>
 
-
 	<servlet-mapping>
 		<servlet-name>AsyncServlet</servlet-name>
 		<url-pattern>/async</url-pattern>
@@ -33,10 +32,24 @@
   	    </init-param>      
 	</servlet>
 
-
 	<servlet-mapping>
 		<servlet-name>BlockingServlet</servlet-name>
 		<url-pattern>/sync</url-pattern>
+	</servlet-mapping>
+
+     <servlet>
+		<display-name>NIOServlet</display-name>
+		<servlet-name>NIOServlet</servlet-name>
+		<servlet-class>org.apache.geronimo.NIOServlet</servlet-class>
+        <init-param>
+			<param-name>remoteUrl</param-name>
+			<param-value>festivus</param-value>
+  	    </init-param>      
+	</servlet>
+
+	<servlet-mapping>
+		<servlet-name>NIOServlet</servlet-name>
+		<url-pattern>/nio</url-pattern>
 	</servlet-mapping>
 
 </web-app>



Mime
View raw message