axis-java-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From asan...@apache.org
Subject svn commit: r549457 [1/3] - in /webservices/axis2/trunk/java/modules: kernel/ kernel/src/org/apache/axis2/transport/nhttp/ kernel/src/org/apache/axis2/transport/nhttp/util/ parent/
Date Thu, 21 Jun 2007 12:21:48 GMT
Author: asankha
Date: Thu Jun 21 05:21:46 2007
New Revision: 549457

URL: http://svn.apache.org/viewvc?view=rev&rev=549457
Log:
add the basic http NIO transport with https support commented out due to JDK 1.5 compilation dependence

Added:
    webservices/axis2/trunk/java/modules/kernel/src/org/apache/axis2/transport/nhttp/
    webservices/axis2/trunk/java/modules/kernel/src/org/apache/axis2/transport/nhttp/Axis2HttpRequest.java
    webservices/axis2/trunk/java/modules/kernel/src/org/apache/axis2/transport/nhttp/ClientHandler.java
    webservices/axis2/trunk/java/modules/kernel/src/org/apache/axis2/transport/nhttp/ClientWorker.java
    webservices/axis2/trunk/java/modules/kernel/src/org/apache/axis2/transport/nhttp/ConnectionPool.java
    webservices/axis2/trunk/java/modules/kernel/src/org/apache/axis2/transport/nhttp/HostnameVerifier.java
    webservices/axis2/trunk/java/modules/kernel/src/org/apache/axis2/transport/nhttp/HttpCoreNIOListener.java
    webservices/axis2/trunk/java/modules/kernel/src/org/apache/axis2/transport/nhttp/HttpCoreNIOSSLListener.java
    webservices/axis2/trunk/java/modules/kernel/src/org/apache/axis2/transport/nhttp/HttpCoreNIOSSLSender.java
    webservices/axis2/trunk/java/modules/kernel/src/org/apache/axis2/transport/nhttp/HttpCoreNIOSender.java
    webservices/axis2/trunk/java/modules/kernel/src/org/apache/axis2/transport/nhttp/HttpCoreRequestResponseTransport.java
    webservices/axis2/trunk/java/modules/kernel/src/org/apache/axis2/transport/nhttp/LoggingIOSession.java
    webservices/axis2/trunk/java/modules/kernel/src/org/apache/axis2/transport/nhttp/LoggingNHttpClientHandler.java
    webservices/axis2/trunk/java/modules/kernel/src/org/apache/axis2/transport/nhttp/LoggingNHttpServiceHandler.java
    webservices/axis2/trunk/java/modules/kernel/src/org/apache/axis2/transport/nhttp/NHttpConfiguration.java
    webservices/axis2/trunk/java/modules/kernel/src/org/apache/axis2/transport/nhttp/NhttpConstants.java
    webservices/axis2/trunk/java/modules/kernel/src/org/apache/axis2/transport/nhttp/PlainClientIOEventDispatch.java
    webservices/axis2/trunk/java/modules/kernel/src/org/apache/axis2/transport/nhttp/PlainServerIOEventDispatch.java
    webservices/axis2/trunk/java/modules/kernel/src/org/apache/axis2/transport/nhttp/SSLClientIOEventDispatch.java
    webservices/axis2/trunk/java/modules/kernel/src/org/apache/axis2/transport/nhttp/SSLServerIOEventDispatch.java
    webservices/axis2/trunk/java/modules/kernel/src/org/apache/axis2/transport/nhttp/ServerHandler.java
    webservices/axis2/trunk/java/modules/kernel/src/org/apache/axis2/transport/nhttp/ServerWorker.java
    webservices/axis2/trunk/java/modules/kernel/src/org/apache/axis2/transport/nhttp/Util.java
    webservices/axis2/trunk/java/modules/kernel/src/org/apache/axis2/transport/nhttp/util/
    webservices/axis2/trunk/java/modules/kernel/src/org/apache/axis2/transport/nhttp/util/BackportWorkerPool.java
    webservices/axis2/trunk/java/modules/kernel/src/org/apache/axis2/transport/nhttp/util/NativeWorkerPool.java
    webservices/axis2/trunk/java/modules/kernel/src/org/apache/axis2/transport/nhttp/util/PipeImpl.java
    webservices/axis2/trunk/java/modules/kernel/src/org/apache/axis2/transport/nhttp/util/WorkerPool.java
    webservices/axis2/trunk/java/modules/kernel/src/org/apache/axis2/transport/nhttp/util/WorkerPoolFactory.java
Modified:
    webservices/axis2/trunk/java/modules/kernel/pom.xml
    webservices/axis2/trunk/java/modules/parent/pom.xml

Modified: webservices/axis2/trunk/java/modules/kernel/pom.xml
URL: http://svn.apache.org/viewvc/webservices/axis2/trunk/java/modules/kernel/pom.xml?view=diff&rev=549457&r1=549456&r2=549457
==============================================================================
--- webservices/axis2/trunk/java/modules/kernel/pom.xml (original)
+++ webservices/axis2/trunk/java/modules/kernel/pom.xml Thu Jun 21 05:21:46 2007
@@ -43,6 +43,14 @@
 			<groupId>org.apache.httpcomponents</groupId>
 			<artifactId>jakarta-httpcore</artifactId>
 		</dependency>
+               <dependency>
+                        <groupId>org.apache.httpcomponents</groupId>
+                        <artifactId>jakarta-httpcore-nio</artifactId>
+                </dependency>
+                <!--<dependency>
+                        <groupId>org.apache.httpcomponents</groupId>
+                        <artifactId>jakarta-httpcore-niossl</artifactId>
+                </dependency>-->
 		<dependency>
 			<groupId>wsdl4j</groupId>
 			<artifactId>wsdl4j</artifactId>

Added: webservices/axis2/trunk/java/modules/kernel/src/org/apache/axis2/transport/nhttp/Axis2HttpRequest.java
URL: http://svn.apache.org/viewvc/webservices/axis2/trunk/java/modules/kernel/src/org/apache/axis2/transport/nhttp/Axis2HttpRequest.java?view=auto&rev=549457
==============================================================================
--- webservices/axis2/trunk/java/modules/kernel/src/org/apache/axis2/transport/nhttp/Axis2HttpRequest.java (added)
+++ webservices/axis2/trunk/java/modules/kernel/src/org/apache/axis2/transport/nhttp/Axis2HttpRequest.java Thu Jun 21 05:21:46 2007
@@ -0,0 +1,181 @@
+/*
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.axis2.transport.nhttp;
+
+import org.apache.axis2.addressing.EndpointReference;
+import org.apache.axis2.context.MessageContext;
+import org.apache.axis2.AxisFault;
+import org.apache.axis2.transport.nhttp.util.PipeImpl;
+import org.apache.axis2.transport.http.HTTPConstants;
+import org.apache.axis2.transport.MessageFormatter;
+import org.apache.axis2.transport.TransportUtils;
+import org.apache.http.*;
+import org.apache.http.protocol.HTTP;
+import org.apache.http.entity.BasicHttpEntity;
+import org.apache.http.message.HttpPost;
+import org.apache.axiom.om.OMOutputFormat;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import javax.xml.stream.XMLStreamException;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.nio.channels.Pipe;
+import java.nio.channels.Channels;
+import java.nio.channels.ReadableByteChannel;
+import java.util.Map;
+import java.util.Iterator;
+
+/**
+ * Represents an outgoing Axis2 HTTP/s request. It holds the EPR of the destination, the
+ * Axis2 MessageContext to be sent, an HttpHost object which captures information about the
+ * destination, and a Pipe used to write the message stream to the destination
+ */
+public class Axis2HttpRequest {
+
+    private static final Log log = LogFactory.getLog(Axis2HttpRequest.class);
+
+    /** the EPR of the destination */
+    private EndpointReference epr = null;
+    /** the HttpHost that contains the HTTP connection information */
+    private HttpHost httpHost = null;
+    /** the message context being sent */
+    private MessageContext msgContext = null;
+    /** the Pipe which facilitates the serialization output to be written to the channel */
+    private PipeImpl pipe = null;
+    /** The Axis2 MessageFormatter that will ensure proper serialization as per Axis2 semantics */
+    MessageFormatter messageFormatter = null;
+    /** The OM Output format holder */
+    OMOutputFormat format = null;
+
+    public Axis2HttpRequest(EndpointReference epr, HttpHost httpHost, MessageContext msgContext) {
+        this.epr = epr;
+        this.httpHost = httpHost;
+        this.msgContext = msgContext;
+        this.format = Util.getOMOutputFormat(msgContext);
+        try {
+            messageFormatter = TransportUtils.getMessageFormatter(msgContext);
+        } catch (AxisFault axisFault) {
+            log.error("Cannot find a suitable MessageFormatter : " + axisFault.getMessage());
+        }
+        try {
+            this.pipe = new PipeImpl();
+        } catch (IOException e) {
+            log.error("Error creating pipe to write message body");
+        }
+    }
+
+    public EndpointReference getEpr() {
+        return epr;
+    }
+
+    public HttpHost getHttpHost() {
+        return httpHost;
+    }
+
+    public MessageContext getMsgContext() {
+        return msgContext;
+    }
+
+    /**
+     * Create and return a new HttpPost request to the destination EPR
+     * @return the HttpRequest to be sent out
+     */
+    public HttpRequest getRequest() throws IOException {
+        HttpPost httpRequest = new HttpPost(epr.getAddress());
+        httpRequest.setEntity(new BasicHttpEntity());
+
+        // set any transport headers
+        Object o = msgContext.getProperty(MessageContext.TRANSPORT_HEADERS);
+        if (o != null && o instanceof Map) {
+            Map headers = (Map) o;
+            Iterator iter = headers.keySet().iterator();
+            while (iter.hasNext()) {
+                Object header = iter.next();
+                Object value = headers.get(header);
+                if (header instanceof String && value != null && value instanceof String) {
+                    httpRequest.setHeader((String) header, (String) value);
+                }
+            }
+        }
+
+        // if the message is SOAP 11 (for which a SOAPAction is *required*), and
+        // the msg context has a SOAPAction or a WSA-Action (give pref to SOAPAction)
+        // use that over any transport header that may be available
+        String soapAction = msgContext.getSoapAction();
+        if (soapAction == null) {
+            soapAction = msgContext.getWSAAction();
+        }
+        if (soapAction == null) {
+            msgContext.getAxisOperation().getInputAction();
+        }
+
+        if (msgContext.isSOAP11() && soapAction != null &&
+            soapAction.length() > 0) {
+            Header existingHeader =
+                httpRequest.getFirstHeader(HTTPConstants.HEADER_SOAP_ACTION);
+            if (existingHeader != null) {
+                httpRequest.removeHeader(existingHeader);
+            }
+            httpRequest.setHeader(HTTPConstants.HEADER_SOAP_ACTION,
+                soapAction);
+        }
+
+
+        httpRequest.setHeader(
+            HTTP.CONTENT_TYPE,
+            messageFormatter.getContentType(msgContext, format, msgContext.getSoapAction()));
+
+        return httpRequest;
+    }
+
+    /**
+     * Return the source channel of the pipe that bridges the serialized output to the socket
+     * @return source channel to read serialized message contents
+     */
+    public ReadableByteChannel getSourceChannel() {
+        log.debug("get source channel of the pipe on which the outgoing response is written");
+        return pipe.source();
+    }
+
+    /**
+     * Start streaming the message into the Pipe, so that the contents could be read off the source
+     * channel returned by getSourceChannel()
+     * @throws AxisFault on error
+     */
+    public void streamMessageContents() throws AxisFault {
+
+        log.debug("start streaming outgoing http request");
+        OutputStream out = Channels.newOutputStream(pipe.sink());
+
+        messageFormatter.writeTo(msgContext, format, out, true);
+            try {
+            out.flush();
+            out.close();
+        } catch (IOException e) {
+            handleException("Error closing outgoing message stream", e);
+        }
+    }
+
+    // -------------- utility methods -------------
+    private void handleException(String msg, Exception e) throws AxisFault {
+        log.error(msg, e);
+        throw new AxisFault(msg, e);
+    }
+}

