Search in sources :

Example 11 with TransportOutDescription

use of org.apache.axis2.description.TransportOutDescription in project wso2-synapse by wso2.

the class PassThroughHttpSender method init.

public void init(ConfigurationContext configurationContext, TransportOutDescription transportOutDescription) throws AxisFault {
    log.info("Initializing Pass-through HTTP/S Sender...");
    namePrefix = transportOutDescription.getName().toUpperCase(Locale.US);
    scheme = getScheme();
    WorkerPool workerPool = null;
    Object obj = configurationContext.getProperty(PassThroughConstants.PASS_THROUGH_TRANSPORT_WORKER_POOL);
    if (obj != null) {
        workerPool = (WorkerPool) obj;
    }
    PassThroughTransportMetricsCollector metrics = new PassThroughTransportMetricsCollector(false, scheme.getName());
    TransportView view = new TransportView(null, this, metrics, null);
    MBeanRegistrar.getInstance().registerMBean(view, "Transport", "passthru-" + namePrefix.toLowerCase() + "-sender");
    proxyConfig = new ProxyConfigBuilder().build(transportOutDescription);
    log.info(proxyConfig.logProxyConfig());
    targetConfiguration = new TargetConfiguration(configurationContext, transportOutDescription, workerPool, metrics, proxyConfig.createProxyAuthenticator());
    targetConfiguration.build();
    PassThroughSenderManager.registerPassThroughHttpSender(this);
    configurationContext.setProperty(PassThroughConstants.PASS_THROUGH_TRANSPORT_WORKER_POOL, targetConfiguration.getWorkerPool());
    ClientConnFactoryBuilder connFactoryBuilder = initConnFactoryBuilder(transportOutDescription);
    connFactory = connFactoryBuilder.createConnFactory(targetConfiguration.getHttpParams());
    try {
        String prefix = namePrefix + "-Sender I/O dispatcher";
        ioReactor = new DefaultConnectingIOReactor(targetConfiguration.getIOReactorConfig(), new NativeThreadFactory(new ThreadGroup(prefix + " Thread Group"), prefix));
        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();
    targetConnections = new TargetConnections(ioReactor, targetConfiguration, connectCallback);
    targetConfiguration.setConnections(targetConnections);
    // create the delivery agent to hand over messages
    deliveryAgent = new DeliveryAgent(targetConfiguration, targetConnections, proxyConfig);
    // we need to set the delivery agent
    connectCallback.setDeliveryAgent(deliveryAgent);
    handler = new TargetHandler(deliveryAgent, connFactory, targetConfiguration);
    ioEventDispatch = new ClientIODispatch(handler, connFactory);
    // 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...");
}
Also used : IOReactorExceptionHandler(org.apache.http.nio.reactor.IOReactorExceptionHandler) ProxyConfigBuilder(org.apache.synapse.transport.nhttp.config.ProxyConfigBuilder) TargetConfiguration(org.apache.synapse.transport.passthru.config.TargetConfiguration) ClientConnFactoryBuilder(org.apache.synapse.transport.nhttp.config.ClientConnFactoryBuilder) PassThroughTransportMetricsCollector(org.apache.synapse.transport.passthru.jmx.PassThroughTransportMetricsCollector) NativeThreadFactory(org.apache.axis2.transport.base.threads.NativeThreadFactory) IOException(java.io.IOException) XMLStreamException(javax.xml.stream.XMLStreamException) RemoteException(java.rmi.RemoteException) HttpException(org.apache.http.HttpException) IOException(java.io.IOException) IOReactorException(org.apache.http.nio.reactor.IOReactorException) DefaultConnectingIOReactor(org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor) IOReactorException(org.apache.http.nio.reactor.IOReactorException) WorkerPool(org.apache.axis2.transport.base.threads.WorkerPool) TransportView(org.apache.synapse.transport.passthru.jmx.TransportView) TargetConnections(org.apache.synapse.transport.passthru.connections.TargetConnections)

Example 12 with TransportOutDescription

use of org.apache.axis2.description.TransportOutDescription in project wso2-synapse by wso2.

the class HttpCoreNIOSender method init.

/**
 * Initialize the transport sender, and execute reactor in new separate thread
 * @param cfgCtx the Axis2 configuration context
 * @param transportOut the description of the http/s transport from Axis2 configuration
 * @throws AxisFault thrown on an error
 */
public void init(ConfigurationContext cfgCtx, TransportOutDescription transportOut) throws AxisFault {
    this.configurationContext = cfgCtx;
    cfg = NHttpConfiguration.getInstance();
    params = new BasicHttpParams();
    params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, cfg.getProperty(NhttpConstants.SO_TIMEOUT_SENDER, 60000)).setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, cfg.getProperty(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000)).setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, cfg.getProperty(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)).setParameter(CoreProtocolPNames.USER_AGENT, "Synapse-HttpComponents-NIO");
    // .setParameter(CoreProtocolPNames.HTTP_ELEMENT_CHARSET,
    // cfg.getStringValue(CoreProtocolPNames.HTTP_ELEMENT_CHARSET,HTTP.DEFAULT_PROTOCOL_CHARSET)); //TODO:This does not works with HTTPCore 4.3
    name = transportOut.getName().toUpperCase(Locale.US) + " Sender";
    ClientConnFactoryBuilder contextBuilder = initConnFactoryBuilder(transportOut);
    connFactory = contextBuilder.createConnFactory(params);
    connpool = new ConnectionPool();
    proxyConfig = new ProxyConfigBuilder().build(transportOut);
    log.info(proxyConfig.logProxyConfig());
    Parameter param = transportOut.getParameter("warnOnHTTP500");
    if (param != null) {
        String[] warnOnHttp500 = ((String) param.getValue()).split("\\|");
        cfgCtx.setNonReplicableProperty("warnOnHTTP500", warnOnHttp500);
    }
    IOReactorConfig ioReactorConfig = new IOReactorConfig();
    ioReactorConfig.setIoThreadCount(NHttpConfiguration.getInstance().getClientIOWorkers());
    ioReactorConfig.setSoTimeout(cfg.getProperty(NhttpConstants.SO_TIMEOUT_RECEIVER, 60000));
    ioReactorConfig.setConnectTimeout(cfg.getProperty(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000));
    ioReactorConfig.setTcpNoDelay(cfg.getProperty(CoreConnectionPNames.TCP_NODELAY, 1) == 1);
    if (cfg.getBooleanValue("http.nio.interest-ops-queueing", false)) {
        ioReactorConfig.setInterestOpQueued(true);
    }
    try {
        String prefix = name + " I/O dispatcher";
        ioReactor = new DefaultConnectingIOReactor(ioReactorConfig, new NativeThreadFactory(new ThreadGroup(prefix + " thread group"), prefix));
        ioReactor.setExceptionHandler(new IOReactorExceptionHandler() {

            public boolean handle(IOException ioException) {
                log.warn("System may be unstable: IOReactor encountered a checked exception : " + ioException.getMessage(), ioException);
                return true;
            }

            public boolean handle(RuntimeException runtimeException) {
                log.warn("System may be unstable: IOReactor encountered a runtime exception : " + runtimeException.getMessage(), runtimeException);
                return true;
            }
        });
    } catch (IOException e) {
        log.error("Error starting the IOReactor", e);
        throw new AxisFault(e.getMessage(), e);
    }
    metrics = new NhttpMetricsCollector(false, transportOut.getName());
    handler = new ClientHandler(connpool, connFactory, proxyConfig, cfgCtx, params, metrics);
    iodispatch = new ClientIODispatch(handler, connFactory);
    final IOEventDispatch ioEventDispatch = iodispatch;
    // start the Sender in a new seperate thread
    Thread t = new Thread(new Runnable() {

        public void run() {
            try {
                ioReactor.execute(ioEventDispatch);
            } catch (InterruptedIOException ex) {
                log.fatal("Reactor Interrupted");
            } catch (IOException e) {
                log.fatal("Encountered an I/O error: " + e.getMessage(), e);
            }
            log.info(name + " Shutdown");
        }
    }, "HttpCoreNIOSender");
    t.start();
    log.info(name + " starting");
    // register with JMX
    mbeanSupport = new TransportMBeanSupport(this, "nio-" + transportOut.getName());
    mbeanSupport.register();
    state = BaseConstants.STARTED;
}
Also used : IOReactorExceptionHandler(org.apache.http.nio.reactor.IOReactorExceptionHandler) AxisFault(org.apache.axis2.AxisFault) InterruptedIOException(java.io.InterruptedIOException) ProxyConfigBuilder(org.apache.synapse.transport.nhttp.config.ProxyConfigBuilder) ClientConnFactoryBuilder(org.apache.synapse.transport.nhttp.config.ClientConnFactoryBuilder) NhttpMetricsCollector(org.apache.synapse.transport.nhttp.util.NhttpMetricsCollector) TransportMBeanSupport(org.apache.axis2.transport.base.TransportMBeanSupport) NativeThreadFactory(org.apache.axis2.transport.base.threads.NativeThreadFactory) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) IOReactorConfig(org.apache.http.impl.nio.reactor.IOReactorConfig) DefaultConnectingIOReactor(org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor) Parameter(org.apache.axis2.description.Parameter) IOEventDispatch(org.apache.http.nio.reactor.IOEventDispatch) BasicHttpParams(org.apache.http.params.BasicHttpParams)

