dev@grizzly.java.net

Re: Grizzly and Axis2

From: sumitsureka <sumit_sureka_at_yahoo.co.uk>
Date: Tue, 20 May 2008 07:48:21 -0700 (PDT)

Hi Jeanfrancois,

I am not a committer, just out of curiosity towards NIO. I wanted to take
the features of both, so thought of going this way though I am very new
Grizzly and I think still some work is left in the implementation to use the
complete feature of Selectors (instead of using multiple threads). Though
this is the small piece of code that I have managed to write:

package com.evolving.sa.Grizzly;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;

import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;

import org.apache.axiom.om.impl.builder.StAXBuilder;
import org.apache.axiom.om.util.UUIDGenerator;
import org.apache.axiom.soap.SOAP11Constants;
import org.apache.axiom.soap.SOAP12Constants;
import org.apache.axiom.soap.SOAPEnvelope;
import org.apache.axiom.soap.impl.builder.StAXSOAPModelBuilder;
import org.apache.axis2.AxisFault;
import org.apache.axis2.Constants;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.context.ConfigurationContext;
import org.apache.axis2.context.MessageContext;
import org.apache.axis2.context.SessionContext;
import org.apache.axis2.description.HandlerDescription;
import org.apache.axis2.description.Parameter;
import org.apache.axis2.description.TransportInDescription;
import org.apache.axis2.description.TransportOutDescription;
import org.apache.axis2.engine.AxisEngine;
import org.apache.axis2.transport.TransportListener;
import org.apache.axis2.transport.TransportSender;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.protocol.HTTP;

import com.sun.grizzly.http.SelectorThread;
import com.sun.grizzly.tcp.Adapter;
import com.sun.grizzly.tcp.OutputBuffer;
import com.sun.grizzly.tcp.Request;
import com.sun.grizzly.tcp.Response;
import com.sun.grizzly.util.buf.ByteChunk;

/**
 * NIO transport listener for Axis2 based on HttpCore and NIO extensions
 */
