You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@synapse.apache.org by hi...@apache.org on 2013/07/12 21:25:41 UTC
svn commit: r1502663 [2/7] - in /synapse/trunk/java: ./
modules/core/src/main/java/org/apache/synapse/core/relay/
modules/integration/src/test/resources/axis2Xml/synapse/
modules/transports/core/nhttp/src/main/java/org/apache/synapse/transport/passthru...
Added: synapse/trunk/java/modules/transports/core/nhttp/src/main/java/org/apache/synapse/transport/passthru/PassThroughHttpListener.java
URL: http://svn.apache.org/viewvc/synapse/trunk/java/modules/transports/core/nhttp/src/main/java/org/apache/synapse/transport/passthru/PassThroughHttpListener.java?rev=1502663&view=auto
==============================================================================
--- synapse/trunk/java/modules/transports/core/nhttp/src/main/java/org/apache/synapse/transport/passthru/PassThroughHttpListener.java (added)
+++ synapse/trunk/java/modules/transports/core/nhttp/src/main/java/org/apache/synapse/transport/passthru/PassThroughHttpListener.java Fri Jul 12 19:25:40 2013
@@ -0,0 +1,430 @@
+/*
+ * 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.synapse.transport.passthru;
+
+import org.apache.axiom.om.OMElement;
+import org.apache.axis2.AxisFault;
+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.*;
+import org.apache.axis2.engine.AxisConfiguration;
+import org.apache.axis2.engine.AxisEvent;
+import org.apache.axis2.engine.AxisObserver;
+import org.apache.axis2.transport.TransportListener;
+import org.apache.axis2.transport.base.BaseConstants;
+import org.apache.axis2.transport.base.BaseUtils;
+import org.apache.axis2.transport.base.threads.NativeThreadFactory;
+import org.apache.axis2.transport.base.threads.WorkerPool;
+import org.apache.axis2.util.JavaUtils;
+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.IOReactorException;
+import org.apache.http.nio.reactor.IOReactorExceptionHandler;
+import org.apache.http.nio.reactor.ListenerEndpoint;
+import org.apache.http.params.HttpParams;
+import org.apache.synapse.transport.passthru.config.SourceConfiguration;
+import org.apache.synapse.transport.passthru.jmx.MBeanRegistrar;
+import org.apache.synapse.transport.passthru.jmx.PassThroughTransportMetricsCollector;
+import org.apache.synapse.transport.passthru.jmx.TransportView;
+
+import javax.net.ssl.SSLContext;
+import java.io.IOException;
+import java.net.InetSocketAddress;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * This is the TransportListener listening for incoming connections. This class start the IOReactor
+ * and registers the InRequest Handlers on it.
+ */
+public class PassThroughHttpListener implements TransportListener {
+
+ protected Log log = LogFactory.getLog(this.getClass());
+
+ /** The reactor being used */
+ private DefaultListeningIOReactor ioReactor;
+
+ /** The configuration of the listener */
+ private SourceConfiguration sourceConfiguration = null;
+
+ /** 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;
+
+ /** The custom URI map for the services if there are any */
+ private Map<String, String> serviceNameToEPRMap = new HashMap<String, String>();
+ /** The service name map for the custom URI if there are any */
+ private Map<String, String> eprToServiceNameMap = new HashMap<String, String>();
+ /** the axis observer that gets notified of service life cycle events*/
+ private final AxisObserver axisObserver = new GenericAxisObserver();
+
+ private volatile int state = BaseConstants.STOPPED;
+
+ private String namePrefix;
+
+ public void init(ConfigurationContext cfgCtx, TransportInDescription transportInDescription)
+ throws AxisFault {
+
+ log.info("Initializing Pass-through HTTP/S Listener...");
+
+ int portOffset = Integer.parseInt(System.getProperty("portOffset", "0"));
+ Parameter portParam = transportInDescription.getParameter("port");
+ int port = Integer.parseInt(portParam.getValue().toString());
+ port = port + portOffset;
+ portParam.setValue(String.valueOf(port));
+ portParam.getParameterElement().setText(String.valueOf(port));
+
+ Object obj = cfgCtx.getProperty(PassThroughConstants.PASS_THROUGH_TRANSPORT_WORKER_POOL);
+ WorkerPool workerPool = null;
+ if (obj != null) {
+ workerPool = (WorkerPool) obj;
+ }
+
+ // is this a SSL listener?
+ sslContext = getSSLContext(transportInDescription);
+ sslIOSessionHandler = getSSLIOSessionHandler(transportInDescription);
+
+ namePrefix = (sslContext == null) ? "HTTP" : "HTTPS";
+
+ sourceConfiguration = new SourceConfiguration(cfgCtx, transportInDescription, workerPool);
+ sourceConfiguration.setSsl((sslContext == null) ? false :true);
+ sourceConfiguration.build();
+
+ // register to receive updates on services for lifetime management
+ cfgCtx.getAxisConfiguration().addObservers(axisObserver);
+ cfgCtx.setProperty(PassThroughConstants.EPR_TO_SERVICE_NAME_MAP, eprToServiceNameMap);
+
+ cfgCtx.setProperty(PassThroughConstants.PASS_THROUGH_TRANSPORT_WORKER_POOL,
+ sourceConfiguration.getWorkerPool());
+
+ PassThroughTransportMetricsCollector metrics = new PassThroughTransportMetricsCollector(
+ true, sslContext != null);
+
+ MBeanRegistrar.getInstance().registerMBean(
+ new TransportView(this, null, metrics, null), "Transport",
+ "passthru-" + namePrefix.toLowerCase() + "-receiver");
+ sourceConfiguration.setMetrics(metrics);
+ }
+
+ public void start() throws AxisFault {
+
+ log.info("Starting Pass-through " + namePrefix + " Listener...");
+
+ try {
+ String prefix = namePrefix + "-Listener I/O dispatcher";
+
+ ioReactor = new DefaultListeningIOReactor(
+ sourceConfiguration.getIOThreadsPerReactor(),
+ new NativeThreadFactory(new ThreadGroup(prefix + " thread group"), prefix),
+ sourceConfiguration.getHttpParameters());
+
+ ioReactor.setExceptionHandler(new IOReactorExceptionHandler() {
+
+ public boolean handle(IOException ioException) {
+ log.warn("System may be unstable: " + namePrefix +
+ " ListeningIOReactor encountered a checked exception : " +
+ ioException.getMessage(), ioException);
+ return true;
+ }
+
+ public boolean handle(RuntimeException runtimeException) {
+ log.warn("System may be unstable: " + namePrefix +
+ " ListeningIOReactor encountered a runtime exception : "
+ + runtimeException.getMessage(), runtimeException);
+ return true;
+ }
+ });
+
+ } catch (IOReactorException e) {
+ handleException("Error starting " + namePrefix + " ListeningIOReactor", e);
+ }
+
+ SourceHandler handler = new SourceHandler(sourceConfiguration);
+
+ final IOEventDispatch ioEventDispatch = getEventDispatch(handler, sslContext,
+ sslIOSessionHandler, sourceConfiguration.getHttpParameters());
+
+ ListenerEndpoint endpoint = ioReactor.listen(
+ new InetSocketAddress(sourceConfiguration.getPort()));
+
+ if(sourceConfiguration.getHttpGetRequestProcessor() != null){
+ sourceConfiguration.getHttpGetRequestProcessor().init(sourceConfiguration.getConfigurationContext(), handler);
+ }
+
+ Thread t = new Thread(new Runnable() {
+ public void run() {
+ try {
+ ioReactor.execute(ioEventDispatch);
+ } catch (Exception e) {
+ log.fatal("Exception encountered in the " + namePrefix + " Listener. " +
+ "No more connections will be accepted by this transport", e);
+ }
+ log.info(namePrefix + " Listener shutdown.");
+ }
+ }, "PassThrough" + namePrefix + "Listener");
+ t.start();
+
+ try {
+ endpoint.waitFor();
+ } catch (InterruptedException e) {
+ log.warn("PassThroughHttpListener start event was interrupted", e);
+ }
+
+ state = BaseConstants.STARTED;
+
+ log.info("Pass-through " + namePrefix + " Listener " + "started on port : " +
+ sourceConfiguration.getPort());
+ }
+
+ private void handleException(String s, Exception e) throws AxisFault {
+ log.error(s, e);
+ throw new AxisFault(s, e);
+ }
+
+ public EndpointReference getEPRForService(String serviceName, String ip) throws AxisFault {
+ String trailer = "";
+ //Strip out the operation name
+ if (serviceName.indexOf('/') != -1) {
+ trailer += serviceName.substring(serviceName.indexOf("/"));
+ serviceName = serviceName.substring(0, serviceName.indexOf('/'));
+ }
+ // strip out the endpoint name if present
+ if (serviceName.indexOf('.') != -1) {
+ trailer += serviceName.substring(serviceName.indexOf("."));
+ serviceName = serviceName.substring(0, serviceName.indexOf('.'));
+ }
+
+ if (serviceNameToEPRMap.containsKey(serviceName)) {
+ return new EndpointReference(
+ sourceConfiguration.getCustomEPRPrefix() +
+ serviceNameToEPRMap.get(serviceName) + trailer);
+ } else {
+ return new EndpointReference(sourceConfiguration.getServiceEPRPrefix() +
+ serviceName + trailer);
+ }
+ }
+
+ /**
+ * 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 {
+ String trailer = "";
+ //Strip out the operation name
+ if (serviceName.indexOf('/') != -1) {
+ trailer += serviceName.substring(serviceName.indexOf("/"));
+ serviceName = serviceName.substring(0, serviceName.indexOf('/'));
+ }
+ // strip out the endpoint name if present
+ if (serviceName.indexOf('.') != -1) {
+ trailer += serviceName.substring(serviceName.indexOf("."));
+ serviceName = serviceName.substring(0, serviceName.indexOf('.'));
+ }
+
+ EndpointReference[] endpointReferences = new EndpointReference[1];
+ if (serviceNameToEPRMap.containsKey(serviceName)) {
+ endpointReferences[0] = new EndpointReference(
+ sourceConfiguration.getCustomEPRPrefix() +
+ serviceNameToEPRMap.get(serviceName) + trailer);
+ } else {
+ endpointReferences[0]
+ = new EndpointReference(sourceConfiguration.getServiceEPRPrefix() +
+ serviceName + trailer);
+ }
+ return endpointReferences;
+ }
+
+ public SessionContext getSessionContext(MessageContext messageContext) {
+ return null;
+ }
+
+
+ public void stop() throws AxisFault {
+ log.info("Stopping Pass-through " + namePrefix + " Listener..");
+ try {
+ ioReactor.shutdown();
+ } catch (IOException e) {
+ handleException("Error shutting down " + namePrefix + " listening IO reactor", e);
+ }
+ }
+
+ public void destroy() {
+ log.info("Destroying PassThroughHttpListener");
+ sourceConfiguration.getConfigurationContext().
+ getAxisConfiguration().getObserversList().remove(axisObserver);
+
+ sourceConfiguration.getMetrics().destroy();
+ }
+
+ /**
+ * Pause the listener - Stops accepting new connections, but continues processing existing
+ * connections until they complete. This helps bring an instance into a maintenance mode
+ *
+ * @throws AxisFault if pausing fails
+ */
+ public void pause() throws AxisFault {
+ if (state != BaseConstants.STARTED) return;
+ try {
+ ioReactor.pause();
+
+ state = BaseConstants.PAUSED;
+ log.info(namePrefix + " Listener Paused");
+ } catch (IOException e) {
+ handleException("Error pausing IOReactor", e);
+ }
+ }
+
+ /**
+ * Resume the lister - Brings the lister into active mode back from a paused state
+ *
+ * @throws AxisFault if the resume fails
+ */
+ public void resume() throws AxisFault {
+ if (state != BaseConstants.PAUSED) return;
+ try {
+ ioReactor.resume();
+ state = BaseConstants.STARTED;
+ log.info((sslContext == null ? "HTTP" : "HTTPS") + "Listener Resumed");
+ } catch (IOException e) {
+ handleException("Error resuming IOReactor", e);
+ }
+ }
+
+ /**
+ * Stop accepting new connections, and wait the maximum specified time for in-flight
+ * requests to complete before a controlled shutdown for maintenance
+ *
+ * @param milliSecs number of milliseconds to wait until pending requests complete
+ * @throws AxisFault if the shutdown fails
+ */
+ public void maintenanceShutdown(long milliSecs) throws AxisFault {
+ if (state != BaseConstants.STARTED) return;
+ try {
+ long start = System.currentTimeMillis();
+ ioReactor.pause();
+ ioReactor.shutdown(milliSecs);
+ state = BaseConstants.STOPPED;
+ log.info("Listener shutdown in : " + (System.currentTimeMillis() - start) / 1000 + "s");
+ } catch (IOException e) {
+ handleException("Error shutting down the IOReactor for maintenance", e);
+ }
+ }
+
+ /**
+ * An AxisObserver which will start listening for newly deployed or started services,
+ * and stop listening when services are un-deployed or stopped.
+ */
+ private class GenericAxisObserver implements AxisObserver {
+ public void init(AxisConfiguration axisConfig) {}
+
+ public void serviceUpdate(AxisEvent event, AxisService service) {
+ if (!ignoreService(service)
+ && BaseUtils.isUsingTransport(service,
+ sourceConfiguration.getInDescription().getName())) {
+ switch (event.getEventType()) {
+ case AxisEvent.SERVICE_DEPLOY :
+ addToServiceURIMap(service);
+ break;
+ case AxisEvent.SERVICE_REMOVE :
+ removeServiceFfromURIMap(service);
+ break;
+ case AxisEvent.SERVICE_START :
+ addToServiceURIMap(service);
+ break;
+ case AxisEvent.SERVICE_STOP :
+ removeServiceFfromURIMap(service);
+ break;
+ }
+ }
+ }
+
+ public void moduleUpdate(AxisEvent event, AxisModule module) {}
+ public void addParameter(Parameter parameter) throws AxisFault {}
+ public void removeParameter(Parameter parameter) throws AxisFault {}
+ public void deserializeParameters(OMElement parameterElement) throws AxisFault {}
+ public Parameter getParameter(String name) { return null; }
+ public ArrayList<Parameter> getParameters() { return null; }
+ public boolean isParameterLocked(String parameterName) { return false; }
+ public void serviceGroupUpdate(AxisEvent event, AxisServiceGroup serviceGroup) {}
+ }
+
+ private boolean ignoreService(AxisService service) {
+ // these are "private" services
+ return service.getName().startsWith("__") || JavaUtils.isTrueExplicitly(
+ service.getParameter(PassThroughConstants.HIDDEN_SERVICE_PARAM_NAME));
+ }
+
+ private void addToServiceURIMap(AxisService service) {
+ Parameter param = service.getParameter(PassThroughConstants.SERVICE_URI_LOCATION);
+ if (param != null) {
+ String uriLocation = param.getValue().toString();
+ if (uriLocation.startsWith("/")) {
+ uriLocation = uriLocation.substring(1);
+ }
+ serviceNameToEPRMap.put(service.getName(), uriLocation);
+ eprToServiceNameMap.put(uriLocation, service.getName());
+ }
+ }
+
+ private void removeServiceFfromURIMap(AxisService service) {
+ eprToServiceNameMap.remove(serviceNameToEPRMap.get(service.getName()));
+ serviceNameToEPRMap.remove(service.getName());
+ }
+
+ protected IOEventDispatch getEventDispatch(
+ NHttpServiceHandler handler, SSLContext sslContext,
+ SSLIOSessionHandler sslioSessionHandler, HttpParams params) {
+ return new SourceIOEventDispatch(handler, params);
+ }
+
+ /**
+ * Create the SSLContext to be used by this listener
+ * @param transportIn transport in description
+ * @return always null
+ * @throws AxisFault never thrown
+ */
+ protected SSLContext getSSLContext(
+ TransportInDescription transportIn) throws AxisFault {
+ return null;
+ }
+
+ /**
+ * Create the SSL IO Session handler to be used by this listener
+ * @param transportIn transport in descritption
+ * @return always null
+ * @throws AxisFault never thrown
+ */
+ protected SSLIOSessionHandler getSSLIOSessionHandler(
+ TransportInDescription transportIn) throws AxisFault {
+ return null;
+ }
+
+}
Added: synapse/trunk/java/modules/transports/core/nhttp/src/main/java/org/apache/synapse/transport/passthru/PassThroughHttpSSLListener.java
URL: http://svn.apache.org/viewvc/synapse/trunk/java/modules/transports/core/nhttp/src/main/java/org/apache/synapse/transport/passthru/PassThroughHttpSSLListener.java?rev=1502663&view=auto
==============================================================================
--- synapse/trunk/java/modules/transports/core/nhttp/src/main/java/org/apache/synapse/transport/passthru/PassThroughHttpSSLListener.java (added)
+++ synapse/trunk/java/modules/transports/core/nhttp/src/main/java/org/apache/synapse/transport/passthru/PassThroughHttpSSLListener.java Fri Jul 12 19:25:40 2013
@@ -0,0 +1,173 @@
+/*
+ * 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.synapse.transport.passthru;
+
+import org.apache.axiom.om.OMElement;
+import org.apache.axis2.AxisFault;
+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.SSLServerIOEventDispatch;
+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;
+
+import javax.net.ssl.*;
+import javax.xml.namespace.QName;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.net.SocketAddress;
+import java.security.GeneralSecurityException;
+import java.security.KeyStore;
+
+public class PassThroughHttpSSLListener extends PassThroughHttpListener {
+
+ private Log log = LogFactory.getLog(PassThroughHttpSSLListener.class);
+
+ protected IOEventDispatch getEventDispatch(
+ NHttpServiceHandler handler, SSLContext sslContext,
+ SSLIOSessionHandler sslIOSessionHandler, HttpParams params) {
+ return new SSLServerIOEventDispatch(handler, sslContext, sslIOSessionHandler, params);
+ }
+
+ /**
+ * Create the SSLContext to be used by this listener
+ * @param transportIn the Axis2 transport description
+ * @return the SSLContext to be used
+ * @throws org.apache.axis2.AxisFault if an error occurs
+ */
+ 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();
+
+ FileInputStream fis = null;
+ try {
+ KeyStore keyStore = KeyStore.getInstance(type);
+ fis = new FileInputStream(location);
+ log.info("Loading Identity Keystore from : " + location);
+
+ keyStore.load(fis, 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);
+ } finally {
+ if (fis != null) {
+ try {
+ fis.close();
+ } catch (IOException ignore) {}
+ }
+ }
+ }
+
+ 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();
+
+ FileInputStream fis = null;
+ try {
+ KeyStore trustStore = KeyStore.getInstance(type);
+ fis = new FileInputStream(location);
+ log.info("Loading Trust Keystore from : " + location);
+
+ trustStore.load(fis, 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);
+ } finally {
+ if (fis != null) {
+ try {
+ fis.close();
+ } catch (IOException ignore) {}
+ }
+ }
+ }
+
+ 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 {}
+ };
+ }
+}
Added: synapse/trunk/java/modules/transports/core/nhttp/src/main/java/org/apache/synapse/transport/passthru/PassThroughHttpSSLSender.java
URL: http://svn.apache.org/viewvc/synapse/trunk/java/modules/transports/core/nhttp/src/main/java/org/apache/synapse/transport/passthru/PassThroughHttpSSLSender.java?rev=1502663&view=auto
==============================================================================
--- synapse/trunk/java/modules/transports/core/nhttp/src/main/java/org/apache/synapse/transport/passthru/PassThroughHttpSSLSender.java (added)
+++ synapse/trunk/java/modules/transports/core/nhttp/src/main/java/org/apache/synapse/transport/passthru/PassThroughHttpSSLSender.java Fri Jul 12 19:25:40 2013
@@ -0,0 +1,341 @@
+/*
+ * 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.synapse.transport.passthru;
+
+import org.apache.axiom.om.OMElement;
+import org.apache.axis2.AxisFault;
+import org.apache.axis2.description.Parameter;
+import org.apache.axis2.description.TransportOutDescription;
+import org.apache.axis2.transport.base.ParamUtils;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.http.impl.nio.reactor.SSLSetupHandler;
+import org.apache.http.nio.NHttpClientHandler;
+import org.apache.http.nio.reactor.IOEventDispatch;
+import org.apache.http.nio.reactor.IOSession;
+import org.apache.http.params.HttpParams;
+
+import javax.net.ssl.*;
+import javax.xml.namespace.QName;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.net.InetSocketAddress;
+import java.net.SocketAddress;
+import java.security.GeneralSecurityException;
+import java.security.KeyStore;
+import java.security.cert.CertificateException;
+import java.security.cert.X509Certificate;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+
+
+public class PassThroughHttpSSLSender extends PassThroughHttpSender {
+ private Log log = LogFactory.getLog(PassThroughHttpSSLSender.class);
+
+ protected IOEventDispatch getEventDispatch(NHttpClientHandler handler,
+ SSLContext sslContext,
+ SSLSetupHandler sslIOSessionHandler,
+ HttpParams params,
+ TransportOutDescription transportOut)
+ throws AxisFault {
+
+ SSLTargetIOEventDispatch dispatch = new SSLTargetIOEventDispatch(handler, sslContext,
+ sslIOSessionHandler, params);
+ dispatch.setContextMap(getCustomSSLContexts(transportOut));
+ return dispatch;
+ }
+
+ /**
+ * Create the SSLContext to be used by this sender
+ *
+ * @param transportOut the Axis2 transport configuration
+ * @return the SSLContext to be used
+ * @throws org.apache.axis2.AxisFault if an error occurs
+ */
+ protected SSLContext getSSLContext(TransportOutDescription transportOut) throws AxisFault {
+
+ Parameter keyParam = transportOut.getParameter("keystore");
+ Parameter trustParam = transportOut.getParameter("truststore");
+
+ OMElement ksEle = null;
+ OMElement tsEle = null;
+
+ if (keyParam != null) {
+ ksEle = keyParam.getParameterElement().getFirstElement();
+ }
+
+ boolean noValidateCert = ParamUtils.getOptionalParamBoolean(transportOut,
+ "novalidatecert", false);
+
+ if (trustParam != null) {
+ if (noValidateCert) {
+ log.warn("Ignoring novalidatecert parameter since a truststore has been specified");
+ }
+ tsEle = trustParam.getParameterElement().getFirstElement();
+ }
+
+ return createSSLContext(ksEle, tsEle, noValidateCert);
+ }
+
+ /**
+ * Create the SSLIOSessionHandler to initialize the host name verification at the following
+ * levels, through an Axis2 transport configuration parameter as follows:
+ * HostnameVerifier - Default, DefaultAndLocalhost, Strict, AllowAll
+ *
+ * @param transportOut the Axis2 transport configuration
+ * @return the SSLIOSessionHandler to be used
+ * @throws AxisFault if a configuration error occurs
+ */
+ protected SSLSetupHandler getSSLSetupHandler(TransportOutDescription transportOut)
+ throws AxisFault {
+
+ final Parameter hostnameVerifier = transportOut.getParameter("HostnameVerifier");
+ if (hostnameVerifier != null) {
+ return createSSLIOSessionHandler(hostnameVerifier.getValue().toString());
+ } else {
+ return createSSLIOSessionHandler(null);
+ }
+ }
+
+ /**
+ * Looks for a transport parameter named customSSLProfiles and initializes zero or more
+ * custom SSLContext instances. The syntax for defining custom SSL profiles is as follows.
+ *
+ * <parameter name="customSSLProfiles>
+ * <profile>
+ * <servers>www.test.org:80, www.test2.com:9763</servers>
+ * <KeyStore>
+ * <Location>/path/to/identity/store</Location>
+ * <Type>JKS</Type>
+ * <Password>password</Password>
+ * <KeyPassword>password</KeyPassword>
+ * </KeyStore>
+ * <TrustStore>
+ * <Location>path/tp/trust/store</Location>
+ * <Type>JKS</Type>
+ * <Password>password</Password>
+ * </TrustStore>
+ * </profile>
+ * </parameter>
+ *
+ * Any number of profiles can be defined under the customSSLProfiles parameter.
+ *
+ * @param transportOut transport out description
+ * @return a map of server addresses and SSL contexts
+ * @throws AxisFault if at least on SSL profile is not properly configured
+ */
+ private Map<String, SSLContext> getCustomSSLContexts(TransportOutDescription transportOut)
+ throws AxisFault {
+
+ if (log.isDebugEnabled()) {
+ log.info("Loading custom SSL profiles for the HTTPS sender");
+ }
+
+ Parameter customProfilesParam = transportOut.getParameter("customSSLProfiles");
+ if (customProfilesParam == null) {
+ return null;
+ }
+
+ OMElement customProfilesElt = customProfilesParam.getParameterElement();
+ Iterator profiles = customProfilesElt.getChildrenWithName(new QName("profile"));
+ Map<String, SSLContext> contextMap = new HashMap<String, SSLContext>();
+ while (profiles.hasNext()) {
+ OMElement profile = (OMElement) profiles.next();
+ OMElement serversElt = profile.getFirstChildWithName(new QName("servers"));
+ if (serversElt == null || serversElt.getText() == null) {
+ String msg = "Each custom SSL profile must define at least one host:port " +
+ "pair under the servers element";
+ log.error(msg);
+ throw new AxisFault(msg);
+ }
+
+ String[] servers = serversElt.getText().split(",");
+ OMElement ksElt = profile.getFirstChildWithName(new QName("KeyStore"));
+ OMElement trElt = profile.getFirstChildWithName(new QName("TrustStore"));
+ String noValCert = profile.getAttributeValue(new QName("novalidatecert"));
+ boolean novalidatecert = "true".equals(noValCert);
+ SSLContext sslContext = createSSLContext(ksElt, trElt, novalidatecert);
+
+ for (String server : servers) {
+ server = server.trim();
+ if (!contextMap.containsKey(server)) {
+ contextMap.put(server, sslContext);
+ } else {
+ log.warn("Multiple SSL profiles were found for the server : " + server + ". " +
+ "Ignoring the excessive profiles.");
+ }
+ }
+ }
+
+ if (contextMap.size() > 0) {
+ log.info("Custom SSL profiles initialized for " + contextMap.size() + " servers");
+ return contextMap;
+ }
+ return null;
+ }
+
+ private SSLContext createSSLContext(OMElement keyStoreElt, OMElement trustStoreElt,
+ boolean novalidatecert) throws AxisFault {
+
+ KeyManager[] keymanagers = null;
+ TrustManager[] trustManagers = null;
+
+
+ if (keyStoreElt != null) {
+ String location = keyStoreElt.getFirstChildWithName(new QName("Location")).getText();
+ String type = keyStoreElt.getFirstChildWithName(new QName("Type")).getText();
+ String storePassword = keyStoreElt.getFirstChildWithName(new QName("Password")).getText();
+ String keyPassword = keyStoreElt.getFirstChildWithName(new QName("KeyPassword")).getText();
+
+ FileInputStream fis = null;
+ try {
+ KeyStore keyStore = KeyStore.getInstance(type);
+ fis = new FileInputStream(location);
+ log.info("Loading Identity Keystore from : " + location);
+
+ keyStore.load(fis, storePassword.toCharArray());
+ KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(
+ KeyManagerFactory.getDefaultAlgorithm());
+ kmfactory.init(keyStore, keyPassword.toCharArray());
+ keymanagers = kmfactory.getKeyManagers();
+
+ } catch (GeneralSecurityException gse) {
+ log.error("Error loading Keystore : " + location, gse);
+ throw new AxisFault("Error loading Keystore : " + location, gse);
+ } catch (IOException ioe) {
+ log.error("Error opening Keystore : " + location, ioe);
+ throw new AxisFault("Error opening Keystore : " + location, ioe);
+ } finally {
+ if (fis != null) {
+ try {
+ fis.close();
+ } catch (IOException ignore) {}
+ }
+ }
+ }
+
+ if (trustStoreElt != null) {
+ if (novalidatecert) {
+ log.warn("Ignoring novalidatecert parameter since a truststore has been specified");
+ }
+
+ String location = trustStoreElt.getFirstChildWithName(new QName("Location")).getText();
+ String type = trustStoreElt.getFirstChildWithName(new QName("Type")).getText();
+ String storePassword = trustStoreElt.getFirstChildWithName(new QName("Password")).getText();
+
+ FileInputStream fis = null;
+ try {
+ KeyStore trustStore = KeyStore.getInstance(type);
+ fis = new FileInputStream(location);
+ log.info("Loading Trust Keystore from : " + location);
+
+ trustStore.load(fis, 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);
+ } finally {
+ if (fis != null) {
+ try {
+ fis.close();
+ } catch (IOException ignore) {}
+ }
+ }
+ } else if (novalidatecert) {
+ log.warn("Server certificate validation (trust) has been disabled. " +
+ "DO NOT USE IN PRODUCTION!");
+ trustManagers = new TrustManager[] { new NoValidateCertTrustManager() };
+ }
+
+ 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);
+ }
+ }
+
+ private SSLSetupHandler createSSLIOSessionHandler(final String hostnameVerifier)
+ throws AxisFault {
+
+ return new SSLSetupHandler() {
+
+ public void initalize(SSLEngine sslengine, HttpParams params) {
+ }
+
+ public void verify(IOSession ioSession, SSLSession session) throws SSLException {
+ SocketAddress remoteAddress = ioSession.getRemoteAddress();
+ String address;
+ if (remoteAddress instanceof InetSocketAddress) {
+ address = ((InetSocketAddress) remoteAddress).getHostName();
+ } else {
+ address = remoteAddress.toString();
+ }
+
+ boolean valid = false;
+ if (hostnameVerifier != null) {
+ if ("Strict".equals(hostnameVerifier)) {
+ valid = HostnameVerifier.STRICT.verify(address, session);
+ } else if ("AllowAll".equals(hostnameVerifier)) {
+ valid = HostnameVerifier.ALLOW_ALL.verify(address, session);
+ } else if ("DefaultAndLocalhost".equals(hostnameVerifier)) {
+ valid = HostnameVerifier.DEFAULT_AND_LOCALHOST.verify(address, session);
+ }
+ } else {
+ valid = HostnameVerifier.DEFAULT.verify(address, session);
+ }
+
+ if (!valid) {
+ throw new SSLException("Host name verification failed for host : " + address);
+ }
+ }
+ };
+ }
+
+ /**
+ * Trust manager accepting any certificate.
+ */
+ public static class NoValidateCertTrustManager implements X509TrustManager {
+ public void checkClientTrusted(X509Certificate[] chain, String authType)
+ throws CertificateException {
+ // Do nothing: we accept any certificate
+ }
+
+ public void checkServerTrusted(X509Certificate[] chain, String authType)
+ throws CertificateException {
+ // Do nothing: we accept any certificate
+ }
+
+ public X509Certificate[] getAcceptedIssuers() {
+ return new X509Certificate[0];
+ }
+ }
+}
Added: synapse/trunk/java/modules/transports/core/nhttp/src/main/java/org/apache/synapse/transport/passthru/PassThroughHttpSender.java
URL: http://svn.apache.org/viewvc/synapse/trunk/java/modules/transports/core/nhttp/src/main/java/org/apache/synapse/transport/passthru/PassThroughHttpSender.java?rev=1502663&view=auto
==============================================================================
--- synapse/trunk/java/modules/transports/core/nhttp/src/main/java/org/apache/synapse/transport/passthru/PassThroughHttpSender.java (added)
+++ synapse/trunk/java/modules/transports/core/nhttp/src/main/java/org/apache/synapse/transport/passthru/PassThroughHttpSender.java Fri Jul 12 19:25:40 2013
@@ -0,0 +1,506 @@
+/*
+ * 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.synapse.transport.passthru;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+
+import javax.net.ssl.SSLContext;
+
+import org.apache.axiom.om.OMOutputFormat;
+import org.apache.axis2.AxisFault;
+import org.apache.axis2.Constants;
+import org.apache.axis2.addressing.AddressingConstants;
+import org.apache.axis2.addressing.AddressingHelper;
+import org.apache.axis2.addressing.EndpointReference;
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.axis2.context.MessageContext;
+import org.apache.axis2.description.TransportOutDescription;
+import org.apache.axis2.handlers.AbstractHandler;
+import org.apache.axis2.transport.MessageFormatter;
+import org.apache.axis2.transport.OutTransportInfo;
+import org.apache.axis2.transport.TransportSender;
+import org.apache.axis2.transport.base.BaseConstants;
+import org.apache.axis2.transport.base.threads.NativeThreadFactory;
+import org.apache.axis2.transport.base.threads.WorkerPool;
+import org.apache.axis2.util.MessageProcessorSelector;
+import org.apache.commons.io.IOUtils;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.http.HttpException;
+import org.apache.http.HttpStatus;
+import org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor;
+import org.apache.http.impl.nio.reactor.SSLSetupHandler;
+import org.apache.http.nio.NHttpClientHandler;
+import org.apache.http.nio.NHttpServerConnection;
+import org.apache.http.nio.reactor.IOEventDispatch;
+import org.apache.http.nio.reactor.IOReactorException;
+import org.apache.http.nio.reactor.IOReactorExceptionHandler;
+import org.apache.http.params.HttpParams;
+import org.apache.synapse.transport.nhttp.NhttpConstants;
+import org.apache.synapse.transport.nhttp.util.MessageFormatterDecoratorFactory;
+import org.apache.synapse.transport.nhttp.util.NhttpUtil;
+import org.apache.synapse.transport.passthru.config.SourceConfiguration;
+import org.apache.synapse.transport.passthru.config.TargetConfiguration;
+import org.apache.synapse.transport.passthru.connections.TargetConnections;
+import org.apache.synapse.transport.passthru.jmx.MBeanRegistrar;
+import org.apache.synapse.transport.passthru.jmx.PassThroughTransportMetricsCollector;
+import org.apache.synapse.transport.passthru.jmx.TransportView;
+import org.apache.synapse.transport.passthru.util.PassThroughTransportUtils;
+import org.apache.synapse.transport.passthru.util.SourceResponseFactory;
+
+/**
+ * PassThroughHttpSender for Synapse based on HttpCore and NIO extensions
+ */
+public class PassThroughHttpSender extends AbstractHandler implements TransportSender {
+
+ protected Log log;
+
+ /** IOReactor used to create connections and manage them */
+ private DefaultConnectingIOReactor ioReactor;
+
+ /** Delivery agent used for delivering the messages to the servers */
+ private DeliveryAgent deliveryAgent;
+
+ /** The configuration of the sender */
+ private TargetConfiguration targetConfiguration;
+
+ /** state of the sender */
+ private volatile int state = BaseConstants.STOPPED;
+
+ private String namePrefix;
+
+ public PassThroughHttpSender() {
+ log = LogFactory.getLog(this.getClass().getName());
+ }
+
+ public void init(ConfigurationContext configurationContext,
+ TransportOutDescription transportOutDescription) throws AxisFault {
+ log.info("Initializing Pass-through HTTP/S Sender...");
+
+ // is this an SSL Sender?
+ SSLContext sslContext = getSSLContext(transportOutDescription);
+ SSLSetupHandler sslSetupHandler = getSSLSetupHandler(transportOutDescription);
+ namePrefix = (sslContext == null) ? "HTTP" : "HTTPS";
+
+ WorkerPool workerPool = null;
+ Object obj = configurationContext.getProperty(
+ PassThroughConstants.PASS_THROUGH_TRANSPORT_WORKER_POOL);
+ if (obj != null) {
+ workerPool = (WorkerPool) obj;
+ }
+
+ targetConfiguration = new TargetConfiguration(configurationContext,
+ transportOutDescription, workerPool);
+ targetConfiguration.build();
+ configurationContext.setProperty(PassThroughConstants.PASS_THROUGH_TRANSPORT_WORKER_POOL,
+ targetConfiguration.getWorkerPool());
+
+ PassThroughTransportMetricsCollector metrics = new
+ PassThroughTransportMetricsCollector(false, sslContext != null);
+ TransportView view = new TransportView(null, this, metrics, null);
+ MBeanRegistrar.getInstance().registerMBean(view, "Transport",
+ "passthru-" + namePrefix.toLowerCase() + "-sender");
+ targetConfiguration.setMetrics(metrics);
+
+ try {
+ String prefix = namePrefix + "-Sender I/O dispatcher";
+
+ ioReactor = new DefaultConnectingIOReactor(
+ targetConfiguration.getIOThreadsPerReactor(),
+ new NativeThreadFactory(new ThreadGroup(prefix + " Thread Group"), prefix),
+ targetConfiguration.getHttpParameters());
+
+ ioReactor.setExceptionHandler(new IOReactorExceptionHandler() {
+
+ public boolean handle(IOException ioException) {
+ log.warn("System may be unstable: " + namePrefix +
+ " ConnectingIOReactor encountered a checked exception : " +
+ ioException.getMessage(), ioException);
+ return true;
+ }
+
+ public boolean handle(RuntimeException runtimeException) {
+ log.warn("System may be unstable: " + namePrefix +
+ " ConnectingIOReactor encountered a runtime exception : "
+ + runtimeException.getMessage(), runtimeException);
+ return true;
+ }
+ });
+ } catch (IOReactorException e) {
+ handleException("Error starting " + namePrefix + " ConnectingIOReactor", e);
+ }
+
+ ConnectCallback connectCallback = new ConnectCallback();
+ // manage target connections
+ TargetConnections targetConnections =
+ new TargetConnections(ioReactor, targetConfiguration, connectCallback);
+ targetConfiguration.setConnections(targetConnections);
+
+ // create the delivery agent to hand over messages
+ deliveryAgent = new DeliveryAgent(targetConfiguration, targetConnections);
+ // we need to set the delivery agent
+ connectCallback.setDeliveryAgent(deliveryAgent);
+
+ TargetHandler handler = new TargetHandler(deliveryAgent, targetConfiguration);
+ final IOEventDispatch ioEventDispatch =
+ getEventDispatch(handler, sslContext, sslSetupHandler,
+ targetConfiguration.getHttpParameters(), transportOutDescription);
+
+ // start the sender in a separate thread
+ Thread t = new Thread(new Runnable() {
+ public void run() {
+ try {
+ ioReactor.execute(ioEventDispatch);
+ } catch (Exception ex) {
+ log.fatal("Exception encountered in the " + namePrefix + " Sender. " +
+ "No more connections will be initiated by this transport", ex);
+ }
+ log.info(namePrefix + " Sender shutdown");
+ }
+ }, "PassThrough" + namePrefix + "Sender");
+ t.start();
+
+ state = BaseConstants.STARTED;
+
+ log.info("Pass-through " + namePrefix + " Sender started...");
+ }
+
+ public void cleanup(org.apache.axis2.context.MessageContext messageContext) throws AxisFault {
+
+ }
+
+ public void stop() {
+ try {
+ ioReactor.shutdown();
+ } catch (IOException e) {
+ log.error("Error shutting down the PassThroughHttpSender", e);
+ }
+ }
+
+
+ public InvocationResponse invoke(org.apache.axis2.context.MessageContext msgContext) throws AxisFault {
+ // remove unwanted HTTP headers (if any from the current message)
+ PassThroughTransportUtils.removeUnwantedHeaders(msgContext,
+ targetConfiguration.isPreserveServerHeader(),
+ targetConfiguration.isPreserveUserAgentHeader());
+
+ if (AddressingHelper.isReplyRedirected(msgContext)
+ && !msgContext.getReplyTo().hasNoneAddress()) {
+
+ msgContext.setProperty(PassThroughConstants.IGNORE_SC_ACCEPTED, Constants.VALUE_TRUE);
+ }
+
+ EndpointReference epr = PassThroughTransportUtils.getDestinationEPR(msgContext);
+ if (epr != null) {
+ if (!epr.hasNoneAddress()) {
+ if (msgContext.getProperty(PassThroughConstants.PASS_THROUGH_PIPE) == null) {
+ Pipe pipe = new Pipe(targetConfiguration.getBufferFactory().getBuffer(),
+ "Test", targetConfiguration);
+ msgContext.setProperty(PassThroughConstants.PASS_THROUGH_PIPE, pipe);
+ msgContext.setProperty(PassThroughConstants.MESSAGE_BUILDER_INVOKED, Boolean.TRUE);
+ }
+ deliveryAgent.submit(msgContext, epr);
+ sendRequestContent(msgContext);
+ } else {
+ handleException("Cannot send message to " + AddressingConstants.Final.WSA_NONE_URI);
+ }
+ } else {
+ if (msgContext.getProperty(Constants.OUT_TRANSPORT_INFO) != null) {
+ if (msgContext.getProperty(Constants.OUT_TRANSPORT_INFO) instanceof ServerWorker) {
+ try {
+ submitResponse(msgContext);
+ } catch (Exception e) {
+ handleException("Failed to submit the response", e);
+ }
+ }else {
+ //handleException("No valid destination EPR to send message");
+ //should be able to handle sendUsingOutputStream Ref NHTTP_NIO
+ sendUsingOutputStream(msgContext);
+ }
+ } else {
+ handleException("No valid destination EPR to send message");
+ }
+ }
+
+ if (msgContext.getOperationContext() != null) {
+ msgContext.getOperationContext().setProperty(
+ Constants.RESPONSE_WRITTEN, Constants.VALUE_TRUE);
+ }
+
+ return InvocationResponse.CONTINUE;
+ }
+
+
+ private void sendUsingOutputStream(MessageContext msgContext) throws AxisFault {
+
+ OMOutputFormat format = NhttpUtil.getOMOutputFormat(msgContext);
+ MessageFormatter messageFormatter =
+ MessageFormatterDecoratorFactory.createMessageFormatterDecorator(msgContext);
+ OutputStream out = (OutputStream) msgContext.getProperty(MessageContext.TRANSPORT_OUT);
+
+ if (msgContext.isServerSide()) {
+ OutTransportInfo transportInfo =
+ (OutTransportInfo) msgContext.getProperty(Constants.OUT_TRANSPORT_INFO);
+
+ if (transportInfo != null) {
+ transportInfo.setContentType(
+ messageFormatter.getContentType(msgContext, format, msgContext.getSoapAction()));
+ } else {
+ throw new AxisFault(Constants.OUT_TRANSPORT_INFO + " has not been set");
+ }
+ }
+
+ try {
+ messageFormatter.writeTo(msgContext, format, out, false);
+ out.close();
+ } catch (IOException e) {
+ handleException("IO Error sending response message", e);
+ }
+ }
+
+
+ private void sendRequestContent(final MessageContext msgContext) throws AxisFault {
+ if (Boolean.TRUE.equals(msgContext.getProperty(PassThroughConstants.MESSAGE_BUILDER_INVOKED))) {
+ synchronized (msgContext) {
+ while (!Boolean.TRUE.equals(msgContext.getProperty("READY2ROCK")) &&
+ !Boolean.TRUE.equals(msgContext.getProperty("PASSTHRU_CONNECT_ERROR"))) {
+ try {
+ msgContext.wait();
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ }
+ }
+
+ if (Boolean.TRUE.equals(msgContext.getProperty("PASSTHRU_CONNECT_ERROR"))) {
+ return;
+ }
+
+ OutputStream out = (OutputStream) msgContext.getProperty("GET_ME_OUT");
+ if (out != null) {
+ String disableChunking = (String) msgContext.getProperty(PassThroughConstants.DISABLE_CHUNKING);
+ String forceHttp10 = (String) msgContext.getProperty(PassThroughConstants.FORCE_HTTP_1_0);
+ Pipe pipe = (Pipe) msgContext.getProperty(PassThroughConstants.PASS_THROUGH_PIPE);
+
+ if("true".equals(disableChunking) || "true".equals(forceHttp10) ){
+ ByteArrayOutputStream _out = new ByteArrayOutputStream();
+ MessageFormatter formatter = MessageProcessorSelector.getMessageFormatter(msgContext);
+ OMOutputFormat format = PassThroughTransportUtils.getOMOutputFormat(msgContext);
+ formatter.writeTo(msgContext, format, _out, false);
+ try {
+ IOUtils.write(_out.toByteArray(),out);
+ msgContext.setProperty(PassThroughConstants.PASS_THROUGH_MESSAGE_LENGTH,new Long(_out.toByteArray().length));
+ } catch (IOException e) {
+ // TODO Auto-generated catch block
+ handleException("IO while building message", e);
+ }
+ pipe.setSerializationComplete(true);
+ }else {
+
+ if ((disableChunking == null || !"true".equals(disableChunking)) ||
+ (forceHttp10 == null || !"true".equals(forceHttp10))) {
+ MessageFormatter formatter = MessageProcessorSelector.getMessageFormatter(msgContext);
+ OMOutputFormat format = PassThroughTransportUtils.getOMOutputFormat(msgContext);
+ formatter.writeTo(msgContext, format, out, false);
+ }
+
+ if ((msgContext.getProperty(PassThroughConstants.REST_GET_DELETE_INVOKE) != null &&
+ (Boolean) msgContext.getProperty(PassThroughConstants.REST_GET_DELETE_INVOKE))) {
+ pipe.setSerializationCompleteWithoutData(true);
+ }else{
+ pipe.setSerializationComplete(true);
+ }
+
+ }
+ }
+ }
+ }
+
+ /**
+ * Return the IOEventDispatch implementation to be used. This is overridden by the
+ * SSL sender
+ *
+ * @param handler The passthru target handler instance
+ * @param sslContext SSL context used by the sender or null
+ * @param sslIOSessionHandler SSL session handler or null
+ * @param params HTTP parameters
+ * @param trpOut Transport out description
+ * @return an IOEventDispatch instance
+ * @throws AxisFault on error
+ */
+ protected IOEventDispatch getEventDispatch(NHttpClientHandler handler,
+ SSLContext sslContext,
+ SSLSetupHandler sslIOSessionHandler,
+ HttpParams params, TransportOutDescription trpOut) throws AxisFault {
+
+ return new TargetIOEventDispatch(handler, params);
+ }
+
+ /**
+ * Always return null, as this implementation does not support outgoing SSL
+ *
+ * @param transportOut The transport out description
+ * @return null
+ * @throws AxisFault on error
+ */
+ protected SSLContext getSSLContext(TransportOutDescription transportOut) throws AxisFault {
+ return null;
+ }
+
+ /**
+ * Create the SSL IO Session handler to be used by this listener
+ *
+ * @param transportOut Transport out description
+ * @return always null
+ * @throws AxisFault on error
+ */
+ protected SSLSetupHandler getSSLSetupHandler(TransportOutDescription transportOut)
+ throws AxisFault {
+ return null;
+ }
+
+ public void submitResponse(MessageContext msgContext)
+ throws IOException, HttpException {
+ SourceConfiguration sourceConfiguration = (SourceConfiguration) msgContext.getProperty(
+ PassThroughConstants.PASS_THROUGH_SOURCE_CONFIGURATION);
+
+ NHttpServerConnection conn = (NHttpServerConnection) msgContext.getProperty(
+ PassThroughConstants.PASS_THROUGH_SOURCE_CONNECTION);
+ if (conn == null) {
+ ServerWorker serverWorker = (ServerWorker) msgContext.getProperty(Constants.OUT_TRANSPORT_INFO);
+ if (serverWorker != null) {
+ MessageContext requestContext = serverWorker.getRequestContext();
+ conn = (NHttpServerConnection) requestContext.getProperty(
+ PassThroughConstants.PASS_THROUGH_SOURCE_CONNECTION);
+ sourceConfiguration = (SourceConfiguration) requestContext.getProperty(
+ PassThroughConstants.PASS_THROUGH_SOURCE_CONFIGURATION);
+ } else {
+ throw new IllegalStateException("Unable to correlate the response to a request");
+ }
+ }
+
+ SourceRequest sourceRequest = SourceContext.getRequest(conn);
+
+ SourceResponse sourceResponse = SourceResponseFactory.create(msgContext,
+ sourceRequest, sourceConfiguration);
+
+ SourceContext.setResponse(conn, sourceResponse);
+
+ Boolean noEntityBody = (Boolean) msgContext.getProperty(PassThroughConstants.NO_ENTITY_BODY);
+ Pipe pipe = (Pipe) msgContext.getProperty(PassThroughConstants.PASS_THROUGH_PIPE);
+ if ((noEntityBody == null || !noEntityBody) || pipe != null) {
+ if (pipe == null) {
+ pipe = new Pipe(sourceConfiguration.getBufferFactory().getBuffer(),
+ "Test", sourceConfiguration);
+ msgContext.setProperty(PassThroughConstants.PASS_THROUGH_PIPE, pipe);
+ msgContext.setProperty(PassThroughConstants.MESSAGE_BUILDER_INVOKED, Boolean.TRUE);
+ }
+
+ pipe.attachConsumer(conn);
+ sourceResponse.connect(pipe);
+ }
+
+ Integer errorCode = (Integer) msgContext.getProperty(PassThroughConstants.ERROR_CODE);
+ if (errorCode != null) {
+ sourceResponse.setStatus(HttpStatus.SC_BAD_GATEWAY);
+ SourceContext.get(conn).setShutDown(true);
+ }
+
+ ProtocolState state = SourceContext.getState(conn);
+ if (state != null && state.compareTo(ProtocolState.REQUEST_DONE) <= 0) {
+ // start sending the response if we
+ if (msgContext.isPropertyTrue(PassThroughConstants.MESSAGE_BUILDER_INVOKED) && pipe != null) {
+ OutputStream out = pipe.getOutputStream();
+ if (msgContext.isPropertyTrue(NhttpConstants.SC_ACCEPTED)) {
+ out.write(new byte[0]);
+ }else {
+ MessageFormatter formatter = MessageProcessorSelector.getMessageFormatter(msgContext);
+ OMOutputFormat format = PassThroughTransportUtils.getOMOutputFormat(msgContext);
+ formatter.writeTo(msgContext, format, out, false);
+ }
+ pipe.setSerializationComplete(true);
+ out.close();
+ }
+
+ if(noEntityBody != null && Boolean.TRUE == noEntityBody && pipe != null){
+ OutputStream out = pipe.getOutputStream();
+ out.write(new byte[0]);
+ pipe.setRawSerializationComplete(true);
+ out.close();
+ }
+ conn.requestOutput();
+ } else {
+ // nothing much to do as we have started the response already
+ if (errorCode != null) {
+ if (log.isDebugEnabled()) {
+ log.warn("A Source connection is closed because of an " +
+ "error in target: " + conn);
+ }
+ } else {
+ log.debug("A Source Connection is closed, because source handler " +
+ "is already in the process of writing a response while " +
+ "another response is submitted: " + conn);
+ }
+
+ SourceContext.updateState(conn, ProtocolState.CLOSED);
+ sourceConfiguration.getSourceConnections().shutDownConnection(conn);
+ }
+ }
+
+ public void pause() throws AxisFault {
+ if (state != BaseConstants.STARTED) {
+ return;
+ }
+ state = BaseConstants.PAUSED;
+ log.info(namePrefix + " Sender Paused");
+ }
+
+ public void resume() throws AxisFault {
+ if (state != BaseConstants.PAUSED) {
+ return;
+ }
+ state = BaseConstants.STARTED;
+ log.info(namePrefix + " Sender Resumed");
+ }
+
+ public void maintenanceShutdown(long millis) throws AxisFault {
+ if (state != BaseConstants.STARTED) return;
+ try {
+ long start = System.currentTimeMillis();
+ ioReactor.shutdown(millis);
+ state = BaseConstants.STOPPED;
+ log.info("Sender shutdown in : " + (System.currentTimeMillis() - start) / 1000 + "s");
+ } catch (IOException e) {
+ handleException("Error shutting down the IOReactor for maintenence", e);
+ }
+ }
+
+ private void handleException(String s, Exception e) throws AxisFault {
+ log.error(s, e);
+ throw new AxisFault(s, e);
+ }
+
+ private void handleException(String msg) throws AxisFault {
+ log.error(msg);
+ throw new AxisFault(msg);
+ }
+}
Added: synapse/trunk/java/modules/transports/core/nhttp/src/main/java/org/apache/synapse/transport/passthru/Pipe.java
URL: http://svn.apache.org/viewvc/synapse/trunk/java/modules/transports/core/nhttp/src/main/java/org/apache/synapse/transport/passthru/Pipe.java?rev=1502663&view=auto
==============================================================================
--- synapse/trunk/java/modules/transports/core/nhttp/src/main/java/org/apache/synapse/transport/passthru/Pipe.java (added)
+++ synapse/trunk/java/modules/transports/core/nhttp/src/main/java/org/apache/synapse/transport/passthru/Pipe.java Fri Jul 12 19:25:40 2013
@@ -0,0 +1,493 @@
+/*
+ * 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.synapse.transport.passthru;
+
+import org.apache.http.nio.IOControl;
+import org.apache.http.nio.ContentDecoder;
+import org.apache.http.nio.ContentEncoder;
+import org.apache.synapse.transport.passthru.config.BaseConfiguration;
+
+import java.io.*;
+import java.nio.ByteBuffer;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.locks.Condition;
+import java.util.concurrent.locks.Lock;
+import java.util.concurrent.locks.ReentrantLock;
+
+/**
+ * This is a buffer shared by both producers and consumers.
+ */
+public class Pipe {
+
+ /** IOControl of the reader */
+ private IOControl producerIoControl;
+
+ /** IOControl of the consumer */
+ private IOControl consumerIoControl;
+
+ /** Fixed size buffer to read and write data */
+ private ByteBuffer buffer;
+
+ private ByteBuffer outputBuffer;
+
+ private boolean producerCompleted = false;
+
+ public boolean isProducerCompleted() {
+ return producerCompleted;
+ }
+
+ /** Lock to synchronize the producers and consumers */
+ private Lock lock = new ReentrantLock();
+
+ private Condition readCondition = lock.newCondition();
+ private Condition writeCondition = lock.newCondition();
+
+ /** Name to identify the buffer */
+ private String name = "Buffer";
+
+ private boolean consumerError = false;
+
+ private boolean producerError = false;
+
+ private BaseConfiguration baseConfig;
+
+ private boolean serializationComplete = false;
+
+ private boolean rawSerializationComplete = false;
+
+ private boolean hasHttpProducer = true;
+
+ private AtomicBoolean inBufferInputMode = new AtomicBoolean(true);
+ private AtomicBoolean outBufferInputMode;
+
+ private ByteBufferInputStream inputStream;
+ private ByteBufferOutputStream outputStream;
+
+ public Pipe(IOControl producerIoControl, ByteBuffer buffer,
+ String name, BaseConfiguration baseConfig) {
+ this.producerIoControl = producerIoControl;
+ this.buffer = buffer;
+ this.name += "_" + name;
+ this.baseConfig = baseConfig;
+ }
+
+ public Pipe(ByteBuffer buffer, String name, BaseConfiguration baseConfig) {
+ this.buffer = buffer;
+ this.name += "_" + name;
+ this.baseConfig = baseConfig;
+ this.hasHttpProducer = false;
+ }
+
+ /**
+ * Set the consumers IOControl
+ * @param consumerIoControl IOControl of the consumer
+ */
+ public void attachConsumer(IOControl consumerIoControl) {
+ this.consumerIoControl = consumerIoControl;
+ }
+
+ /**
+ * Consume the data from the buffer. Before calling this method attachConsumer
+ * method must be called with a valid IOControl.
+ *
+ * @param encoder encoder used to write the data means there will not be any data
+ * written in to this buffer
+ * @return number of bytes written (consumed)
+ * @throws IOException if an error occurred while consuming data
+ */
+ public int consume(final ContentEncoder encoder) throws IOException {
+ if (consumerIoControl == null) {
+ throw new IllegalStateException("Consumer cannot be null when calling consume");
+ }
+
+ if (hasHttpProducer && producerIoControl == null) {
+ throw new IllegalStateException("Producer cannot be null when calling consume");
+ }
+
+ lock.lock();
+ ByteBuffer consumerBuffer;
+ AtomicBoolean inputMode;
+ if (outputBuffer != null) {
+ consumerBuffer = outputBuffer;
+ inputMode = outBufferInputMode;
+ } else {
+ consumerBuffer = buffer;
+ inputMode = inBufferInputMode;
+ }
+ try {
+ // if producer at error we have to stop the encoding and return immediately
+ if (producerError) {
+ encoder.complete();
+ return -1;
+ }
+
+ setOutputMode(consumerBuffer, inputMode);
+ int bytesWritten = encoder.write(consumerBuffer);
+ setInputMode(consumerBuffer, inputMode);
+
+ if (consumerBuffer.position() == 0) {
+ if (outputBuffer == null) {
+ if (producerCompleted) {
+ encoder.complete();
+ } else {
+ // buffer is empty. Wait until the producer fills up
+ // the buffer
+ consumerIoControl.suspendOutput();
+ }
+ } else if (serializationComplete || rawSerializationComplete) {
+ encoder.complete();
+ }
+ }
+
+ if (bytesWritten > 0) {
+ if (!encoder.isCompleted() && !producerCompleted && hasHttpProducer) {
+ producerIoControl.requestInput();
+ }
+ writeCondition.signalAll();
+ }
+
+ return bytesWritten;
+ } finally {
+ lock.unlock();
+ }
+ }
+
+ /**
+ * Produce data in to the buffer.
+ *
+ * @param decoder decoder to read bytes from the underlying stream
+ * @return bytes read (consumed)
+ * @throws IOException if an error occurs while reading data
+ */
+ public int produce(final ContentDecoder decoder) throws IOException {
+ if (producerIoControl == null) {
+ throw new IllegalStateException("Producer cannot be null when calling produce");
+ }
+
+ lock.lock();
+ try {
+ setInputMode(buffer, inBufferInputMode);
+ int bytesRead = decoder.read(buffer);
+
+ // if consumer is at error we have to let the producer complete
+ if (consumerError) {
+ buffer.clear();
+ }
+
+ if (!buffer.hasRemaining()) {
+ // Input buffer is full. Suspend client input
+ // until the origin handler frees up some space in the buffer
+ producerIoControl.suspendInput();
+ }
+
+ // If there is some content in the input buffer make sure consumer output is active
+ if (buffer.position() > 0 || decoder.isCompleted()) {
+ if (consumerIoControl != null) {
+ consumerIoControl.requestOutput();
+ }
+ readCondition.signalAll();
+ }
+
+ if (decoder.isCompleted()) {
+ producerCompleted = true;
+ }
+ return bytesRead;
+ } finally {
+ lock.unlock();
+ }
+ }
+
+ @Override
+ public String toString() {
+ return name;
+ }
+
+ public void consumerError() {
+ lock.lock();
+ try {
+ this.consumerError = true;
+ writeCondition.signalAll();
+ } finally {
+ lock.unlock();
+ }
+ }
+
+ public void producerError() {
+ lock.lock();
+ try {
+ this.producerError = true;
+ readCondition.signalAll();
+ } finally {
+ lock.unlock();
+ }
+ }
+
+ /**
+ * Creates an InputStream object on the underlying ByteBuffer. The returned
+ * InputStream can be used to read bytes from the underlying buffer which
+ * is being filled by the producer.
+ *
+ * @return An InputStream object
+ */
+ public synchronized InputStream getInputStream() {
+ if (inputStream == null) {
+ inputStream = new ByteBufferInputStream();
+ }
+ return inputStream;
+ }
+
+ /**
+ * Creates a separate ByteBuffer for the output data and returns an OutputStream
+ * on top of it.
+ *
+ * @return An OutputStream object
+ */
+ public synchronized OutputStream getOutputStream() {
+ if (outputStream == null) {
+ outputBuffer = baseConfig.getBufferFactory().getBuffer();
+ outBufferInputMode = new AtomicBoolean(true);
+ outputStream = new ByteBufferOutputStream();
+ }
+ return outputStream;
+ }
+
+
+ /**
+ * Creates a separate ByteBuffer for the output data and returns an OutputStream
+ * on top of it.
+ *
+ * @return An OutputStream object
+ */
+ public synchronized OutputStream resetOutputStream() {
+ outputBuffer = baseConfig.getBufferFactory().getBuffer();
+ outBufferInputMode = new AtomicBoolean(true);
+ outputStream = new ByteBufferOutputStream();
+ return outputStream;
+ }
+
+
+ public synchronized void resetBufferPossition() {
+ if(buffer != null){
+ buffer.rewind();
+ }
+
+ if(outputBuffer != null){
+ outputBuffer.rewind();
+ }
+ }
+
+ public synchronized void setSerializationComplete(boolean serializationComplete) {
+ if (!this.serializationComplete) {
+ this.serializationComplete = serializationComplete;
+ if (consumerIoControl != null && hasData(outputBuffer, outBufferInputMode)) {
+ consumerIoControl.requestOutput();
+ }
+ }
+ }
+
+ public synchronized void setSerializationCompleteWithoutData(boolean serializationComplete) {
+ if (!this.serializationComplete) {
+ this.serializationComplete = serializationComplete;
+ consumerIoControl.requestOutput();
+ }
+ }
+
+ public void setRawSerializationComplete(boolean rawSerializationComplete) {
+ this.rawSerializationComplete = rawSerializationComplete;
+ }
+
+ public void forceSetSerializationRest(){
+ if(this.serializationComplete){
+ this.serializationComplete = false;
+ }
+ }
+
+
+
+
+ public boolean isSerializationComplete() {
+ return serializationComplete;
+ }
+
+ public ByteBuffer getBuffer() {
+ return buffer;
+ }
+
+ public boolean hasHttpProducer() {
+ return hasHttpProducer;
+ }
+
+ private void setInputMode(ByteBuffer buffer, AtomicBoolean inputMode) {
+ if (inputMode.compareAndSet(false, true)) {
+ if (buffer.hasRemaining()) {
+ buffer.compact();
+ } else {
+ buffer.clear();
+ }
+ }
+ }
+
+ private void setOutputMode(ByteBuffer buffer, AtomicBoolean inputMode) {
+ if (inputMode.compareAndSet(true, false)) {
+ buffer.flip();
+ }
+ }
+
+ private boolean hasData(ByteBuffer buffer, AtomicBoolean inputMode) {
+ lock.lock();
+ try {
+ setOutputMode(buffer, inputMode);
+ return buffer.hasRemaining();
+ } finally {
+ lock.unlock();
+ }
+ }
+
+ private class ByteBufferInputStream extends InputStream {
+
+ @Override
+ public int read() throws IOException {
+ lock.lock();
+ try {
+ if (!hasData(buffer, inBufferInputMode)) {
+ waitForData();
+ }
+ if (isEndOfStream()) {
+ return -1;
+ }
+ return buffer.get() & 0xff;
+ } finally {
+ lock.unlock();
+ }
+ }
+
+ public int read(byte[] b, int off, int len) throws IOException {
+ if (b == null) {
+ return 0;
+ }
+
+ lock.lock();
+ try {
+ if (!hasData(buffer, inBufferInputMode)) {
+ waitForData();
+ }
+ if (isEndOfStream()) {
+ return -1;
+ }
+ setOutputMode(buffer, inBufferInputMode);
+ int chunk = len;
+ if (chunk > buffer.remaining()) {
+ chunk = buffer.remaining();
+ }
+ buffer.get(b, off, chunk);
+ return chunk;
+ } finally {
+ lock.unlock();
+ }
+ }
+
+ private void waitForData() throws IOException {
+ lock.lock();
+ try {
+ try {
+ while (!hasData(buffer, inBufferInputMode) && !producerCompleted) {
+ producerIoControl.requestInput();
+ readCondition.await();
+ }
+ } catch (InterruptedException e) {
+ throw new IOException("Interrupted while waiting for data");
+ }
+ } finally {
+ lock.unlock();
+ }
+ }
+
+ private boolean isEndOfStream() {
+ return !hasData(buffer, inBufferInputMode) && producerCompleted;
+ }
+ }
+
+ private class ByteBufferOutputStream extends OutputStream {
+
+ @Override
+ public void write(int b) throws IOException {
+ lock.lock();
+ try {
+ setInputMode(outputBuffer, outBufferInputMode);
+ if (!outputBuffer.hasRemaining()) {
+ flushContent();
+ setInputMode(outputBuffer, outBufferInputMode);
+ }
+ outputBuffer.put((byte) b);
+ } finally {
+ lock.unlock();
+ }
+ }
+
+ public void write(final byte[] b, int off, int len) throws IOException {
+ if (b == null) {
+ return;
+ }
+ lock.lock();
+ try {
+ setInputMode(outputBuffer, outBufferInputMode);
+ int remaining = len;
+ while (remaining > 0) {
+ if (!outputBuffer.hasRemaining()) {
+ flushContent();
+ setInputMode(outputBuffer, outBufferInputMode);
+ }
+ int chunk = Math.min(remaining, outputBuffer.remaining());
+ outputBuffer.put(b, off, chunk);
+ remaining -= chunk;
+ off += chunk;
+ }
+ } finally {
+ lock.unlock();
+ }
+ }
+
+ private void flushContent() throws IOException {
+ lock.lock();
+
+ if(rawSerializationComplete){
+ return;
+ }
+
+ try {
+ try {
+ while (hasData(outputBuffer, outBufferInputMode)) {
+ if (consumerIoControl != null && writeCondition != null) {
+ consumerIoControl.requestOutput();
+ writeCondition.await();
+ }
+ }
+
+ } catch (InterruptedException ex) {
+ throw new IOException("Interrupted while flushing the content buffer");
+ }
+ } finally {
+ lock.unlock();
+ }
+ }
+ }
+
+}
+
Added: synapse/trunk/java/modules/transports/core/nhttp/src/main/java/org/apache/synapse/transport/passthru/ProtocolState.java
URL: http://svn.apache.org/viewvc/synapse/trunk/java/modules/transports/core/nhttp/src/main/java/org/apache/synapse/transport/passthru/ProtocolState.java?rev=1502663&view=auto
==============================================================================
--- synapse/trunk/java/modules/transports/core/nhttp/src/main/java/org/apache/synapse/transport/passthru/ProtocolState.java (added)
+++ synapse/trunk/java/modules/transports/core/nhttp/src/main/java/org/apache/synapse/transport/passthru/ProtocolState.java Fri Jul 12 19:25:40 2013
@@ -0,0 +1,48 @@
+/*
+* 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.synapse.transport.passthru;
+
+/**
+ * State of a request or a response in transport receiver or sender
+ * is represented in these values.
+ */
+public enum ProtocolState {
+ /** Connection is at the initial stage ready to receive a request */
+ REQUEST_READY,
+ /** The connection is reading the request headers */
+ REQUEST_HEAD,
+ /** The connection is reading the request body */
+ REQUEST_BODY,
+ /** Request is completely received */
+ REQUEST_DONE,
+ /** The connection is reading the response headers */
+ RESPONSE_HEAD,
+ /** The connection si reading the response body */
+ RESPONSE_BODY,
+ /** The response is completed */
+ RESPONSE_DONE,
+ /** The connection is closing */
+ CLOSING,
+ /** The connection is closed */
+ CLOSED,
+
+ WSDL_RESPONSE_DONE
+}
Added: synapse/trunk/java/modules/transports/core/nhttp/src/main/java/org/apache/synapse/transport/passthru/SSLSourceIOEventDispatch.java
URL: http://svn.apache.org/viewvc/synapse/trunk/java/modules/transports/core/nhttp/src/main/java/org/apache/synapse/transport/passthru/SSLSourceIOEventDispatch.java?rev=1502663&view=auto
==============================================================================
--- synapse/trunk/java/modules/transports/core/nhttp/src/main/java/org/apache/synapse/transport/passthru/SSLSourceIOEventDispatch.java (added)
+++ synapse/trunk/java/modules/transports/core/nhttp/src/main/java/org/apache/synapse/transport/passthru/SSLSourceIOEventDispatch.java Fri Jul 12 19:25:40 2013
@@ -0,0 +1,52 @@
+/*
+ * 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.synapse.transport.passthru;
+
+import org.apache.http.impl.nio.reactor.SSLSetupHandler;
+import org.apache.http.impl.nio.ssl.SSLServerIOEventDispatch;
+import org.apache.http.nio.NHttpServerIOTarget;
+import org.apache.http.nio.NHttpServiceHandler;
+import org.apache.http.nio.reactor.IOSession;
+import org.apache.http.params.HttpParams;
+import org.apache.synapse.transport.passthru.logging.LoggingUtils;
+
+import javax.net.ssl.SSLContext;
+
+public class SSLSourceIOEventDispatch extends SSLServerIOEventDispatch {
+
+ private HttpParams params = null;
+
+ public SSLSourceIOEventDispatch(NHttpServiceHandler handler,
+ SSLContext sslcontext,
+ SSLSetupHandler sslHandler,
+ HttpParams params) {
+ super(handler, sslcontext, sslHandler, params);
+ this.params = params;
+ }
+
+ @Override
+ protected NHttpServerIOTarget createConnection(IOSession session) {
+ session = LoggingUtils.decorate(session, "sslserver");
+ return LoggingUtils.createServerConnection(
+ session,
+ createHttpRequestFactory(),
+ createByteBufferAllocator(),
+ this.params);
+ }
+}