Added: webservices/axis2/trunk/java/modules/kernel/src/org/apache/axis2/transport/nhttp/ClientHandler.java
URL: http://svn.apache.org/viewvc/webservices/axis2/trunk/java/modules/kernel/src/org/apache/axis2/transport/nhttp/ClientHandler.java?view=auto&rev=549457
==============================================================================
--- webservices/axis2/trunk/java/modules/kernel/src/org/apache/axis2/transport/nhttp/ClientHandler.java (added)
+++ webservices/axis2/trunk/java/modules/kernel/src/org/apache/axis2/transport/nhttp/ClientHandler.java Thu Jun 21 05:21:46 2007
@@ -0,0 +1,404 @@
+/*
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.axis2.transport.nhttp;
+
+import org.apache.http.nio.NHttpClientHandler;
+import org.apache.http.nio.NHttpClientConnection;
+import org.apache.http.nio.ContentDecoder;
+import org.apache.http.nio.ContentEncoder;
+import org.apache.http.params.HttpParams;
+import org.apache.http.*;
+import org.apache.http.entity.BasicHttpEntity;
+import org.apache.http.impl.DefaultConnectionReuseStrategy;
+import org.apache.http.protocol.*;
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.axis2.context.MessageContext;
+import org.apache.axis2.transport.nhttp.util.PipeImpl;
+import org.apache.axis2.transport.nhttp.util.WorkerPool;
+import org.apache.axis2.transport.nhttp.util.WorkerPoolFactory;
+import org.apache.axis2.description.WSDL2Constants;
+import org.apache.axis2.engine.MessageReceiver;
+import org.apache.axis2.wsdl.WSDLConstants;
+import org.apache.axis2.addressing.AddressingConstants;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.axiom.soap.SOAP11Constants;
+import org.apache.axiom.soap.SOAP12Constants;
+import org.apache.axiom.soap.SOAPFactory;
+
+import java.nio.ByteBuffer;
+import java.nio.channels.Channels;
+import java.nio.channels.ReadableByteChannel;
+import java.nio.channels.WritableByteChannel;
+import java.io.IOException;
+
+/**
+ * The client connection handler. An instance of this class is used by each IOReactor, to
+ * process every connection. Hence this class should not store any data related to a single
+ * connection - as this is being shared.
+ */
+public class ClientHandler implements NHttpClientHandler {
+
+    private static final Log log = LogFactory.getLog(ClientHandler.class);
+
+    /** the HTTP protocol parameters to adhere to for outgoing messages */
+    private final HttpParams params;
+    /** the HttpProcessor for response messages received */
+    private final HttpProcessor httpProcessor;
+    /** the connection re-use strategy */
+    private final ConnectionReuseStrategy connStrategy;
+
+    /** the Axis2 configuration context */
+    ConfigurationContext cfgCtx = null;
+    /** the nhttp configuration */
+    private NHttpConfiguration cfg = null;
+
+    private WorkerPool workerPool = null;
+
+    private static final String REQUEST_BUFFER = "request-buffer";
+    private static final String RESPONSE_BUFFER = "response-buffer";
+    private static final String OUTGOING_MESSAGE_CONTEXT = "axis2_message_context";
+    private static final String REQUEST_SOURCE_CHANNEL = "request-source-channel";
+    private static final String RESPONSE_SINK_CHANNEL = "request-sink-channel";
+
+    private static final String CONTENT_TYPE = "Content-Type";
+
+    /**
+     * Create an instance of this client connection handler using the Axis2 configuration
+     * context and Http protocol parameters given
+     * @param cfgCtx the Axis2 configuration context
+     * @param params the Http protocol parameters to adhere to
+     */
+    public ClientHandler(final ConfigurationContext cfgCtx, final HttpParams params) {
+        super();
+        this.cfgCtx = cfgCtx;
+        this.params = params;
+        this.httpProcessor = getHttpProcessor();
+        this.connStrategy = new DefaultConnectionReuseStrategy();
+
+        this.cfg = NHttpConfiguration.getInstance();
+        workerPool = WorkerPoolFactory.getWorkerPool(
+            cfg.getClientCoreThreads(),
+            cfg.getClientMaxThreads(),
+            cfg.getClientKeepalive(),
+            cfg.getClientQueueLen(),
+            "Client Worker thread group", "HttpClientWorker");
+    }
+
+    public void requestReady(final NHttpClientConnection conn) {
+        // The connection is ready for submission of a new request
+    }
+
+    /**
+     * Submit a new request over an already established connection, which has been 
+     * 'kept alive'
+     * @param conn the connection to use to send the request, which has been kept open
+     * @param axis2Req the new request
+     */
+    public void submitRequest(final NHttpClientConnection conn, Axis2HttpRequest axis2Req) {
+
+        try {
+            HttpContext context = conn.getContext();
+
+            context.setAttribute(HttpExecutionContext.HTTP_CONNECTION, conn);
+            context.setAttribute(HttpExecutionContext.HTTP_TARGET_HOST, axis2Req.getHttpHost());
+
+            context.setAttribute(OUTGOING_MESSAGE_CONTEXT, axis2Req.getMsgContext());
+            context.setAttribute(REQUEST_SOURCE_CHANNEL, axis2Req.getSourceChannel());
+
+            HttpRequest request = axis2Req.getRequest();
+            request.getParams().setDefaults(this.params);
+            this.httpProcessor.process(request, context);
+
+            conn.submitRequest(request);
+            context.setAttribute(HttpExecutionContext.HTTP_REQUEST, request);
+
+        } catch (IOException e) {
+            handleException("I/O Error : " + e.getMessage(), e, conn);
+        } catch (HttpException e) {
+            handleException("Unexpected HTTP protocol error: " + e.getMessage(), e, conn);
+        }
+    }
+
+    /**
+     * Invoked when the destination is connected
+     * @param conn the connection being processed
+     * @param attachment the attachment set previously
+     */
+    public void connected(final NHttpClientConnection conn, final Object attachment) {
+        try {
+            HttpContext context = conn.getContext();
+            Axis2HttpRequest axis2Req = (Axis2HttpRequest) attachment;
+
+            context.setAttribute(HttpExecutionContext.HTTP_CONNECTION, conn);
+            context.setAttribute(HttpExecutionContext.HTTP_TARGET_HOST, axis2Req.getHttpHost());
+
+            // allocate temporary buffers to process this request
+            context.setAttribute(REQUEST_BUFFER, ByteBuffer.allocate(cfg.getBufferZise()));
+            context.setAttribute(RESPONSE_BUFFER, ByteBuffer.allocate(cfg.getBufferZise()));
+
+            context.setAttribute(OUTGOING_MESSAGE_CONTEXT, axis2Req.getMsgContext());
+            context.setAttribute(REQUEST_SOURCE_CHANNEL, axis2Req.getSourceChannel());
+
+            HttpRequest request = axis2Req.getRequest();
+            request.getParams().setDefaults(this.params);
+            this.httpProcessor.process(request, context);
+
+            conn.submitRequest(request);
+            context.setAttribute(HttpExecutionContext.HTTP_REQUEST, request);
+
+        } catch (IOException e) {
+            handleException("I/O Error : " + e.getMessage(), e, conn);
+        } catch (HttpException e) {
+            handleException("Unexpected HTTP protocol error: " + e.getMessage(), e, conn);
+        }
+    }
+
+    public void closed(final NHttpClientConnection conn) {
+        log.trace("Connection closed");
+    }
+
+    /**
+     * Handle connection timeouts by shutting down the connections
+     * @param conn the connection being processed
+     */
+    public void timeout(final NHttpClientConnection conn) {
+        log.debug("Connection Timeout");
+        shutdownConnection(conn);
+    }
+
+    /**
+     * Handle Http protocol violations encountered while reading from underlying channels
+     * @param conn the connection being processed
+     * @param e the exception encountered
+     */
+    public void exception(final NHttpClientConnection conn, final HttpException e) {
+        log.error("HTTP protocol violation : " + e.getMessage());
+        shutdownConnection(conn);
+    }
+
+    /**
+     * Handle IO errors while reading or writing to underlying channels
+     * @param conn the connection being processed
+     * @param e the exception encountered
+     */
+    public void exception(final NHttpClientConnection conn, final IOException e) {
+        log.error("I/O error : " + e.getMessage(), e);
+        shutdownConnection(conn);
+    }
+
+    /**
+     * Process ready input (i.e. response from remote server)
+     * @param conn connection being processed
+     * @param decoder the content decoder in use
+     */
+    public void inputReady(final NHttpClientConnection conn, final ContentDecoder decoder) {
+        HttpContext context = conn.getContext();
+        HttpResponse response = conn.getHttpResponse();
+        WritableByteChannel sink = (WritableByteChannel) context.getAttribute(RESPONSE_SINK_CHANNEL);
+        ByteBuffer inbuf = (ByteBuffer) context.getAttribute(REQUEST_BUFFER);
+
+        try {
+            while (decoder.read(inbuf) > 0) {
+                inbuf.flip();
+                sink.write(inbuf);
+                inbuf.compact();
+            }
+
+            if (decoder.isCompleted()) {
+                if (sink != null) sink.close();
+                if (!connStrategy.keepAlive(response, context)) {
+                    conn.close();
+                } else {
+                    ConnectionPool.release(conn);
+                }
+            }
+
+        } catch (IOException e) {
+            handleException("I/O Error : " + e.getMessage(), e, conn);
+        }
+    }
+
+    /**
+     * Process ready output (i.e. write request to remote server)
+     * @param conn the connection being processed
+     * @param encoder the encoder in use
+     */
+    public void outputReady(final NHttpClientConnection conn, final ContentEncoder encoder) {
+        HttpContext context = conn.getContext();
+        HttpResponse response = conn.getHttpResponse();
+
+        ReadableByteChannel source = (ReadableByteChannel) context.getAttribute(REQUEST_SOURCE_CHANNEL);
+        ByteBuffer outbuf = (ByteBuffer) context.getAttribute(RESPONSE_BUFFER);
+
+        try {
+            int bytesRead = source.read(outbuf);
+            if (bytesRead == -1) {
+                encoder.complete();
+            } else {
+                outbuf.flip();
+                encoder.write(outbuf);
+                outbuf.compact();
+            }
+
+            if (encoder.isCompleted()) {
+                source.close();
+            }
+
+        } catch (IOException e) {
+            handleException("I/O Error : " + e.getMessage(), e, conn);
+        }
+    }
+
+    /**
+     * Process a response received for the request sent out
+     * @param conn the connection being processed
+     */
+    public void responseReceived(final NHttpClientConnection conn) {
+        HttpContext context = conn.getContext();
+        HttpResponse response = conn.getHttpResponse();
+
+        switch (response.getStatusLine().getStatusCode()) {
+            case HttpStatus.SC_ACCEPTED : {
+                log.debug("Received a 202 Accepted response");
+
+                // create a dummy message with an empty SOAP envelope and a property
+                // NhttpConstants.SC_ACCEPTED set to Boolean.TRUE to indicate this is a
+                // placeholder message for the transport to send a HTTP 202 to the
+                // client. Should / would be ignored by any transport other than
+                // nhttp. For example, JMS would not send a reply message for one-way
+                // operations.
+                MessageContext outMsgCtx =
+                    (MessageContext) context.getAttribute(OUTGOING_MESSAGE_CONTEXT);
+                MessageReceiver mr = outMsgCtx.getAxisOperation().getMessageReceiver();
+
+                try {
+                    MessageContext responseMsgCtx = outMsgCtx.getOperationContext().
+                        getMessageContext(WSDL2Constants.MESSAGE_LABEL_IN);
+                    if (responseMsgCtx == null) {
+                        // to support Sandesha.. however, this means that we received a 202 accepted
+                        // for an out-only , for which we do not need a dummy message anyway
+                        return;
+                    }
+                    responseMsgCtx.setServerSide(true);
+                    responseMsgCtx.setDoingREST(outMsgCtx.isDoingREST());
+                    responseMsgCtx.setProperty(MessageContext.TRANSPORT_IN,
+                        outMsgCtx.getProperty(MessageContext.TRANSPORT_IN));
+                    responseMsgCtx.setTransportIn(outMsgCtx.getTransportIn());
+                    responseMsgCtx.setTransportOut(outMsgCtx.getTransportOut());
+
+                    responseMsgCtx.setAxisMessage(outMsgCtx.getAxisOperation().
+                        getMessage(WSDLConstants.MESSAGE_LABEL_IN_VALUE));
+                    responseMsgCtx.setOperationContext(outMsgCtx.getOperationContext());
+                    responseMsgCtx.setConfigurationContext(outMsgCtx.getConfigurationContext());
+                    responseMsgCtx.setTo(null);
+
+                    responseMsgCtx.setEnvelope(
+                        ((SOAPFactory)outMsgCtx.getEnvelope().getOMFactory()).getDefaultEnvelope());
+                    responseMsgCtx.setProperty(AddressingConstants.DISABLE_ADDRESSING_FOR_OUT_MESSAGES, Boolean.TRUE);
+                    responseMsgCtx.setProperty(NhttpConstants.SC_ACCEPTED, Boolean.TRUE);
+                    mr.receive(responseMsgCtx);
+
+                } catch (org.apache.axis2.AxisFault af) {
+                    log.error("Unable to report back 202 Accepted state to the message receiver", af);
+                }
+
+                return;
+            }
+            case HttpStatus.SC_INTERNAL_SERVER_ERROR : {
+                Header contentType = response.getFirstHeader(CONTENT_TYPE);
+                if (contentType != null &&
+                    (contentType.getValue().indexOf(SOAP11Constants.SOAP_11_CONTENT_TYPE) >= 0) ||
+                     contentType.getValue().indexOf(SOAP12Constants.SOAP_12_CONTENT_TYPE) >=0) {
+                    log.debug("Received an internal server error with a SOAP payload");
+                    processResponse(conn, context, response);
+                    return;
+                }
+                log.error("Received an internal server error : " +
+                    response.getStatusLine().getReasonPhrase());
+                return;
+            }
+            case HttpStatus.SC_OK : {
+                processResponse(conn, context, response);
+            }
+        }
+    }
+
+    /**
+     * Perform processing of the received response though Axis2
+     * @param conn
+     * @param context
+     * @param response
+     */
+    private void processResponse(final NHttpClientConnection conn, HttpContext context, HttpResponse response) {
+
+        try {
+            PipeImpl responsePipe = new PipeImpl();
+            context.setAttribute(RESPONSE_SINK_CHANNEL, responsePipe.sink());
+
+            BasicHttpEntity entity = new BasicHttpEntity();
+            if (response.getStatusLine().getHttpVersion().greaterEquals(HttpVersion.HTTP_1_1)) {
+                entity.setChunked(true);
+            }
+            response.setEntity(entity);
+            context.setAttribute(HttpContext.HTTP_RESPONSE, response);
+
+            workerPool.execute(
+                new ClientWorker(cfgCtx, Channels.newInputStream(responsePipe.source()), response,
+                    (MessageContext) context.getAttribute(OUTGOING_MESSAGE_CONTEXT)));
+
+        } catch (IOException e) {
+            handleException("I/O Error : " + e.getMessage(), e, conn);
+        }
+    }
+
+    // ----------- utility methods -----------
+
+    private void handleException(String msg, Exception e, NHttpClientConnection conn) {
+        log.error(msg, e);
+        if (conn != null) {
+            shutdownConnection(conn);
+        }
+    }
+
+    /**
+     * Shutdown the connection ignoring any IO errors during the process
+     * @param conn the connection to be shutdown
+     */
+    private void shutdownConnection(final HttpConnection conn) {
+        try {
+            conn.shutdown();
+        } catch (IOException ignore) {}
+    }
+
+    /**
+     * Return the HttpProcessor for requests
+     * @return the HttpProcessor that processes requests
+     */
+    private HttpProcessor getHttpProcessor() {
+        BasicHttpProcessor httpProcessor = new BasicHttpProcessor();
+        httpProcessor.addInterceptor(new RequestContent());
+        httpProcessor.addInterceptor(new RequestTargetHost());
+        httpProcessor.addInterceptor(new RequestConnControl());
+        httpProcessor.addInterceptor(new RequestUserAgent());
+        httpProcessor.addInterceptor(new RequestExpectContinue());
+        return httpProcessor;
+    }
+
+}