public class GrizzlyListener implements TransportListener, Adapter,
TransportSender {

 private static final Log log = LogFactory.getLog(GrizzlyListener.class);
 
    protected ConfigurationContext configurationContext;
    /** The EPR prefix for services available over this transport */
    private String serviceEPRPrefix;
    /** The port to listen on, defaults to 8080 */
    private int port = 8080;
    /** The hostname to use, defaults to localhost */
    private String host = "localhost";
 
 public void destroy() {
  // TODO Auto-generated method stub
  
 }

 public EndpointReference getEPRForService(String serviceName, String ip)
   throws AxisFault {
  // TODO Auto-generated method stub
  return null;
 }

 public EndpointReference[] getEPRsForService(String serviceName, String ip)
   throws AxisFault {
  // TODO Auto-generated method stub
  return null;
 }

 public SessionContext getSessionContext(MessageContext messageContext) {
  // TODO Auto-generated method stub
  return null;
 }

 public void init(ConfigurationContext axisConf,
   TransportInDescription transprtIn) throws AxisFault {
        
        this.configurationContext = axisConf;
        
        Parameter param = transprtIn.getParameter(PARAM_PORT);
        if (param != null) {
            port = Integer.parseInt((String) param.getValue());
        }

        param = transprtIn.getParameter(HOST_ADDRESS);
        if (param != null) {
            host = ((String) param.getValue()).trim();
        } else {
            try {
                host = java.net.InetAddress.getLocalHost().getHostName();
            } catch (UnknownHostException e) {
                log.warn("Unable to lookup local host name, using
'localhost'");
            }
        }
 }

 public void start() throws AxisFault {
  SelectorThread st = new SelectorThread();
  st.setMinWorkerThreads(10);
  st.setMaxThreads(12);
  st.setPort(port);
  st.setAdapter(this);
  st.setDisplayConfiguration(true);
  try {
   st.initEndpoint();
   st.startEndpoint();
  } catch (Exception e) {
   System.out.println("Exception in SelectorThread: " + e);
  } finally {
   if (st.isRunning()) {
    st.stopEndpoint();
   }
  }
 }

 public void stop() {
  // TODO Auto-generated method stub
  
 }

 public void afterService(Request request, Response response) throws
Exception {
  request.recycle();
  response.recycle();
 }

 public void fireAdapterEvent(String arg0, Object arg1) {
  // TODO Auto-generated method stub
  
 }

 public void service(Request request, Response response) throws Exception {
  System.out.println("Thread Name : "+Thread.currentThread().getName());
  String requestURI = request.requestURI().toString();
  System.out.println("New incoming request with URI: " + requestURI);
  System.out.println("Request Method is: " + request.method());
  AxisEngine engine = new AxisEngine(configurationContext);
        MessageContext msgContext = new MessageContext();
        try {
            msgContext.setProperty(MessageContext.TRANSPORT_NON_BLOCKING,
Boolean.TRUE);
            msgContext.setConfigurationContext(configurationContext);
           
msgContext.setTransportOut(configurationContext.getAxisConfiguration().getTransportOut(Constants.TRANSPORT_HTTP));
           
msgContext.setTransportIn(configurationContext.getAxisConfiguration().getTransportIn(Constants.TRANSPORT_HTTP));
            msgContext.setIncomingTransportName(Constants.TRANSPORT_HTTP);
            msgContext.setProperty(Constants.OUT_TRANSPORT_INFO, this);
            msgContext.setServiceGroupContextId(UUIDGenerator.getUUID());
            msgContext.setServerSide(true);
            msgContext.setProperty(Constants.Configuration.TRANSPORT_IN_URL,
request.requestURI().toString());
            Map headerMap = new HashMap();
            headerMap.put("SOAPAction", request.getHeader("SOAPAction"));
            msgContext.setProperty(MessageContext.TRANSPORT_HEADERS,
headerMap);
            String soapAction = request.getHeader("SOAPAction");
         msgContext.setWSAAction(soapAction);
         msgContext.setSoapAction(soapAction);
         
         //Need to set the EPR
         //msgContext.setReplyTo(new
EndpointReference("http://localhost:8090/axis2/services/ActivationServiceSkeleton"));
         msgContext.setTo(new
EndpointReference(request.requestURI().toString()));

         //Extract SOAP Envelope from Input request object.
         //Needs to replace the below given code.
         /*String str = new
String(request.requestURI().getByteChunk().getBytes());
         int endIndex = str.length();
         int beginIndex = str.indexOf('<');
         String soapEnvelope = str.substring(beginIndex, endIndex-1).trim();
         System.out.println(soapEnvelope);
         
         byte byteArray[] = soapEnvelope.getBytes();*/
         
         int contentLenght = request.getContentLength();
      ByteChunk byteChunk = new ByteChunk(contentLenght);
      String inStr = "";
      try {
       int readBytes = 0;
       while ( readBytes < contentLenght ) {
        readBytes += request.doRead( byteChunk );
        inStr += byteChunk.toString();
       }
      } catch ( IOException e ) {
       e.printStackTrace();
      }
      System.out.println(inStr);
      byte byteArray[] = inStr.getBytes();
         
         ByteArrayInputStream bais = new ByteArrayInputStream(byteArray);
         XMLStreamReader reader =
XMLInputFactory.newInstance().createXMLStreamReader(bais);
         String soapNamespaceURI = "";
           
if(request.getContentType().indexOf(SOAP12Constants.SOAP_12_CONTENT_TYPE) >
-1){
                soapNamespaceURI =
SOAP12Constants.SOAP_ENVELOPE_NAMESPACE_URI;
            } else
if(request.getContentType().indexOf(SOAP11Constants.SOAP_11_CONTENT_TYPE) >
-1){
                soapNamespaceURI =
SOAP11Constants.SOAP_ENVELOPE_NAMESPACE_URI;
            }
            StAXBuilder builder = new StAXSOAPModelBuilder(reader,
soapNamespaceURI);
         SOAPEnvelope envelope = (SOAPEnvelope)
builder.getDocumentElement();
         msgContext.setEnvelope(envelope);
         InvocationResponse resp = engine.receive(msgContext);
         response.setStatus(HttpURLConnection.HTTP_OK);
   byte[] bytes = "Here is the final response".getBytes();
   ByteChunk chunk = new ByteChunk();
   response.setContentLength(bytes.length);
   response.setContentType("text/plain");
   chunk.append(bytes, 0, bytes.length);
   OutputBuffer buffer = response.getOutputBuffer();
   buffer.doWrite(chunk, response);
         response.finish();
        } catch (Exception e) {
            System.out.println("Exception in service processing : "+e);
            e.printStackTrace();
        }
    }

 public void cleanup(MessageContext msgContext) throws AxisFault {
  // TODO Auto-generated method stub
  
 }

 public void init(ConfigurationContext confContext,
   TransportOutDescription transportOut) throws AxisFault {
  // TODO Auto-generated method stub
  
 }

 public void cleanup() {
  // TODO Auto-generated method stub
  
 }

 public void flowComplete(MessageContext msgContext) {
  // TODO Auto-generated method stub
  
 }

 public HandlerDescription getHandlerDesc() {
  // TODO Auto-generated method stub
  return null;
 }

 public String getName() {
  // TODO Auto-generated method stub
  return null;
 }

 public Parameter getParameter(String name) {
  // TODO Auto-generated method stub
  return null;
 }

 public void init(HandlerDescription handlerDesc) {
  // TODO Auto-generated method stub
  
 }

 public InvocationResponse invoke(MessageContext msgContext)
   throws AxisFault {
  //Need to implement this for extracting the msgContext
  XMLStreamReader reader =
msgContext.getEnvelope().getBody().getXMLStreamReader();
  System.out.println(msgContext.getEnvelope().getBody().toString());
  
        try {
            while (reader.hasNext()) {
                int event = reader.next();
                if (event == XMLStreamConstants.CHARACTERS) {
                    System.out.println(reader.getText());
                } else if (event == XMLStreamConstants.ENTITY_REFERENCE) {
                 System.out.println("en: "+reader.getLocalName());
                 System.out.println("er: "+reader.getText());
                } else if (event == XMLStreamConstants.START_ELEMENT) {
                 System.out.println(reader.getLocalName());
                }
            }
  } catch (XMLStreamException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  return null;
 }
 
}

Here, each HTTP request is handled by a different worker thread that is
created by grizzly.

Regards,
Sumit

-- 
View this message in context: http://www.nabble.com/Grizzly-and-Axis2-tp17303209p17342301.html
Sent from the Grizzly - Development mailing list archive at Nabble.com.