Example 13 with TransportOutDescription

use of org.apache.axis2.description.TransportOutDescription in project wso2-synapse by wso2.

the class ClientConnFactoryBuilder method loadDynamicSSLConfig.

/**
 * Extracts Dynamic SSL profiles configuration from given TransportOut Configuration
 *
 * @param transportOut TransportOut Configuration of the connection
 * @return TransportOut configuration with extracted Dynamic SSL profiles information
 */
public TransportOutDescription loadDynamicSSLConfig(TransportOutDescription transportOut) {
    Parameter profilePathParam = transportOut.getParameter("dynamicSSLProfilesConfig");
    // No Separate configuration file configured. Therefore using Axis2 Configuration
    if (profilePathParam == null) {
        return transportOut;
    }
    // Using separate SSL Profile configuration file, ignore Axis2 configurations
    OMElement pathEl = profilePathParam.getParameterElement();
    String path = pathEl.getFirstChildWithName(new QName("filePath")).getText();
    try {
        if (path != null) {
            String separator = path.startsWith(System.getProperty("file.separator")) ? "" : System.getProperty("file.separator");
            String fullPath = System.getProperty("user.dir") + separator + path;
            OMElement profileEl = new StAXOMBuilder(fullPath).getDocumentElement();
            Parameter profileParam = new Parameter();
            profileParam.setParameterElement(profileEl);
            profileParam.setName("customSSLProfiles");
            profileParam.setValue(profileEl);
            transportOut.addParameter(profileParam);
            log.info("customSSLProfiles configuration is loaded from path: " + fullPath);
            return transportOut;
        }
    } catch (XMLStreamException xmlEx) {
        log.error("XMLStreamException - Could not load customSSLProfiles from file path: " + path, xmlEx);
    } catch (FileNotFoundException fileEx) {
        log.error("FileNotFoundException - Could not load customSSLProfiles from file path: " + path, fileEx);
    } catch (AxisFault axisFault) {
        log.error("AxisFault - Could not load customSSLProfiles from file path: " + path, axisFault);
    } catch (Exception ex) {
        log.error("Exception - Could not load customSSLProfiles from file path: " + path, ex);
    }
    return null;
}
Also used : AxisFault(org.apache.axis2.AxisFault) XMLStreamException(javax.xml.stream.XMLStreamException) QName(javax.xml.namespace.QName) FileNotFoundException(java.io.FileNotFoundException) Parameter(org.apache.axis2.description.Parameter) OMElement(org.apache.axiom.om.OMElement) StAXOMBuilder(org.apache.axiom.om.impl.builder.StAXOMBuilder) GeneralSecurityException(java.security.GeneralSecurityException) XMLStreamException(javax.xml.stream.XMLStreamException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException)