Added: webservices/axis2/trunk/java/modules/kernel/src/org/apache/axis2/transport/nhttp/ClientWorker.java
URL: http://svn.apache.org/viewvc/webservices/axis2/trunk/java/modules/kernel/src/org/apache/axis2/transport/nhttp/ClientWorker.java?view=auto&rev=549457
==============================================================================
--- webservices/axis2/trunk/java/modules/kernel/src/org/apache/axis2/transport/nhttp/ClientWorker.java (added)
+++ webservices/axis2/trunk/java/modules/kernel/src/org/apache/axis2/transport/nhttp/ClientWorker.java Thu Jun 21 05:21:46 2007
@@ -0,0 +1,190 @@
+/*
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.axis2.transport.nhttp;
+
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.axis2.context.MessageContext;
+import org.apache.axis2.description.WSDL2Constants;
+import org.apache.axis2.AxisFault;
+import org.apache.axis2.Constants;
+import org.apache.axis2.builder.BuilderUtil;
+import org.apache.axis2.wsdl.WSDLConstants;
+import org.apache.axis2.engine.AxisEngine;
+import org.apache.axis2.transport.TransportUtils;
+import org.apache.axiom.soap.SOAPEnvelope;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.http.HttpResponse;
+import org.apache.http.Header;
+import org.apache.http.protocol.HTTP;
+
+import javax.xml.stream.XMLStreamException;
+import java.io.InputStream;
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * Performs processing of the HTTP response received for our outgoing request. An instance of this
+ * class is created to process each unique response.
+ */
+public class ClientWorker implements Runnable {
+
+    private static final Log log = LogFactory.getLog(ClientWorker.class);
+
+    /** the Axis2 configuration context */
+    private ConfigurationContext cfgCtx = null;
+    /** the response message context that would be created */
+    private MessageContext responseMsgCtx = null;
+    /** the InputStream out of which the response body should be read */
+    private InputStream in = null;
+    /** the original request message context */
+    private MessageContext outMsgCtx = null;
+    /** the HttpResponse received */
+    private HttpResponse response = null;
+
+    /**
+     * Create the thread that would process the response message received for the outgoing message
+     * context sent
+     * @param cfgCtx the Axis2 configuration context
+     * @param in the InputStream to read the body of the response message received
+     * @param outMsgCtx the original outgoing message context (i.e. corresponding request)
+     */
+    public ClientWorker(ConfigurationContext cfgCtx, InputStream in,
+        HttpResponse response, MessageContext outMsgCtx) {
+
+        this.cfgCtx = cfgCtx;
+        this.in = in;
+        this.outMsgCtx = outMsgCtx;
+        this.response = response;
+
+        try {
+            responseMsgCtx = outMsgCtx.getOperationContext().
+                getMessageContext(WSDL2Constants.MESSAGE_LABEL_IN);
+        } catch (AxisFault af) {
+            log.error("Error getting IN message context from the operation context", af);
+            return;
+        }
+
+        // this conditional block is to support Sandesha, as it uses an out-in mep, but without
+        // creating the message context to write the response and adding it into the operation
+        // context, as it may get a 202 accepted or 200. So if the operation is complete ignore
+        // this message, else, create a new message context and handle this
+        if (responseMsgCtx == null && outMsgCtx.getOperationContext().isComplete()) {
+            log.debug("Error getting IN message context from the operation context. " +
+                "Possibly an RM terminate sequence message");
+            return;
+
+        } else {
+            if (responseMsgCtx == null) {
+                responseMsgCtx = new MessageContext();
+                responseMsgCtx.setOperationContext(outMsgCtx.getOperationContext());
+            }
+
+            responseMsgCtx.setServerSide(true);
+            responseMsgCtx.setDoingREST(outMsgCtx.isDoingREST());
+            responseMsgCtx.setProperty(MessageContext.TRANSPORT_IN, outMsgCtx
+                .getProperty(MessageContext.TRANSPORT_IN));
+            responseMsgCtx.setTransportIn(outMsgCtx.getTransportIn());
+            responseMsgCtx.setTransportOut(outMsgCtx.getTransportOut());
+
+            // set any transport headers received
+            Header[] headers = response.getAllHeaders();
+            if (headers != null && headers.length > 0) {
+                Map headerMap = new HashMap();
+                for (int i=0; i<headers.length; i++) {
+                    Header header = headers[i];
+                    headerMap.put(header.getName(), header.getValue());
+                }
+                responseMsgCtx.setProperty(MessageContext.TRANSPORT_HEADERS, headerMap);
+            }
+
+            responseMsgCtx.setAxisMessage(outMsgCtx.getOperationContext().getAxisOperation().
+                getMessage(WSDLConstants.MESSAGE_LABEL_IN_VALUE));
+            responseMsgCtx.setOperationContext(outMsgCtx.getOperationContext());
+            responseMsgCtx.setConfigurationContext(outMsgCtx.getConfigurationContext());
+            responseMsgCtx.setTo(null);
+        }
+    }
+
+    /**
+     * Process the received response through Axis2
+     */
+    public void run() {
+        // to support Sandesha.. if there isn't a response message context, we cannot read any
+        // response and populate it with the soap envelope
+        if (responseMsgCtx == null) {
+            return;
+        }
+
+        SOAPEnvelope envelope = null;
+        try {
+            String contentType = response.getFirstHeader(HTTP.CONTENT_TYPE).getValue();
+            String charSetEnc = BuilderUtil.getCharSetEncoding(contentType);
+            if (charSetEnc == null) {
+                charSetEnc = MessageContext.DEFAULT_CHAR_SET_ENCODING;
+            }
+
+            if (contentType.indexOf(HTTP.CHARSET_PARAM) > 0) {
+                responseMsgCtx.setProperty(Constants.Configuration.CHARACTER_SET_ENCODING, charSetEnc);
+            } else {
+                responseMsgCtx.setProperty(Constants.Configuration.CHARACTER_SET_ENCODING,
+                    MessageContext.DEFAULT_CHAR_SET_ENCODING);
+            }
+            // workaround for Axis2 TransportUtils.createSOAPMessage() issue, where a response
+            // of content type "text/xml" is thought to be REST if !MC.isServerSide(). This
+            // question is still under debate and due to the timelines, I am commiting this
+            // workaround as Axis2 1.2 is about to be released and Synapse 1.0
+            responseMsgCtx.setServerSide(false);
+            envelope = TransportUtils.createSOAPMessage(
+                responseMsgCtx,
+                in,
+                contentType);
+            responseMsgCtx.setServerSide(true);
+            responseMsgCtx.setEnvelope(envelope);
+
+        } catch (AxisFault af) {
+            log.error("Fault creating response SOAP envelope", af);
+            return;
+        } catch (XMLStreamException e) {
+            log.error("Error creating response SOAP envelope", e);
+        } catch (IOException e) {
+            log.error("Error closing input stream from which message was read", e);
+        }
+
+        AxisEngine engine = new AxisEngine(cfgCtx);
+        try {
+            engine.receive(responseMsgCtx);
+        } catch (AxisFault af) {
+            log.error("Fault processing response message through Axis2", af);
+        }
+
+        try {
+            if (in != null) {
+                in.close();
+            }
+        } catch (IOException ignore) {}
+    }
+
+    // -------------- utility methods -------------
+    private void handleException(String msg, Exception e) throws AxisFault {
+        log.error(msg, e);
+        throw new AxisFault(msg, e);
+    }
+}