Example 14 with TransportOutDescription

use of org.apache.axis2.description.TransportOutDescription in project wso2-synapse by wso2.

the class ClientConnFactoryBuilder method getCustomSSLContexts.

/**
 * 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 {
    TransportOutDescription customSSLProfileTransport = loadDynamicSSLConfig(transportOut);
    Parameter customProfilesParam = customSSLProfileTransport.getParameter("customSSLProfiles");
    if (customProfilesParam == null) {
        return null;
    }
    if (log.isInfoEnabled()) {
        log.info(name + " Loading custom SSL profiles for the HTTPS sender");
    }
    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(name + " " + 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 {
                if (log.isWarnEnabled()) {
                    log.warn(name + " Multiple SSL profiles were found for the server : " + server + ". Ignoring the excessive profiles.");
                }
            }
        }
    }
    if (contextMap.size() > 0) {
        if (log.isInfoEnabled()) {
            log.info(name + " Custom SSL profiles initialized for " + contextMap.size() + " servers");
        }
        return contextMap;
    }
    return null;
}
Also used : AxisFault(org.apache.axis2.AxisFault) HashMap(java.util.HashMap) QName(javax.xml.namespace.QName) Parameter(org.apache.axis2.description.Parameter) OMElement(org.apache.axiom.om.OMElement) SSLContext(javax.net.ssl.SSLContext) TransportOutDescription(org.apache.axis2.description.TransportOutDescription)

Example 15 with TransportOutDescription

use of org.apache.axis2.description.TransportOutDescription in project wso2-synapse by wso2.

the class ProxyConfigBuilder method build.

/**
 * Tries to read the axis2.xml transport sender's proxy configuration
 * @param transportOut axis2 transport out description
 * @return ProxyConfig
 * @throws AxisFault
 */