Added: webservices/axis2/trunk/java/modules/kernel/src/org/apache/axis2/transport/nhttp/ConnectionPool.java
URL: http://svn.apache.org/viewvc/webservices/axis2/trunk/java/modules/kernel/src/org/apache/axis2/transport/nhttp/ConnectionPool.java?view=auto&rev=549457
==============================================================================
--- webservices/axis2/trunk/java/modules/kernel/src/org/apache/axis2/transport/nhttp/ConnectionPool.java (added)
+++ webservices/axis2/trunk/java/modules/kernel/src/org/apache/axis2/transport/nhttp/ConnectionPool.java Thu Jun 21 05:21:46 2007
@@ -0,0 +1,101 @@
+/*
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.axis2.transport.nhttp;
+
+import org.apache.http.nio.NHttpClientConnection;
+import org.apache.http.protocol.HttpExecutionContext;
+import org.apache.http.HttpHost;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import java.util.*;
+import java.io.IOException;
+
+public class ConnectionPool {
+
+    private static final Log log = LogFactory.getLog(ConnectionPool.class);
+
+    /** A map of available connections for reuse. The key selects the host+port of the
+     * connection and the value contains a List of available connections to destination
+     */
+    private static Map connMap = Collections.synchronizedMap(new HashMap());
+
+    public static NHttpClientConnection getConnection(String host, int port) {
+
+        String key = host + ":" + Integer.toString(port);
+        List connections = (List) connMap.get(key);
+
+        if (connections == null || connections.isEmpty()) {
+            if (log.isDebugEnabled()) {
+                log.debug("No connections available for reuse");
+            }
+            return null;
+
+        } else {
+            NHttpClientConnection conn = null;
+
+            synchronized (connections) {
+                while (!connections.isEmpty()) {
+                    conn = (NHttpClientConnection) connections.remove(0);
+
+                    if (conn.isOpen()) {
+                        if (log.isDebugEnabled()) {
+                            log.debug("A connection to host : " + host + " on port : " +
+                                port + " is available in the pool, and will be reused");
+                        }
+                        return conn;
+                    } else {
+                        if (log.isDebugEnabled()) {
+                            log.debug("closing stale connection");
+                        }
+                        try {
+                            conn.close();
+                        } catch (IOException ignore) {
+                        }
+                    }
+                }
+            }
+            return null;
+        }
+    }
+
+    public static void release(NHttpClientConnection conn) {
+
+        HttpHost host = (HttpHost) conn.getContext().getAttribute(
+            HttpExecutionContext.HTTP_TARGET_HOST);
+        String key = host.getHostName() + ":" + Integer.toString(host.getPort());
+
+        List connections = (List) connMap.get(key);
+        if (connections == null) {
+            synchronized(connMap) {
+                // use double locking to make sure
+                connections = (List) connMap.get(key);
+                if (connections == null) {
+                    connections = Collections.synchronizedList(new LinkedList());
+                    connMap.put(key, connections);
+                }
+            }
+        }
+
+        connections.add(conn);
+
+        log.debug("Released a connection to host: " + host.getHostName() + " on port : " +
+            host.getPort() + " to the connection pool of current size : " + connections.size());
+    }
+}