public ProxyConfig build(TransportOutDescription transportOut) throws AxisFault {
    name = transportOut.getName();
    Map<String, ProxyProfileConfig> proxyProfileConfigMap = getProxyProfiles(transportOut);
    // if proxy profile is configured we only read profile related configuration
    if (proxyProfileConfigMap == null) {
        String proxyHost = null;
        int proxyPort = -1;
        Parameter proxyHostParam = transportOut.getParameter(PassThroughConstants.HTTP_PROXY_HOST);
        if (proxyHostParam != null) {
            proxyHost = (String) proxyHostParam.getValue();
            Parameter proxyPortParam = transportOut.getParameter(PassThroughConstants.HTTP_PROXY_PORT);
            if (proxyPortParam != null) {
                proxyPort = Integer.parseInt((String) proxyPortParam.getValue());
            }
        }
        if (proxyHost == null) {
            proxyHost = System.getProperty(PassThroughConstants.HTTP_PROXY_HOST);
            if (proxyHost != null) {
                String s = System.getProperty(PassThroughConstants.HTTP_PROXY_PORT);
                if (s != null) {
                    proxyPort = Integer.parseInt(s);
                }
            }
        }
        if (proxyHost != null) {
            proxy = new HttpHost(proxyHost, proxyPort >= 0 ? proxyPort : 80);
            String bypassListStr = null;
            Parameter bypassListParam = transportOut.getParameter(PassThroughConstants.HTTP_NON_PROXY_HOST);
            if (bypassListParam == null) {
                bypassListStr = System.getProperty(PassThroughConstants.HTTP_NON_PROXY_HOST);
            } else {
                bypassListStr = (String) bypassListParam.getValue();
            }
            if (bypassListStr != null) {
                proxyBypass = bypassListStr.split("\\|");
            }
            Parameter proxyUsernameParam = transportOut.getParameter(PassThroughConstants.HTTP_PROXY_USERNAME);
            Parameter proxyPasswordParam = transportOut.getParameter(PassThroughConstants.HTTP_PROXY_PASSWORD);
            if (proxyUsernameParam != null) {
                proxyCredentials = new UsernamePasswordCredentials((String) proxyUsernameParam.getValue(), proxyPasswordParam != null ? (String) proxyPasswordParam.getValue() : "");
            }
        }
    }
    return new ProxyConfig(proxy, proxyCredentials, proxyBypass, proxyProfileConfigMap);
}
Also used : ProxyProfileConfig(org.apache.synapse.transport.http.conn.ProxyProfileConfig) HttpHost(org.apache.http.HttpHost) Parameter(org.apache.axis2.description.Parameter) ProxyConfig(org.apache.synapse.transport.http.conn.ProxyConfig) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials)

Aggregations

TransportOutDescription (org.apache.axis2.description.TransportOutDescription)28 AxisConfiguration (org.apache.axis2.engine.AxisConfiguration)20 Parameter (org.apache.axis2.description.Parameter)17 ConfigurationContext (org.apache.axis2.context.ConfigurationContext)16 MessageContext (org.apache.axis2.context.MessageContext)11 AxisFault (org.apache.axis2.AxisFault)9 QName (javax.xml.namespace.QName)7 OMElement (org.apache.axiom.om.OMElement)6 AxisService (org.apache.axis2.description.AxisService)6 TransportInDescription (org.apache.axis2.description.TransportInDescription)6 IOException (java.io.IOException)4 Map (java.util.Map)4 ServiceContext (org.apache.axis2.context.ServiceContext)4 Test (org.junit.Test)4 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)4 HashMap (java.util.HashMap)3 OperationContext (org.apache.axis2.context.OperationContext)3 InOutAxisOperation (org.apache.axis2.description.InOutAxisOperation)3 OutTransportInfo (org.apache.axis2.transport.OutTransportInfo)3 VFSOutTransportInfo (org.apache.synapse.commons.vfs.VFSOutTransportInfo)3