Added: webservices/axis2/trunk/java/modules/kernel/src/org/apache/axis2/transport/nhttp/HostnameVerifier.java
URL: http://svn.apache.org/viewvc/webservices/axis2/trunk/java/modules/kernel/src/org/apache/axis2/transport/nhttp/HostnameVerifier.java?view=auto&rev=549457
==============================================================================
--- webservices/axis2/trunk/java/modules/kernel/src/org/apache/axis2/transport/nhttp/HostnameVerifier.java (added)
+++ webservices/axis2/trunk/java/modules/kernel/src/org/apache/axis2/transport/nhttp/HostnameVerifier.java Thu Jun 21 05:21:46 2007
@@ -0,0 +1,575 @@
+/*
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.axis2.transport.nhttp;
+
+import javax.net.ssl.SSLException;
+import javax.net.ssl.SSLPeerUnverifiedException;
+import javax.net.ssl.SSLSession;
+import javax.net.ssl.SSLSocket;
+import java.io.IOException;
+import java.io.InputStream;
+import java.security.cert.Certificate;
+import java.security.cert.X509Certificate;
+import java.security.cert.CertificateParsingException;
+import java.util.*;
+
+/**
+ * ************************************************************************
+ * Copied from the not-yet-commons-ssl project at http://juliusdavies.ca/commons-ssl/
+ * As the above project is accepted into Apache and its JARs become available in
+ * the Maven 2 repos, we will have to switch to using the JARs instead
+ * ************************************************************************
+ * <p/>
+ * Interface for checking if a hostname matches the names stored inside the
+ * server's X.509 certificate.  Correctly implements
+ * javax.net.ssl.HostnameVerifier, but that interface is not recommended.
+ * Instead we added several check() methods that take SSLSocket,
+ * or X509Certificate, or ultimately (they all end up calling this one),
+ * String.  (It's easier to supply JUnit with Strings instead of mock
+ * SSLSession objects!)
+ * </p><p>Our check() methods throw exceptions if the name is
+ * invalid, whereas javax.net.ssl.HostnameVerifier just returns true/false.
+ * <p/>
+ * We provide the HostnameVerifier.DEFAULT, HostnameVerifier.STRICT, and
+ * HostnameVerifier.ALLOW_ALL implementations.  We also provide the more
+ * specialized HostnameVerifier.DEFAULT_AND_LOCALHOST, as well as
+ * HostnameVerifier.STRICT_IE6.  But feel free to define your own
+ * implementations!
+ * <p/>
+ * Inspired by Sebastian Hauer's original StrictSSLProtocolSocketFactory in the
+ * HttpClient "contrib" repository.
+ *
+ * @author Julius Davies
+ * @author <a href="mailto:hauer@psicode.com">Sebastian Hauer</a>
+ * @since 8-Dec-2006
+ */
+
+public interface HostnameVerifier extends javax.net.ssl.HostnameVerifier {
+
+    boolean verify(String host, SSLSession session);
+
+    void check(String host, SSLSocket ssl) throws IOException;
+
+    void check(String host, X509Certificate cert) throws SSLException;
+
+    void check(String host, String[] cns, String[] subjectAlts)
+        throws SSLException;
+
+    void check(String[] hosts, SSLSocket ssl) throws IOException;
+
+    void check(String[] hosts, X509Certificate cert) throws SSLException;
+
+
+    /**
+     * Checks to see if the supplied hostname matches any of the supplied CNs
+     * or "DNS" Subject-Alts.  Most implementations only look at the first CN,
+     * and ignore any additional CNs.  Most implementations do look at all of
+     * the "DNS" Subject-Alts. The CNs or Subject-Alts may contain wildcards
+     * according to RFC 2818.
+     *
+     * @param cns         CN fields, in order, as extracted from the X.509
+     *                    certificate.
+     * @param subjectAlts Subject-Alt fields of type 2 ("DNS"), as extracted
+     *                    from the X.509 certificate.
+     * @param hosts       The array of hostnames to verify.
+     * @throws SSLException If verification failed.
+     */
+    void check(String[] hosts, String[] cns, String[] subjectAlts)
+        throws SSLException;
+
+
+    /**
+     * The DEFAULT HostnameVerifier works the same way as Curl and Firefox.
+     * <p/>
+     * The hostname must match either the first CN, or any of the subject-alts.
+     * A wildcard can occur in the CN, and in any of the subject-alts.
+     * <p/>
+     * The only difference between DEFAULT and STRICT is that a wildcard (such
+     * as "*.foo.com") with DEFAULT matches all subdomains, including
+     * "a.b.foo.com".
+     */
+    public final static HostnameVerifier DEFAULT =
+        new AbstractVerifier() {
+            public final void check(final String[] hosts, final String[] cns,
+                final String[] subjectAlts)
+                throws SSLException {
+                check(hosts, cns, subjectAlts, false, false);
+            }
+
+            public final String toString() {
+                return "DEFAULT";
+            }
+        };
+
+
+    /**
+     * The DEFAULT_AND_LOCALHOST HostnameVerifier works like the DEFAULT
+     * one with one additional relaxation:  a host of "localhost",
+     * "localhost.localdomain", "127.0.0.1", "::1" will always pass, no matter
+     * what is in the server's certificate.
+     */
+    public final static HostnameVerifier DEFAULT_AND_LOCALHOST =
+        new AbstractVerifier() {
+            public final void check(final String[] hosts, final String[] cns,
+                final String[] subjectAlts)
+                throws SSLException {
+                if (isLocalhost(hosts[0])) {
+                    return;
+                }
+                check(hosts, cns, subjectAlts, false, false);
+            }
+
+            public final String toString() {
+                return "DEFAULT_AND_LOCALHOST";
+            }
+        };
+
+    /**
+     * The STRICT HostnameVerifier works the same way as java.net.URL in Sun
+     * Java 1.4, Sun Java 5, Sun Java 6.  It's also pretty close to IE6.
+     * This implementation appears to be compliant with RFC 2818 for dealing
+     * with wildcards.
+     * <p/>
+     * The hostname must match either the first CN, or any of the subject-alts.
+     * A wildcard can occur in the CN, and in any of the subject-alts.  The
+     * one divergence from IE6 is how we only check the first CN.  IE6 allows
+     * a match against any of the CNs present.  We decided to follow in
+     * Sun Java 1.4's footsteps and only check the first CN.
+     * <p/>
+     * A wildcard such as "*.foo.com" matches only subdomains in the same
+     * level, for example "a.foo.com".  It does not match deeper subdomains
+     * such as "a.b.foo.com".
+     */
+    public final static HostnameVerifier STRICT =
+        new AbstractVerifier() {
+            public final void check(final String[] host, final String[] cns,
+                final String[] subjectAlts)
+                throws SSLException {
+                check(host, cns, subjectAlts, false, true);
+            }
+
+            public final String toString() {
+                return "STRICT";
+            }
+        };
+
+    /**
+     * The STRICT_IE6 HostnameVerifier works just like the STRICT one with one
+     * minor variation:  the hostname can match against any of the CN's in the
+     * server's certificate, not just the first one.  This behaviour is
+     * identical to IE6's behaviour.
+     */
+    public final static HostnameVerifier STRICT_IE6 =
+        new AbstractVerifier() {
+            public final void check(final String[] host, final String[] cns,
+                final String[] subjectAlts)
+                throws SSLException {
+                check(host, cns, subjectAlts, true, true);
+            }
+
+            public final String toString() {
+                return "STRICT_IE6";
+            }
+        };
+
+    /**
+     * The ALLOW_ALL HostnameVerifier essentially turns hostname verification
+     * off.  This implementation is a no-op, and never throws the SSLException.
+     */
+    public final static HostnameVerifier ALLOW_ALL =
+        new AbstractVerifier() {
+            public final void check(final String[] host, final String[] cns,
+                final String[] subjectAlts) {
+                // Allow everything - so never blowup.
+            }
+
+            public final String toString() {
+                return "ALLOW_ALL";
+            }
+        };
+
+    abstract class AbstractVerifier implements HostnameVerifier {
+
+        /**
+         * This contains a list of 2nd-level domains that aren't allowed to
+         * have wildcards when combined with country-codes.
+         * For example: [*.co.uk].
+         * <p/>
+         * The [*.co.uk] problem is an interesting one.  Should we just hope
+         * that CA's would never foolishly allow such a certificate to happen?
+         * Looks like we're the only implementation guarding against this.
+         * Firefox, Curl, Sun Java 1.4, 5, 6 don't bother with this check.
+         */
+        private final static String[] BAD_COUNTRY_2LDS =
+            {"ac", "co", "com", "ed", "edu", "go", "gouv", "gov", "info",
+                "lg", "ne", "net", "or", "org"};
+
+        private final static String[] LOCALHOSTS = {"::1", "127.0.0.1",
+            "localhost",
+            "localhost.localdomain"};
+
+
+        static {
+            // Just in case developer forgot to manually sort the array.  :-)
+            Arrays.sort(BAD_COUNTRY_2LDS);
+            Arrays.sort(LOCALHOSTS);
+        }
+
+        protected AbstractVerifier() {
+        }
+
+        /**
+         * The javax.net.ssl.HostnameVerifier contract.
+         *
+         * @param host    'hostname' we used to create our socket
+         * @param session SSLSession with the remote server
+         * @return true if the host matched the one in the certificate.
+         */
+        public boolean verify(String host, SSLSession session) {
+            try {
+                Certificate[] certs = session.getPeerCertificates();
+                X509Certificate x509 = (X509Certificate) certs[0];
+                check(new String[]{host}, x509);
+                return true;
+            }
+            catch (SSLException e) {
+                return false;
+            }
+        }
+
+        public void check(String host, SSLSocket ssl) throws IOException {
+            check(new String[]{host}, ssl);
+        }
+
+        public void check(String host, X509Certificate cert)
+            throws SSLException {
+            check(new String[]{host}, cert);
+        }
+
+        public void check(String host, String[] cns, String[] subjectAlts)
+            throws SSLException {
+            check(new String[]{host}, cns, subjectAlts);
+        }
+
+        public void check(String host[], SSLSocket ssl)
+            throws IOException {
+            if (host == null) {
+                throw new NullPointerException("host to verify is null");
+            }
+
+            SSLSession session = ssl.getSession();
+            if (session == null) {
+                // In our experience this only happens under IBM 1.4.x when
+                // spurious (unrelated) certificates show up in the server'
+                // chain.  Hopefully this will unearth the real problem:
+                InputStream in = ssl.getInputStream();
+                in.available();
+                /*
+                  If you're looking at the 2 lines of code above because
+                  you're running into a problem, you probably have two
+                  options:
+
+                    #1.  Clean up the certificate chain that your server
+                         is presenting (e.g. edit "/etc/apache2/server.crt"
+                         or wherever it is your server's certificate chain
+                         is defined).
+
+                                               OR
+
+                    #2.   Upgrade to an IBM 1.5.x or greater JVM, or switch
+                          to a non-IBM JVM.
+                */
+
+                // If ssl.getInputStream().available() didn't cause an
+                // exception, maybe at least now the session is available?
+                session = ssl.getSession();
+                if (session == null) {
+                    // If it's still null, probably a startHandshake() will
+                    // unearth the real problem.
+                    ssl.startHandshake();
+
+                    // Okay, if we still haven't managed to cause an exception,
+                    // might as well go for the NPE.  Or maybe we're okay now?
+                    session = ssl.getSession();
+                }
+            }
+            Certificate[] certs;
+            try {
+                certs = session.getPeerCertificates();
+            } catch (SSLPeerUnverifiedException spue) {
+                InputStream in = ssl.getInputStream();
+                in.available();
+                // Didn't trigger anything interesting?  Okay, just throw
+                // original.
+                throw spue;
+            }
+            X509Certificate x509 = (X509Certificate) certs[0];
+            check(host, x509);
+        }
+
+        public void check(String[] host, X509Certificate cert)
+            throws SSLException {
+
+            String[] cns = Certificates.getCNs(cert);
+            String[] subjectAlts = Certificates.getDNSSubjectAlts(cert);
+            check(host, cns, subjectAlts);
+
+        }
+
+        public void check(final String[] hosts, final String[] cns,
+            final String[] subjectAlts, final boolean ie6,
+            final boolean strictWithSubDomains)
+            throws SSLException {
+            // Build up lists of allowed hosts For logging/debugging purposes.
+            StringBuffer buf = new StringBuffer(32);
+            buf.append('<');
+            for (int i = 0; i < hosts.length; i++) {
+                String h = hosts[i];
+                h = h != null ? h.trim().toLowerCase() : "";
+                hosts[i] = h;
+                if (i > 0) {
+                    buf.append('/');
+                }
+                buf.append(h);
+            }
+            buf.append('>');
+            String hostnames = buf.toString();
+            // Build the list of names we're going to check.  Our DEFAULT and
+            // STRICT implementations of the HostnameVerifier only use the
+            // first CN provided.  All other CNs are ignored.
+            // (Firefox, wget, curl, Sun Java 1.4, 5, 6 all work this way).
+            TreeSet names = new TreeSet();
+            if (cns != null && cns.length > 0 && cns[0] != null) {
+                names.add(cns[0]);
+                if (ie6) {
+                    for (int i = 1; i < cns.length; i++) {
+                        names.add(cns[i]);
+                    }
+                }
+            }
+            if (subjectAlts != null) {
+                for (int i = 0; i < subjectAlts.length; i++) {
+                    if (subjectAlts[i] != null) {
+                        names.add(subjectAlts[i]);
+                    }
+                }
+            }
+            if (names.isEmpty()) {
+                String msg = "Certificate for " + hosts[0] + " doesn't contain CN or DNS subjectAlt";
+                throw new SSLException(msg);
+            }
+
+            // StringBuffer for building the error message.
+            buf = new StringBuffer();
+
+            boolean match = false;
+            out:
+            for (Iterator it = names.iterator(); it.hasNext();) {
+                // Don't trim the CN, though!
+                String cn = (String) it.next();
+                cn = cn.toLowerCase();
+                // Store CN in StringBuffer in case we need to report an error.
+                buf.append(" <");
+                buf.append(cn);
+                buf.append('>');
+                if (it.hasNext()) {
+                    buf.append(" OR");
+                }
+
+                // The CN better have at least two dots if it wants wildcard
+                // action.  It also can't be [*.co.uk] or [*.co.jp] or
+                // [*.org.uk], etc...
+                boolean doWildcard = cn.startsWith("*.") &&
+                    cn.lastIndexOf('.') >= 0 &&
+                    !isIP4Address(cn) &&
+                    acceptableCountryWildcard(cn);
+
+                for (int i = 0; i < hosts.length; i++) {
+                    final String hostName = hosts[i].trim().toLowerCase();
+                    if (doWildcard) {
+                        match = hostName.endsWith(cn.substring(1));
+                        if (match && strictWithSubDomains) {
+                            // If we're in strict mode, then [*.foo.com] is not
+                            // allowed to match [a.b.foo.com]
+                            match = countDots(hostName) == countDots(cn);
+                        }
+                    } else {
+                        match = hostName.equals(cn);
+                    }
+                    if (match) {
+                        break out;
+                    }
+                }
+            }
+            if (!match) {
+                throw new SSLException("hostname in certificate didn't match: " + hostnames + " !=" + buf);
+            }
+        }
+
+        public static boolean isIP4Address(final String cn) {
+            boolean isIP4 = true;
+            String tld = cn;
+            int x = cn.lastIndexOf('.');
+            // We only bother analyzing the characters after the final dot
+            // in the name.
+            if (x >= 0 && x + 1 < cn.length()) {
+                tld = cn.substring(x + 1);
+            }
+            for (int i = 0; i < tld.length(); i++) {
+                if (!Character.isDigit(tld.charAt(0))) {
+                    isIP4 = false;
+                    break;
+                }
+            }
+            return isIP4;
+        }
+
+        public static boolean acceptableCountryWildcard(final String cn) {
+            int cnLen = cn.length();
+            if (cnLen >= 7 && cnLen <= 9) {
+                // Look for the '.' in the 3rd-last position:
+                if (cn.charAt(cnLen - 3) == '.') {
+                    // Trim off the [*.] and the [.XX].
+                    String s = cn.substring(2, cnLen - 3);
+                    // And test against the sorted array of bad 2lds:
+                    int x = Arrays.binarySearch(BAD_COUNTRY_2LDS, s);
+                    return x < 0;
+                }
+            }
+            return true;
+        }
+
+        public static boolean isLocalhost(String host) {
+            host = host != null ? host.trim().toLowerCase() : "";
+            if (host.startsWith("::1")) {
+                int x = host.lastIndexOf('%');
+                if (x >= 0) {
+                    host = host.substring(0, x);
+                }
+            }
+            int x = Arrays.binarySearch(LOCALHOSTS, host);
+            return x >= 0;
+        }
+
+        /**
+         * Counts the number of dots "." in a string.
+         *
+         * @param s string to count dots from
+         * @return number of dots
+         */
+        public static int countDots(final String s) {
+            int count = 0;
+            for (int i = 0; i < s.length(); i++) {
+                if (s.charAt(i) == '.') {
+                    count++;
+                }
+            }
+            return count;
+        }
+    }
+
+    class Certificates {
+        public static String[] getCNs(X509Certificate cert) {
+            LinkedList cnList = new LinkedList();
+            /*
+           Sebastian Hauer's original StrictSSLProtocolSocketFactory used
+           getName() and had the following comment:
+
+              Parses a X.500 distinguished name for the value of the
+              "Common Name" field.  This is done a bit sloppy right
+              now and should probably be done a bit more according to
+              <code>RFC 2253</code>.
+
+            I've noticed that toString() seems to do a better job than
+            getName() on these X500Principal objects, so I'm hoping that
+            addresses Sebastian's concern.
+
+            For example, getName() gives me this:
+            1.2.840.113549.1.9.1=#16166a756c6975736461766965734063756362632e636f6d
+
+            whereas toString() gives me this:
+            EMAILADDRESS=juliusdavies@cucbc.com
+
+            Looks like toString() even works with non-ascii domain names!
+            I tested it with "&#x82b1;&#x5b50;.co.jp" and it worked fine.
+           */
+            String subjectPrincipal = cert.getSubjectX500Principal().toString();
+            StringTokenizer st = new StringTokenizer(subjectPrincipal, ",");
+            while (st.hasMoreTokens()) {
+                String tok = st.nextToken();
+                int x = tok.indexOf("CN=");
+                if (x >= 0) {
+                    cnList.add(tok.substring(x + 3));
+                }
+            }
+            if (!cnList.isEmpty()) {
+                String[] cns = new String[cnList.size()];
+                cnList.toArray(cns);
+                return cns;
+            } else {
+                return null;
+            }
+        }
+
+        /**
+         * Extracts the array of SubjectAlt DNS names from an X509Certificate.
+         * Returns null if there aren't any.
+         * <p/>
+         * Note:  Java doesn't appear able to extract international characters
+         * from the SubjectAlts.  It can only extract international characters
+         * from the CN field.
+         * <p/>
+         * (Or maybe the version of OpenSSL I'm using to test isn't storing the
+         * international characters correctly in the SubjectAlts?).
+         *
+         * @param cert X509Certificate
+         * @return Array of SubjectALT DNS names stored in the certificate.
+         */
+        public static String[] getDNSSubjectAlts(X509Certificate cert) {
+            LinkedList subjectAltList = new LinkedList();
+            Collection c = null;
+            try {
+                c = cert.getSubjectAlternativeNames();
+            }
+            catch (CertificateParsingException cpe) {
+                // Should probably log.debug() this?
+                cpe.printStackTrace();
+            }
+            if (c != null) {
+                Iterator it = c.iterator();
+                while (it.hasNext()) {
+                    List list = (List) it.next();
+                    int type = ((Integer) list.get(0)).intValue();
+                    // If type is 2, then we've got a dNSName
+                    if (type == 2) {
+                        String s = (String) list.get(1);
+                        subjectAltList.add(s);
+                    }
+                }
+            }
+            if (!subjectAltList.isEmpty()) {
+                String[] subjectAlts = new String[subjectAltList.size()];
+                subjectAltList.toArray(subjectAlts);
+                return subjectAlts;
+            } else {
+                return null;
+            }
+        }
+    }
+}

Added: webservices/axis2/trunk/java/modules/kernel/src/org/apache/axis2/transport/nhttp/HttpCoreNIOListener.java
URL: http://svn.apache.org/viewvc/webservices/axis2/trunk/java/modules/kernel/src/org/apache/axis2/transport/nhttp/HttpCoreNIOListener.java?view=auto&rev=549457
==============================================================================
--- webservices/axis2/trunk/java/modules/kernel/src/org/apache/axis2/transport/nhttp/HttpCoreNIOListener.java (added)
+++ webservices/axis2/trunk/java/modules/kernel/src/org/apache/axis2/transport/nhttp/HttpCoreNIOListener.java Thu Jun 21 05:21:46 2007
@@ -0,0 +1,266 @@
+/*
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.axis2.transport.nhttp;
+
+import java.io.IOException;
+import java.io.InterruptedIOException;
+import java.net.InetSocketAddress;
+import java.net.UnknownHostException;
+
+import javax.net.ssl.SSLContext;
+
+import org.apache.axis2.AxisFault;
+import org.apache.axis2.addressing.EndpointReference;
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.axis2.context.SessionContext;
+import org.apache.axis2.context.MessageContext;
+import org.apache.axis2.description.Parameter;
+import org.apache.axis2.description.TransportInDescription;
+import org.apache.axis2.transport.TransportListener;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.http.impl.nio.reactor.DefaultListeningIOReactor;
+//import org.apache.http.impl.nio.reactor.SSLIOSessionHandler;
+import org.apache.http.nio.NHttpServiceHandler;
+import org.apache.http.nio.reactor.IOEventDispatch;
+import org.apache.http.nio.reactor.ListeningIOReactor;
+import org.apache.http.params.BasicHttpParams;
+import org.apache.http.params.HttpConnectionParams;
+import org.apache.http.params.HttpParams;
+import org.apache.http.params.HttpProtocolParams;
+
+/**
+ * NIO transport listener for Axis2 based on HttpCore and NIO extensions
+ */
+public class HttpCoreNIOListener implements TransportListener {
+
+    private static final Log log = LogFactory.getLog(HttpCoreNIOListener.class);
+
+    /** The Axis2 configuration context */
+    private ConfigurationContext cfgCtx;
+    /** The IOReactor */
+    private ListeningIOReactor ioReactor = null;
+
+    /** 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";
+    /** SSLContext if this listener is a SSL listener */
+    private SSLContext sslContext = null;
+    /** The SSL session handler that manages client authentication etc */
+//    private SSLIOSessionHandler sslIOSessionHandler = null;
+
+    /**
+     * configure and start the IO reactor on the specified port
+     * @param port port to start the listener on
+     */
+    private void startServerEngine(int port) {
+        HttpParams params = getServerParameters();
+        try {
+            ioReactor = new DefaultListeningIOReactor(
+                NHttpConfiguration.getInstance().getServerIOWorkers(), params);
+        } catch (IOException e) {
+            log.error("Error starting the IOReactor", e);
+        }
+
+        NHttpServiceHandler handler = new ServerHandler(cfgCtx, params, sslContext != null);
+        IOEventDispatch ioEventDispatch = getEventDispatch(
+            handler, sslContext, /*sslIOSessionHandler,*/ params);
+
+        try {
+            ioReactor.listen(new InetSocketAddress(port));
+            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("Listener Shutdown");
+    }
+
+    protected IOEventDispatch getEventDispatch(
+        NHttpServiceHandler handler, SSLContext sslContext, 
+        /*SSLIOSessionHandler sslioSessionHandler,*/ HttpParams params) {
+        return new PlainServerIOEventDispatch(handler, params);
+    }
+
+    /**
+     * get HTTP protocol parameters to which the listener must adhere to
+     * @return the applicable HTTP protocol parameters
+     */
+    private HttpParams getServerParameters() {
+        HttpParams params = new BasicHttpParams();
+        NHttpConfiguration cfg = NHttpConfiguration.getInstance();
+        params
+            .setIntParameter(HttpConnectionParams.SO_TIMEOUT,
+                cfg.getProperty(HttpConnectionParams.SO_TIMEOUT, 60000))
+            .setIntParameter(HttpConnectionParams.SOCKET_BUFFER_SIZE,
+                cfg.getProperty(HttpConnectionParams.SOCKET_BUFFER_SIZE, 8 * 1024))
+            .setBooleanParameter(HttpConnectionParams.STALE_CONNECTION_CHECK,
+                cfg.getProperty(HttpConnectionParams.STALE_CONNECTION_CHECK, 0) == 1)
+            .setBooleanParameter(HttpConnectionParams.TCP_NODELAY,
+                cfg.getProperty(HttpConnectionParams.TCP_NODELAY, 1) == 1)
+            .setParameter(HttpProtocolParams.ORIGIN_SERVER, "Synapse-HttpComponents-NIO");
+        return params;
+    }
+
+    /**
+     * Initialize the transport listener, and execute reactor in new seperate thread
+     * @param cfgCtx the Axis2 configuration context
+     * @param transprtIn the description of the http/s transport from Axis2 configuration
+     * @throws AxisFault on error
+     */
+    public void init(ConfigurationContext cfgCtx, TransportInDescription transprtIn) throws AxisFault {
+
+        this.cfgCtx = cfgCtx;
+        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'");
+            }
+        }
+
+        // is this an SSL listener?
+        sslContext = getSSLContext(transprtIn);
+        //sslIOSessionHandler = getSSLIOSessionHandler(transprtIn);
+
+        serviceEPRPrefix = getServiceEPRPrefix(cfgCtx, host, port);
+    }
+
+    /**
+     * Return the EPR prefix for services made available over this transport
+     * @return
+     */
+    protected String getServiceEPRPrefix(ConfigurationContext cfgCtx, String host, int port) {
+        return "http://" + host + (port == 80 ? "" : ":" + port) +
+            (!cfgCtx.getServiceContextPath().startsWith("/") ? "/" : "") +
+            cfgCtx.getServiceContextPath() +
+            (!cfgCtx.getServiceContextPath().endsWith("/") ? "/" : "");
+    }
+
+    /**
+     * Create the SSLContext to be used by this listener
+     * @param transportIn
+     * @return always null
+     */
+    protected SSLContext getSSLContext(TransportInDescription transportIn) throws AxisFault {
+        return null;
+    }
+
+    /**
+     * Create the SSL IO Session handler to be used by this listener
+     * @param transportIn
+     * @return always null
+     */
+//    protected SSLIOSessionHandler getSSLIOSessionHandler(TransportInDescription transportIn)
+//        throws AxisFault {
+//        return null;
+//    }
+
+    /**
+     * Start the transport listener on a new thread
+     * @throws AxisFault
+     */
+    public void start() throws AxisFault {
+        log.debug("Starting Listener...");
+        // start the Listener in a new seperate thread
+        Thread t = new Thread(new Runnable() {
+            public void run() {
+                try {
+                    startServerEngine(port);
+                } catch (Exception e) {
+                    e.printStackTrace();
+                }
+            }
+        }, "HttpCoreNIOListener");
+
+        t.start();
+        log.info((sslContext == null ? "HTTP" : "HTTPS") + " Listener starting on port : " + port);
+    }
+
+    /**
+     * Stop the listener
+     * @throws AxisFault on error
+     */
+    public void stop() throws AxisFault {
+        try {
+            ioReactor.shutdown();
+            log.info("Listener shut down");
+        } catch (IOException e) {
+            handleException("Error shutting down IOReactor", e);
+        }
+    }
+
+    /**
+     * Return the EPR for the given service (implements deprecated method temporarily)
+     */
+    public EndpointReference getEPRForService(String serviceName, String ip) throws AxisFault {
+        return new EndpointReference(serviceEPRPrefix + serviceName);
+    }
+
+    /**
+     * Return the EPRs for the given service over this transport
+     * @param serviceName name of the service
+     * @param ip IP address
+     * @return the EndpointReferences for this service over the transport
+     * @throws AxisFault on error
+     */
+    public EndpointReference[] getEPRsForService(String serviceName, String ip) throws AxisFault {
+        EndpointReference[] endpointReferences = new EndpointReference[1];
+        endpointReferences[0] = new EndpointReference(serviceEPRPrefix + serviceName);
+        return endpointReferences;
+    }
+
+    /**
+     * TODO: Return session context from transport, this is an improvement in axis2 1.2 and
+     * is not currently supported
+     * @param messageContext
+     * @return
+     */
+    public SessionContext getSessionContext(MessageContext messageContext) {
+        return null;
+    }
+
+    public void destroy() {
+        ioReactor = null;
+    }
+
+    // -------------- utility methods -------------
+    private void handleException(String msg, Exception e) throws AxisFault {
+        log.error(msg, e);
+        throw new AxisFault(msg, e);
+    }
+
+    private void handleException(String msg) throws AxisFault {
+        log.error(msg);
+        throw new AxisFault(msg);
+    }
+
+}

Added: webservices/axis2/trunk/java/modules/kernel/src/org/apache/axis2/transport/nhttp/HttpCoreNIOSSLListener.java
URL: http://svn.apache.org/viewvc/webservices/axis2/trunk/java/modules/kernel/src/org/apache/axis2/transport/nhttp/HttpCoreNIOSSLListener.java?view=auto&rev=549457
==============================================================================
--- webservices/axis2/trunk/java/modules/kernel/src/org/apache/axis2/transport/nhttp/HttpCoreNIOSSLListener.java (added)
+++ webservices/axis2/trunk/java/modules/kernel/src/org/apache/axis2/transport/nhttp/HttpCoreNIOSSLListener.java Thu Jun 21 05:21:46 2007
@@ -0,0 +1,179 @@
+///*
+// *  Licensed to the Apache Software Foundation (ASF) under one
+// *  or more contributor license agreements.  See the NOTICE file
+// *  distributed with this work for additional information
+// *  regarding copyright ownership.  The ASF licenses this file
+// *  to you under the Apache License, Version 2.0 (the
+// *  "License"); you may not use this file except in compliance
+// *  with the License.  You may obtain a copy of the License at
+// *
+// *   http://www.apache.org/licenses/LICENSE-2.0
+// *
+// *  Unless required by applicable law or agreed to in writing,
+// *  software distributed under the License is distributed on an
+// *   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// *  KIND, either express or implied.  See the License for the
+// *  specific language governing permissions and limitations
+// *  under the License.
+// */
+//
+//package org.apache.axis2.transport.nhttp;
+//
+//import java.io.IOException;
+//import java.net.SocketAddress;
+//import java.net.URL;
+//import java.security.GeneralSecurityException;
+//import java.security.KeyStore;
+//
+//import javax.net.ssl.KeyManager;
+//import javax.net.ssl.KeyManagerFactory;
+//import javax.net.ssl.SSLContext;
+//import javax.net.ssl.SSLEngine;
+//import javax.net.ssl.SSLException;
+//import javax.net.ssl.SSLSession;
+//import javax.net.ssl.TrustManager;
+//import javax.net.ssl.TrustManagerFactory;
+//import javax.xml.namespace.QName;
+//
+//import org.apache.axiom.om.OMElement;
+//import org.apache.axis2.AxisFault;
+//import org.apache.axis2.context.ConfigurationContext;
+//import org.apache.axis2.description.Parameter;
+//import org.apache.axis2.description.TransportInDescription;
+//import org.apache.commons.logging.Log;
+//import org.apache.commons.logging.LogFactory;
+//import org.apache.http.impl.nio.reactor.SSLIOSessionHandler;
+//import org.apache.http.nio.NHttpServiceHandler;
+//import org.apache.http.nio.reactor.IOEventDispatch;
+//import org.apache.http.params.HttpParams;
+//
+//public class HttpCoreNIOSSLListener extends HttpCoreNIOListener {
+//
+//    private static final Log log = LogFactory.getLog(HttpCoreNIOSSLListener.class);
+//
+//    protected IOEventDispatch getEventDispatch(
+//        NHttpServiceHandler handler, SSLContext sslContext,
+//        SSLIOSessionHandler sslIOSessionHandler, HttpParams params) {
+//        return new SSLServerIOEventDispatch(handler, sslContext, sslIOSessionHandler, params);
+//    }
+//
+//    /**
+//     * Return the EPR prefix for services made available over this transport
+//     * @return
+//     */
+//    protected String getServiceEPRPrefix(ConfigurationContext cfgCtx, String host, int port) {
+//        return "https://" + host + (port == 443 ? "" : ":" + port) +
+//            (!cfgCtx.getServiceContextPath().startsWith("/") ? "/" : "") +
+//            cfgCtx.getServiceContextPath() +
+//            (!cfgCtx.getServiceContextPath().endsWith("/") ? "/" : "");
+//    }
+//
+//
+//    /**
+//     * Create the SSLContext to be used by this listener
+//     * @param transportIn the Axis2 transport description
+//     * @return the SSLContext to be used
+//     */
+//    protected SSLContext getSSLContext(TransportInDescription transportIn) throws AxisFault {
+//
+//        KeyManager[] keymanagers  = null;
+//        TrustManager[] trustManagers = null;
+//
+//        Parameter keyParam    = transportIn.getParameter("keystore");
+//        Parameter trustParam  = transportIn.getParameter("truststore");
+//
+//        if (keyParam != null) {
+//            OMElement ksEle      = keyParam.getParameterElement().getFirstElement();
+//            String location      = ksEle.getFirstChildWithName(new QName("Location")).getText();
+//            String type          = ksEle.getFirstChildWithName(new QName("Type")).getText();
+//            String storePassword = ksEle.getFirstChildWithName(new QName("Password")).getText();
+//            String keyPassword   = ksEle.getFirstChildWithName(new QName("KeyPassword")).getText();
+//
+//            try {
+//                KeyStore keyStore = KeyStore.getInstance(type);
+//                URL url = getClass().getClassLoader().getResource(location);
+//                log.debug("Loading Key Store from URL : " + url);
+//
+//                keyStore.load(url.openStream(), storePassword.toCharArray());
+//                KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(
+//                    KeyManagerFactory.getDefaultAlgorithm());
+//                kmfactory.init(keyStore, keyPassword.toCharArray());
+//                keymanagers = kmfactory.getKeyManagers();
+//
+//            } catch (GeneralSecurityException gse) {
+//                log.error("Error loading Key store : " + location, gse);
+//                throw new AxisFault("Error loading Key store : " + location, gse);
+//            } catch (IOException ioe) {
+//                log.error("Error opening Key store : " + location, ioe);
+//                throw new AxisFault("Error opening Key store : " + location, ioe);
+//            }
+//        }
+//
+//        if (trustParam != null) {
+//            OMElement tsEle      = trustParam.getParameterElement().getFirstElement();
+//            String location      = tsEle.getFirstChildWithName(new QName("Location")).getText();
+//            String type          = tsEle.getFirstChildWithName(new QName("Type")).getText();
+//            String storePassword = tsEle.getFirstChildWithName(new QName("Password")).getText();
+//
+//            try {
+//                KeyStore trustStore = KeyStore.getInstance(type);
+//                URL url = getClass().getClassLoader().getResource(location);
+//                log.debug("Loading Trust Key Store from URL : " + url);
+//
+//                trustStore.load(url.openStream(), storePassword.toCharArray());
+//                TrustManagerFactory trustManagerfactory = TrustManagerFactory.getInstance(
+//                    TrustManagerFactory.getDefaultAlgorithm());
+//                trustManagerfactory.init(trustStore);
+//                trustManagers = trustManagerfactory.getTrustManagers();
+//
+//            } catch (GeneralSecurityException gse) {
+//                log.error("Error loading Key store : " + location, gse);
+//                throw new AxisFault("Error loading Key store : " + location, gse);
+//            } catch (IOException ioe) {
+//                log.error("Error opening Key store : " + location, ioe);
+//                throw new AxisFault("Error opening Key store : " + location, ioe);
+//            }
+//        }
+//
+//        try {
+//            SSLContext sslcontext = SSLContext.getInstance("TLS");
+//            sslcontext.init(keymanagers, trustManagers, null);
+//            return sslcontext;
+//
+//        } catch (GeneralSecurityException gse) {
+//            log.error("Unable to create SSL context with the given configuration", gse);
+//            throw new AxisFault("Unable to create SSL context with the given configuration", gse);
+//        }
+//    }
+//
+//    /**
+//     * Create the SSLIOSessionHandler to initialize the SSL session / engine, and request for
+//     * client authentication at the following levels, through an Axis2 transport configuration
+//     * parameter as follows:
+//     * SSLVerifyClient - none, optional, require
+//     *
+//     * @param transportIn the Axis2 transport configuration
+//     * @return the SSLIOSessionHandler to be used
+//     * @throws AxisFault if a configuration error occurs
+//     */
+//    protected SSLIOSessionHandler getSSLIOSessionHandler(TransportInDescription transportIn) throws AxisFault {
+//
+//        final Parameter clientAuth = transportIn.getParameter("SSLVerifyClient");
+//
+//        return new SSLIOSessionHandler() {
+//
+//            public void initalize(SSLEngine sslengine, HttpParams params) {
+//                if (clientAuth != null) {
+//                    if ("optional".equals(clientAuth.getValue())) {
+//                        sslengine.setWantClientAuth(true);
+//                    } else if ("require".equals(clientAuth.getValue())) {
+//                        sslengine.setNeedClientAuth(true);
+//                    }
+//                }
+//            }
+//
+//            public void verify(SocketAddress removeAddress, SSLSession session)
+//                throws SSLException {}
+//        };
+//    }
+//}



---------------------------------------------------------------------
To unsubscribe, e-mail: axis-cvs-unsubscribe@ws.apache.org
For additional commands, e-mail: axis-cvs-help@ws.apache.org


Mime
View raw message