flex-messaging-proxy-1.0

16:35:52.129 INFO  jd.cli.Main - Decompiling flex-messaging-proxy-1.0.jar
package flex.management.runtime.messaging.services;

import flex.management.BaseControl;
import flex.messaging.services.HTTPProxyService;
import java.util.Date;

public class HTTPProxyServiceControl
  extends ServiceControl
  implements HTTPProxyServiceControlMBean
{
  private static final String TYPE = "HTTPProxyService";
  private int invokeSOAPCount = 0;
  private Date lastInvokeSOAPTimestamp;
  private long invokeSOAPStart;
  private int invokeHTTPCount = 0;
  private Date lastInvokeHTTPTimestamp;
  private long invokeHTTPStart;
  
  public HTTPProxyServiceControl(HTTPProxyService service, BaseControl parent)
  {
    super(service, parent);
    invokeSOAPStart = System.currentTimeMillis();
    invokeHTTPStart = invokeSOAPStart;
  }
  
  public String getType()
  {
    return "HTTPProxyService";
  }
  
  public Integer getInvokeSOAPCount()
  {
    return new Integer(invokeSOAPCount);
  }
  
  public void resetInvokeSOAPCount()
  {
    invokeSOAPStart = System.currentTimeMillis();
    invokeSOAPCount = 0;
    lastInvokeSOAPTimestamp = null;
  }
  
  public void incrementInvokeSOAPCount()
  {
    invokeSOAPCount += 1;
    lastInvokeSOAPTimestamp = new Date();
  }
  
  public Date getLastInvokeSOAPTimestamp()
  {
    return lastInvokeSOAPTimestamp;
  }
  
  public Double getInvokeSOAPFrequency()
  {
    if (invokeSOAPCount > 0)
    {
      double runtime = differenceInMinutes(invokeSOAPStart, System.currentTimeMillis());
      return new Double(invokeSOAPCount / runtime);
    }
    return new Double(0.0D);
  }
  
  public Integer getInvokeHTTPCount()
  {
    return new Integer(invokeHTTPCount);
  }
  
  public void resetInvokeHTTPCount()
  {
    invokeHTTPStart = System.currentTimeMillis();
    invokeHTTPCount = 0;
    lastInvokeHTTPTimestamp = null;
  }
  
  public void incrementInvokeHTTPCount()
  {
    invokeHTTPCount += 1;
    lastInvokeHTTPTimestamp = new Date();
  }
  
  public Date getLastInvokeHTTPTimestamp()
  {
    return lastInvokeHTTPTimestamp;
  }
  
  public Double getInvokeHTTPFrequency()
  {
    if (invokeHTTPCount > 0)
    {
      double runtime = differenceInMinutes(invokeHTTPStart, System.currentTimeMillis());
      return new Double(invokeHTTPCount / runtime);
    }
    return new Double(0.0D);
  }
}

/* Location:
 * Qualified Name:     flex.management.runtime.messaging.services.HTTPProxyServiceControl
 * Java Class Version: 1.4 (48.0)
 * JD-Core Version:    0.7.1
 */
package flex.management.runtime.messaging.services;

public abstract interface HTTPProxyServiceControlMBean
  extends ServiceControlMBean
{}

/* Location:
 * Qualified Name:     flex.management.runtime.messaging.services.HTTPProxyServiceControlMBean
 * Java Class Version: 1.4 (48.0)
 * JD-Core Version:    0.7.1
 */
package flex.management.runtime.messaging.services.http;

import flex.management.BaseControl;
import flex.management.runtime.messaging.services.ServiceAdapterControl;
import flex.messaging.services.http.HTTPProxyAdapter;

public class HTTPProxyAdapterControl
  extends ServiceAdapterControl
  implements HTTPProxyAdapterControlMBean
{
  private static final String TYPE = "HTTPProxyAdapter";
  
  public HTTPProxyAdapterControl(HTTPProxyAdapter serviceAdapter, BaseControl parent)
  {
    super(serviceAdapter, parent);
  }
  
  public String getType()
  {
    return "HTTPProxyAdapter";
  }
}

/* Location:
 * Qualified Name:     flex.management.runtime.messaging.services.http.HTTPProxyAdapterControl
 * Java Class Version: 1.4 (48.0)
 * JD-Core Version:    0.7.1
 */
package flex.management.runtime.messaging.services.http;

import flex.management.runtime.messaging.services.ServiceAdapterControlMBean;

public abstract interface HTTPProxyAdapterControlMBean
  extends ServiceAdapterControlMBean
{}

/* Location:
 * Qualified Name:     flex.management.runtime.messaging.services.http.HTTPProxyAdapterControlMBean
 * Java Class Version: 1.4 (48.0)
 * JD-Core Version:    0.7.1
 */
package flex.management.runtime.messaging.services.http;

import flex.management.BaseControl;
import flex.management.runtime.AdminConsoleDisplayRegistrar;
import flex.management.runtime.messaging.DestinationControl;
import flex.messaging.services.http.HTTPProxyDestination;
import java.util.Date;
import javax.management.ObjectName;

public class HTTPProxyDestinationControl
  extends DestinationControl
  implements HTTPProxyDestinationControlMBean
{
  private static final String TYPE = "HTTPProxyDestination";
  private int invokeSOAPCount = 0;
  private Date lastInvokeSOAPTimestamp;
  private long invokeSOAPStart;
  private int invokeHTTPCount = 0;
  private Date lastInvokeHTTPTimestamp;
  private long invokeHTTPStart;
  
  public HTTPProxyDestinationControl(HTTPProxyDestination destination, BaseControl parent)
  {
    super(destination, parent);
    invokeSOAPStart = System.currentTimeMillis();
    invokeHTTPStart = invokeSOAPStart;
  }
  
  protected void onRegistrationComplete()
  {
    super.onRegistrationComplete();
    
    String name = getObjectName().getCanonicalName();
    
    String[] pollablePerInterval = { "InvokeHTTPCount", "InvokeSOAPCount" };
    String[] pollableGeneral = { "InvokeHTTPFrequency", "InvokeSOAPFrequency" };
    String[] destinationGeneral = { "LastInvokeHTTPTimestamp", "LastInvokeSOAPTimestamp" };
    
    getRegistrar().registerObjects(new int[] { 151, 50 }, name, pollablePerInterval);
    
    getRegistrar().registerObjects(151, name, pollableGeneral);
    
    getRegistrar().registerObjects(150, name, destinationGeneral);
  }
  
  public Integer getInvokeSOAPCount()
  {
    return new Integer(invokeSOAPCount);
  }
  
  public void resetInvokeSOAPCount()
  {
    invokeSOAPStart = System.currentTimeMillis();
    invokeSOAPCount = 0;
    lastInvokeSOAPTimestamp = null;
  }
  
  public void incrementInvokeSOAPCount()
  {
    invokeSOAPCount += 1;
    lastInvokeSOAPTimestamp = new Date();
  }
  
  public Date getLastInvokeSOAPTimestamp()
  {
    return lastInvokeSOAPTimestamp;
  }
  
  public Double getInvokeSOAPFrequency()
  {
    if (invokeSOAPCount > 0)
    {
      double runtime = differenceInMinutes(invokeSOAPStart, System.currentTimeMillis());
      return new Double(invokeSOAPCount / runtime);
    }
    return new Double(0.0D);
  }
  
  public Integer getInvokeHTTPCount()
  {
    return new Integer(invokeHTTPCount);
  }
  
  public void resetInvokeHTTPCount()
  {
    invokeHTTPStart = System.currentTimeMillis();
    invokeHTTPCount = 0;
    lastInvokeHTTPTimestamp = null;
  }
  
  public void incrementInvokeHTTPCount()
  {
    invokeHTTPCount += 1;
    lastInvokeHTTPTimestamp = new Date();
  }
  
  public Date getLastInvokeHTTPTimestamp()
  {
    return lastInvokeHTTPTimestamp;
  }
  
  public Double getInvokeHTTPFrequency()
  {
    if (invokeHTTPCount > 0)
    {
      double runtime = differenceInMinutes(invokeHTTPStart, System.currentTimeMillis());
      return new Double(invokeHTTPCount / runtime);
    }
    return new Double(0.0D);
  }
  
  public String getType()
  {
    return "HTTPProxyDestination";
  }
}

/* Location:
 * Qualified Name:     flex.management.runtime.messaging.services.http.HTTPProxyDestinationControl
 * Java Class Version: 1.4 (48.0)
 * JD-Core Version:    0.7.1
 */
package flex.management.runtime.messaging.services.http;

import flex.management.runtime.messaging.DestinationControlMBean;
import java.io.IOException;
import java.util.Date;

public abstract interface HTTPProxyDestinationControlMBean
  extends DestinationControlMBean
{
  public abstract Integer getInvokeSOAPCount()
    throws IOException;
  
  public abstract void resetInvokeSOAPCount()
    throws IOException;
  
  public abstract Date getLastInvokeSOAPTimestamp()
    throws IOException;
  
  public abstract Double getInvokeSOAPFrequency()
    throws IOException;
  
  public abstract Integer getInvokeHTTPCount()
    throws IOException;
  
  public abstract void resetInvokeHTTPCount()
    throws IOException;
  
  public abstract Date getLastInvokeHTTPTimestamp()
    throws IOException;
  
  public abstract Double getInvokeHTTPFrequency()
    throws IOException;
}

/* Location:
 * Qualified Name:     flex.management.runtime.messaging.services.http.HTTPProxyDestinationControlMBean
 * Java Class Version: 1.4 (48.0)
 * JD-Core Version:    0.7.1
 */
package flex.management.runtime.messaging.services.http;

import flex.management.BaseControl;
import flex.messaging.services.http.SOAPProxyAdapter;

public class SOAPProxyAdapterControl
  extends HTTPProxyAdapterControl
  implements SOAPProxyAdapterControlMBean
{
  private static final String TYPE = "SOAPProxyAdapter";
  
  public SOAPProxyAdapterControl(SOAPProxyAdapter serviceAdapter, BaseControl parent)
  {
    super(serviceAdapter, parent);
  }
  
  public String getType()
  {
    return "SOAPProxyAdapter";
  }
}

/* Location:
 * Qualified Name:     flex.management.runtime.messaging.services.http.SOAPProxyAdapterControl
 * Java Class Version: 1.4 (48.0)
 * JD-Core Version:    0.7.1
 */
package flex.management.runtime.messaging.services.http;

public abstract interface SOAPProxyAdapterControlMBean
  extends HTTPProxyAdapterControlMBean
{}

/* Location:
 * Qualified Name:     flex.management.runtime.messaging.services.http.SOAPProxyAdapterControlMBean
 * Java Class Version: 1.4 (48.0)
 * JD-Core Version:    0.7.1
 */
package flex.messaging.services;

import flex.management.runtime.messaging.services.HTTPProxyServiceControl;
import flex.management.runtime.messaging.services.http.HTTPProxyDestinationControl;
import flex.messaging.Destination;
import flex.messaging.FlexContext;
import flex.messaging.FlexRemoteCredentials;
import flex.messaging.FlexSession;
import flex.messaging.MessageBroker;
import flex.messaging.MessageException;
import flex.messaging.log.Log;
import flex.messaging.log.Logger;
import flex.messaging.messages.HTTPMessage;
import flex.messaging.messages.Message;
import flex.messaging.messages.SOAPMessage;
import flex.messaging.services.http.HTTPProxyDestination;
import flex.messaging.services.http.proxy.ProxyException;
import flex.messaging.util.SettingsReplaceUtil;
import flex.messaging.util.StringUtils;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;

public class HTTPProxyService
  extends AbstractService
{
  public static final String LOG_CATEGORY = "Service.HTTP";
  private static final int DOT_DOT_NOT_ALLOWED = 10700;
  private static final int MULTIPLE_DOMAIN_PORT = 10701;
  private static final int DYNAMIC_NOT_CONFIGURED = 10702;
  private HTTPProxyServiceControl controller;
  
  public HTTPProxyService()
  {
    this(false);
  }
  
  public HTTPProxyService(boolean enableManagement)
  {
    super(enableManagement);
  }
  
  public Destination createDestination(String id)
  {
    HTTPProxyDestination destination = new HTTPProxyDestination();
    destination.setId(id);
    destination.setManaged(isManaged());
    destination.setService(this);
    
    return destination;
  }
  
  public void addDestination(Destination destination)
  {
    HTTPProxyDestination proxyDestination = (HTTPProxyDestination)destination;
    super.addDestination(proxyDestination);
  }
  
  public Object serviceMessage(Message msg)
  {
    if (!(msg instanceof HTTPMessage))
    {
      ServiceException e = new ServiceException();
      e.setMessage(10454, new Object[] { "HTTPProxy", "HTTPMessage" });
      throw e;
    }
    HTTPMessage message = (HTTPMessage)msg;
    
    String destination = message.getDestination();
    HTTPProxyDestination dest = (HTTPProxyDestination)destinations.get(destination);
    
    FlexRemoteCredentials remoteCredentials = FlexContext.getFlexSession().getRemoteCredentials(getId(), destination);
    if (remoteCredentials != null)
    {
      message.setRemoteUsername(remoteCredentials.getUsername());
      message.setRemotePassword((String)remoteCredentials.getCredentials());
    }
    else if ((dest.getRemoteUsername() != null) && (dest.getRemotePassword() != null))
    {
      message.setRemoteUsername(dest.getRemoteUsername());
      message.setRemotePassword(dest.getRemotePassword());
    }
    ServiceAdapter adapter = dest.getAdapter();
    Object result;
    Object result;
    if ((message instanceof SOAPMessage)) {
      result = invokeSoap(adapter, (SOAPMessage)message, dest);
    } else {
      result = invokeHttp(adapter, message, dest);
    }
    if (Log.isDebug())
    {
      String debugResult = StringUtils.prettifyString(String.valueOf(result));
      
      Log.getLogger(getLogCategory()).debug("HTTP request: " + message + StringUtils.NEWLINE + "  response: " + StringUtils.NEWLINE + debugResult + StringUtils.NEWLINE);
    }
    return result;
  }
  
  protected Object invokeSoap(ServiceAdapter adapter, SOAPMessage message, HTTPProxyDestination destination)
  {
    if (isManaged()) {
      ((HTTPProxyDestinationControl)destination.getControl()).incrementInvokeSOAPCount();
    }
    String dynamicUrl = message.getUrl();
    
    String contextPath = null;
    String serverName = null;
    String serverPort = null;
    String protocol = null;
    HttpServletRequest req = FlexContext.getHttpRequest();
    if (req != null)
    {
      contextPath = req.getContextPath();
      protocol = req.getScheme();
      serverName = req.getServerName();
      int port = req.getServerPort();
      if (port != 0) {
        serverPort = new Integer(req.getServerPort()).toString();
      }
    }
    if ((dynamicUrl != null) && (dynamicUrl.length() > 0)) {
      checkUrl(dynamicUrl, contextPath, destination, serverName, serverPort, protocol, message.getRemoteUsername() != null);
    } else {
      throw new MessageException("A SOAP endpoint was not provided.");
    }
    return adapter.invoke(message);
  }
  
  protected void checkUrl(String url, String contextPath, HTTPProxyDestination destination, String serverName, String serverPort, String serverProtocol, boolean authSupplied)
  {
    String originalUrl = url;
    
    String defaultUrl = destination.getParsedDefaultUrl(contextPath, serverName, serverPort, serverProtocol);
    List dynamicUrls = destination.getParsedDynamicUrls(contextPath);
    
    int i = url.indexOf("/..");
    while (i != -1)
    {
      if ((i == url.length() - 3) || (url.charAt(i + 3) == '/')) {
        throw new ProxyException(10700);
      }
      i = url.indexOf("/..", i + 1);
    }
    url = url.toLowerCase();
    
    url = SettingsReplaceUtil.updateIPv6(url);
    if ((defaultUrl != null) && (defaultUrl.toLowerCase().equals(url))) {
      return;
    }
    char[] urlChars = url.toCharArray();
    for (i = 0; i < dynamicUrls.size(); i++)
    {
      char[] pattern = (char[])dynamicUrls.get(i);
      boolean matches = StringUtils.findMatchWithWildcard(urlChars, pattern);
      if (matches)
      {
        if ((!authSupplied) || (destination.allowsDynamicAuthentication())) {
          return;
        }
        throw new ProxyException(10701);
      }
    }
    ProxyException exception = new ProxyException();
    exception.setMessage(10702, new Object[] { originalUrl, destination.getId() });
    
    throw exception;
  }
  
  protected String getLogCategory()
  {
    return "Service.HTTP";
  }
  
  protected Object invokeHttp(ServiceAdapter adapter, HTTPMessage message, HTTPProxyDestination destination)
  {
    if (isManaged()) {
      ((HTTPProxyDestinationControl)destination.getControl()).incrementInvokeHTTPCount();
    }
    String dynamicUrl = message.getUrl();
    
    String contextPath = null;
    String serverName = null;
    String serverPort = null;
    String protocol = null;
    HttpServletRequest req = FlexContext.getHttpRequest();
    if (req != null)
    {
      contextPath = req.getContextPath();
      protocol = req.getScheme();
      serverName = req.getServerName();
      int port = req.getServerPort();
      if (port != 0) {
        serverPort = Integer.toString(req.getServerPort());
      }
    }
    if ((dynamicUrl != null) && (!"".equals(dynamicUrl)))
    {
      checkUrl(dynamicUrl, contextPath, destination, serverName, serverPort, protocol, message.getRemoteUsername() != null);
    }
    else
    {
      String url = destination.getParsedDefaultUrl(contextPath, serverName, serverPort, protocol);
      message.setUrl(url);
    }
    return adapter.invoke(message);
  }
  
  protected void setupServiceControl(MessageBroker broker)
  {
    controller = new HTTPProxyServiceControl(this, broker.getControl());
    controller.register();
    setControl(controller);
  }
}

/* Location:
 * Qualified Name:     flex.messaging.services.HTTPProxyService
 * Java Class Version: 1.4 (48.0)
 * JD-Core Version:    0.7.1
 */
package flex.messaging.services.http;

public class ExternalProxySettings
{
  public static final int DEFAULT_PROXY_PORT = 80;
  public static final String PORT = "port";
  public static final String EXTERNAL_PROXY = "external-proxy";
  public static final String SERVER = "server";
  public static final String NT_DOMAIN = "nt-domain";
  public static final String USERNAME = "username";
  public static final String PASSWORD = "password";
  private static final String HTTP = "http://";
  private String proxyServer;
  private int proxyPort = 80;
  private String username;
  private String password;
  private String ntDomain;
  
  public String getProxyServer()
  {
    return proxyServer;
  }
  
  public void setProxyServer(String s)
  {
    if (s != null)
    {
      if (s.endsWith("/")) {
        s = s.substring(0, s.length() - 1);
      }
      boolean hasProtocol = s.indexOf("://") != -1;
      if ((!hasProtocol) && (isDotNet())) {
        s = "http://" + s;
      }
      if (!isDotNet()) {
        if ((hasProtocol) && (!isDotNet())) {
          if (s.startsWith("http://")) {
            s = s.substring("http://".length());
          } else {
            throw new IllegalArgumentException("A protocol cannot be specified for the proxy element: " + s);
          }
        }
      }
    }
    proxyServer = s;
  }
  
  public int getProxyPort()
  {
    return proxyPort;
  }
  
  public void setProxyPort(int p)
  {
    if (p > 0) {
      proxyPort = p;
    }
  }
  
  public String getUsername()
  {
    return username;
  }
  
  public void setUsername(String username)
  {
    this.username = username;
  }
  
  public String getPassword()
  {
    return password;
  }
  
  public void setPassword(String password)
  {
    this.password = password;
  }
  
  public String getNTDomain()
  {
    return ntDomain;
  }
  
  public void setNTDomain(String ntDomain)
  {
    this.ntDomain = ntDomain;
  }
  
  public static boolean isDotNet()
  {
    return System.getProperty("flex.platform.CLR") != null;
  }
}

/* Location:
 * Qualified Name:     flex.messaging.services.http.ExternalProxySettings
 * Java Class Version: 1.4 (48.0)
 * JD-Core Version:    0.7.1
 */
package flex.messaging.services.http;

import java.util.List;

public class HTTPConnectionManagerSettings
{
  public static final String CONNECTION_MANAGER = "connection-manager";
  public static final String CONNECTION_TIMEOUT = "connection-timeout";
  public static final String DEFAULT_MAX_CONNECTIONS_PER_HOST = "default-max-connections-per-host";
  public static final String LINGER = "linger";
  public static final String MAX_PER_HOST = "max-per-host";
  public static final String MAX_TOTAL_CONNECTIONS = "max-total-connections";
  public static final String RECEIVE_BUFFER_SIZE = "receive-buffer-size";
  public static final String SEND_BUFFER_SIZE = "send-buffer-size";
  public static final String SOCKET_TIMEOUT = "socket-timeout";
  public static final String STALE_CHECKING_ENABLED = "stale-checking-enabled";
  public static final String TCP_NO_DELAY = "tcp-no-delay";
  public static final int DEFAULT_MAX_CONNECTIONS_HOST = 2;
  public static final int DEFAULT_MAX_TOTAL_CONNECTIONS = 20;
  private int connectionTimeout;
  private int defaultMaxConnectionsPerHost;
  private int linger;
  private int maxTotalConnections;
  private List maxConnectionsPerHost;
  private int receiveBufferSize;
  private int sendBufferSize;
  private int socketTimeout;
  private boolean staleCheckingEnabled;
  private boolean tcpNoDelay;
  
  public HTTPConnectionManagerSettings()
  {
    defaultMaxConnectionsPerHost = 2;
    maxTotalConnections = 20;
    linger = -1;
    staleCheckingEnabled = true;
    tcpNoDelay = true;
  }
  
  public int getConnectionTimeout()
  {
    return connectionTimeout;
  }
  
  public void setConnectionTimeout(int value)
  {
    connectionTimeout = value;
  }
  
  public int getDefaultMaxConnectionsPerHost()
  {
    return defaultMaxConnectionsPerHost;
  }
  
  public void setDefaultMaxConnectionsPerHost(int value)
  {
    defaultMaxConnectionsPerHost = value;
  }
  
  public int getLinger()
  {
    return linger;
  }
  
  public void setLinger(int linger)
  {
    this.linger = linger;
  }
  
  public List getMaxConnectionsPerHost()
  {
    return maxConnectionsPerHost;
  }
  
  public void setMaxConnectionsPerHost(List value)
  {
    maxConnectionsPerHost = value;
  }
  
  public int getMaxTotalConnections()
  {
    return maxTotalConnections;
  }
  
  public void setMaxTotalConnections(int value)
  {
    maxTotalConnections = value;
  }
  
  public int getReceiveBufferSize()
  {
    return receiveBufferSize;
  }
  
  public void setReceiveBufferSize(int value)
  {
    receiveBufferSize = value;
  }
  
  public int getSendBufferSize()
  {
    return sendBufferSize;
  }
  
  public void setSendBufferSize(int sendBufferSize)
  {
    this.sendBufferSize = sendBufferSize;
  }
  
  public int getSocketTimeout()
  {
    return socketTimeout;
  }
  
  public void setSocketTimeout(int value)
  {
    socketTimeout = value;
  }
  
  public boolean isStaleCheckingEnabled()
  {
    return staleCheckingEnabled;
  }
  
  public void setStaleCheckingEnabled(boolean value)
  {
    staleCheckingEnabled = value;
  }
  
  public boolean isTcpNoDelay()
  {
    return tcpNoDelay;
  }
  
  public void setTcpNoDelay(boolean value)
  {
    tcpNoDelay = value;
  }
}

/* Location:
 * Qualified Name:     flex.messaging.services.http.HTTPConnectionManagerSettings
 * Java Class Version: 1.4 (48.0)
 * JD-Core Version:    0.7.1
 */
package flex.messaging.services.http;

import flex.management.runtime.messaging.services.http.HTTPProxyAdapterControl;
import flex.messaging.Destination;
import flex.messaging.FlexContext;
import flex.messaging.MessageException;
import flex.messaging.config.ConfigMap;
import flex.messaging.messages.AcknowledgeMessage;
import flex.messaging.messages.HTTPMessage;
import flex.messaging.messages.Message;
import flex.messaging.messages.SOAPMessage;
import flex.messaging.services.ServiceAdapter;
import flex.messaging.services.http.proxy.AccessFilter;
import flex.messaging.services.http.proxy.ErrorFilter;
import flex.messaging.services.http.proxy.ProxyContext;
import flex.messaging.services.http.proxy.ProxyContextFilter;
import flex.messaging.services.http.proxy.ProxyFilter;
import flex.messaging.services.http.proxy.RequestFilter;
import flex.messaging.services.http.proxy.ResponseFilter;
import flex.messaging.services.http.proxy.SecurityFilter;
import flex.messaging.services.http.proxy.Target;
import flex.messaging.util.ClassUtil;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.commons.httpclient.HostConfiguration;
import org.apache.commons.httpclient.HttpConnectionManager;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.NTCredentials;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.params.HostParams;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.apache.commons.httpclient.protocol.Protocol;

public class HTTPProxyAdapter
  extends ServiceAdapter
{
  public static final String CONTENT_TYPE_XML = "application/xml";
  public static final String CONTENT_TYPE_FORM = "application/x-www-form-urlencoded";
  public static final int DEFAULT_COOKIE_LIMIT = 200;
  private static final String COOKIE_LIMIT = "cookie-limit";
  private static final String ALLOW_LAX_SSL = "allow-lax-ssl";
  private static final String CONTENT_CHUNKED = "content-chunked";
  private static final String ID = "id";
  private static final String CLASS = "class";
  private static final String PROPERTIES = "properties";
  private static final String REQUEST_HEADERS = "requestHeaders";
  private static final String RESPONSE_HEADERS = "responseHeaders";
  protected boolean allowLaxSSL = false;
  protected boolean contentChunked = false;
  protected int cookieLimit = 200;
  protected ExternalProxySettings externalProxy;
  protected HTTPConnectionManagerSettings connectionManagerSettings;
  protected HttpConnectionManager connectionManager;
  protected HttpConnectionManagerParams connectionParams;
  protected ProxyFilter filterChain;
  protected UsernamePasswordCredentials proxyCredentials;
  private HTTPProxyAdapterControl controller;
  
  public HTTPProxyAdapter()
  {
    this(false);
  }
  
  public HTTPProxyAdapter(boolean enableManagement)
  {
    super(enableManagement);
    
    createFilterChain();
    externalProxy = new ExternalProxySettings();
    connectionManagerSettings = new HTTPConnectionManagerSettings();
  }
  
  public void initialize(String id, ConfigMap properties)
  {
    super.initialize(id, properties);
    if ((properties == null) || (properties.size() == 0)) {
      return;
    }
    ConfigMap conn = properties.getPropertyAsMap("connection-manager", null);
    if (conn != null)
    {
      int defaultMaxConnsPerHost = 2;
      if (conn.getProperty("max-total-connections") != null)
      {
        int maxTotal = conn.getPropertyAsInt("max-total-connections", 20);
        
        connectionManagerSettings.setMaxTotalConnections(maxTotal);
      }
      if (conn.getProperty("default-max-connections-per-host") != null)
      {
        defaultMaxConnsPerHost = conn.getPropertyAsInt("default-max-connections-per-host", 2);
        
        connectionManagerSettings.setDefaultMaxConnectionsPerHost(defaultMaxConnsPerHost);
      }
      if (conn.getProperty("connection-timeout") != null)
      {
        int timeout = conn.getPropertyAsInt("connection-timeout", 0);
        if (timeout >= 0) {
          connectionManagerSettings.setConnectionTimeout(timeout);
        }
      }
      if (conn.getProperty("socket-timeout") != null)
      {
        int timeout = conn.getPropertyAsInt("socket-timeout", 0);
        if (timeout >= 0) {
          connectionManagerSettings.setSocketTimeout(timeout);
        }
      }
      if (conn.getProperty("stale-checking-enabled") != null)
      {
        boolean staleCheck = conn.getPropertyAsBoolean("stale-checking-enabled", true);
        connectionManagerSettings.setStaleCheckingEnabled(staleCheck);
      }
      if (conn.getProperty("send-buffer-size") != null)
      {
        int bufferSize = conn.getPropertyAsInt("send-buffer-size", 0);
        if (bufferSize > 0) {
          connectionManagerSettings.setSendBufferSize(bufferSize);
        }
      }
      if (conn.getProperty("receive-buffer-size") != null)
      {
        int bufferSize = conn.getPropertyAsInt("receive-buffer-size", 0);
        if (bufferSize > 0) {
          connectionManagerSettings.setReceiveBufferSize(bufferSize);
        }
      }
      if (conn.getProperty("tcp-no-delay") != null)
      {
        boolean noNagel = conn.getPropertyAsBoolean("tcp-no-delay", true);
        connectionManagerSettings.setTcpNoDelay(noNagel);
      }
      if (conn.getProperty("linger") != null)
      {
        int linger = conn.getPropertyAsInt("linger", -1);
        connectionManagerSettings.setLinger(linger);
      }
      List hosts = conn.getPropertyAsList("max-per-host", null);
      if (hosts != null)
      {
        List hostSettings = new ArrayList();
        Iterator it = hosts.iterator();
        while (it.hasNext())
        {
          ConfigMap maxPerHost = (ConfigMap)it.next();
          HostConfigurationSettings hostConfig = new HostConfigurationSettings();
          if (maxPerHost.getProperty("max-connections") != null)
          {
            int maxConn = maxPerHost.getPropertyAsInt("max-connections", defaultMaxConnsPerHost);
            
            hostConfig.setMaximumConnections(maxConn);
          }
          if (maxPerHost.getProperty("host") != null)
          {
            String host = maxPerHost.getPropertyAsString("host", null);
            hostConfig.setHost(host);
            if (host != null)
            {
              int port = maxPerHost.getPropertyAsInt("port", 0);
              hostConfig.setPort(port);
              
              ConfigMap factoryMap = maxPerHost.getPropertyAsMap("protocol-factory", null);
              if (factoryMap != null)
              {
                String className = factoryMap.getPropertyAsString("class", null);
                if (className != null)
                {
                  Class factoryClass = ClassUtil.createClass(className);
                  ProtocolFactory protocolFactory = (ProtocolFactory)ClassUtil.createDefaultInstance(factoryClass, ProtocolFactory.class);
                  String factoryId = factoryMap.getPropertyAsString("id", host + "_protocol_factory");
                  ConfigMap protocolProperties = factoryMap.getPropertyAsMap("properties", null);
                  protocolFactory.initialize(factoryId, protocolProperties);
                }
              }
              else
              {
                String protocol = maxPerHost.getPropertyAsString("protocol", null);
                hostConfig.setProtocol(protocol);
              }
            }
          }
          ConfigMap proxy = maxPerHost.getPropertyAsMap("proxy", null);
          if (proxy != null)
          {
            String proxyHost = proxy.getPropertyAsString("host", null);
            hostConfig.setProxyHost(proxyHost);
            if (proxyHost != null)
            {
              int port = proxy.getPropertyAsInt("port", 0);
              hostConfig.setProxyPort(port);
            }
          }
          if (maxPerHost.getProperty("local-address") != null)
          {
            String localAddress = maxPerHost.getPropertyAsString("local-address", null);
            hostConfig.setLocalAddress(localAddress);
          }
          if (maxPerHost.getProperty("virtual-host") != null)
          {
            String virtualHost = maxPerHost.getPropertyAsString("virtual-host", null);
            hostConfig.setVirtualHost(virtualHost);
          }
          hostSettings.add(hostConfig);
        }
        if (hostSettings.size() > 0) {
          connectionManagerSettings.setMaxConnectionsPerHost(hostSettings);
        }
      }
      setConnectionManagerSettings(connectionManagerSettings);
    }
    if (properties.getProperty("cookie-limit") != null)
    {
      int cl = properties.getPropertyAsInt("cookie-limit", 200);
      setCookieLimit(cl);
    }
    if (properties.getProperty("allow-lax-ssl") != null)
    {
      boolean lax = properties.getPropertyAsBoolean("allow-lax-ssl", false);
      setAllowLaxSSL(lax);
    }
    if (properties.getProperty("content-chunked") != null)
    {
      boolean ch = properties.getPropertyAsBoolean("content-chunked", false);
      setContentChunked(ch);
    }
    ConfigMap extern = properties.getPropertyAsMap("external-proxy", null);
    if (extern != null)
    {
      ExternalProxySettings proxy = new ExternalProxySettings();
      
      String proxyServer = extern.getPropertyAsString("server", null);
      proxy.setProxyServer(proxyServer);
      int proxyPort = extern.getPropertyAsInt("port", 80);
      proxy.setProxyPort(proxyPort);
      String ntdomain = extern.getPropertyAsString("nt-domain", null);
      proxy.setNTDomain(ntdomain);
      String username = extern.getPropertyAsString("username", null);
      proxy.setUsername(username);
      String password = extern.getPropertyAsString("password", null);
      proxy.setPassword(password);
      
      setExternalProxySettings(proxy);
    }
  }
  
  public boolean isAllowLaxSSL()
  {
    return allowLaxSSL;
  }
  
  public void setAllowLaxSSL(boolean allowLaxSSL)
  {
    this.allowLaxSSL = allowLaxSSL;
  }
  
  public boolean isContentChunked()
  {
    return contentChunked;
  }
  
  public void setContentChunked(boolean contentChunked)
  {
    this.contentChunked = contentChunked;
  }
  
  public int getCookieLimit()
  {
    return cookieLimit;
  }
  
  public void setCookieLimit(int cookieLimit)
  {
    this.cookieLimit = cookieLimit;
  }
  
  public void setDestination(Destination destination)
  {
    Destination dest = (HTTPProxyDestination)destination;
    super.setDestination(dest);
  }
  
  public ExternalProxySettings getExternalProxySettings()
  {
    return externalProxy;
  }
  
  public void setExternalProxySettings(ExternalProxySettings externalProxy)
  {
    this.externalProxy = externalProxy;
    initExternalProxy(externalProxy);
  }
  
  public HTTPConnectionManagerSettings getConnectionManagerSettings()
  {
    return connectionManagerSettings;
  }
  
  public void setConnectionManagerSettings(HTTPConnectionManagerSettings connectionManagerSettings)
  {
    this.connectionManagerSettings = connectionManagerSettings;
    initHttpConnectionManagerParams(connectionManagerSettings);
    connectionManager = new MultiThreadedHttpConnectionManager();
    connectionManager.setParams(connectionParams);
  }
  
  public Object invoke(Message msg)
  {
    HTTPMessage message = (HTTPMessage)msg;
    
    ProxyContext context = new ProxyContext();
    if ((message instanceof SOAPMessage)) {
      context.setSoapRequest(true);
    } else {
      context.setSoapRequest(false);
    }
    setupContext(context, message);
    try
    {
      filterChain.invoke(context);
      
      Object response = context.getResponse();
      if (context.getRecordHeaders())
      {
        AcknowledgeMessage ack = new AcknowledgeMessage();
        ack.setBody(response);
        ack.setHeader("requestHeaders", context.getRequestHeaders());
        ack.setHeader("responseHeaders", context.getResponseHeaders());
        return ack;
      }
      return response;
    }
    catch (MessageException ex)
    {
      throw ex;
    }
    catch (Throwable t)
    {
      t.printStackTrace();
      throw new MessageException(t.toString());
    }
  }
  
  protected void setupContext(ProxyContext context, HTTPMessage message)
  {
    Target target = new Target();
    context.setTarget(target);
    
    context.setExternalProxySettings(externalProxy);
    context.setProxyCredentials(proxyCredentials);
    context.setConnectionManager(connectionManager);
    context.setAllowLaxSSL(allowLaxSSL);
    context.setContentChunked(contentChunked);
    context.setRecordHeaders(message.getRecordHeaders());
    context.setCookieLimit(cookieLimit);
    context.setHttpRequest(FlexContext.getHttpRequest() != null);
    
    String url = message.getUrl();
    context.setUrl(url);
    
    Map httpHeaders = message.getHttpHeaders();
    context.setHeaders(httpHeaders);
    
    String method = message.getMethod();
    context.setMethod(method);
    
    String contentType = message.getContentType();
    context.setContentType(contentType);
    
    Object body = message.getBody();
    context.setBody(body);
    
    target.setRemoteUsername(message.getRemoteUsername());
    target.setRemotePassword(message.getRemotePassword());
    
    HTTPProxyDestination destination = (HTTPProxyDestination)getDestination();
    target.setUseCustomAuthentication(destination.isUseCustomAuthentication());
    if (destination.getProtocolFactory() != null)
    {
      ProtocolFactory protocolFactory = destination.getProtocolFactory();
      context.setProtocol(protocolFactory.getProtocol());
    }
  }
  
  protected void setupAdapterControl(Destination destination)
  {
    controller = new HTTPProxyAdapterControl(this, destination.getControl());
    controller.register();
    setControl(controller);
  }
  
  private ProxyFilter createFilterChain()
  {
    if (filterChain == null)
    {
      ErrorFilter errorFilter = new ErrorFilter();
      
      AccessFilter accessFilter = new AccessFilter();
      
      ProxyContextFilter contextFilter = new ProxyContextFilter();
      
      ResponseFilter responseFilter = new ResponseFilter();
      
      SecurityFilter securityFilter = new SecurityFilter();
      
      RequestFilter requestFilter = new RequestFilter();
      
      errorFilter.setNext(accessFilter);
      accessFilter.setNext(contextFilter);
      contextFilter.setNext(responseFilter);
      responseFilter.setNext(securityFilter);
      securityFilter.setNext(requestFilter);
      
      filterChain = errorFilter;
    }
    return filterChain;
  }
  
  private void initExternalProxy(ExternalProxySettings ep)
  {
    if (externalProxy != null)
    {
      String proxyServer = externalProxy.getProxyServer();
      String proxyUsername = externalProxy.getUsername();
      if (proxyUsername != null)
      {
        String proxyPassword = externalProxy.getPassword();
        String proxyDomain = externalProxy.getNTDomain();
        if (proxyDomain != null) {
          proxyCredentials = new NTCredentials(proxyUsername, proxyPassword, proxyServer, proxyDomain);
        } else {
          proxyCredentials = new UsernamePasswordCredentials(proxyUsername, proxyPassword);
        }
      }
    }
  }
  
  private void initHttpConnectionManagerParams(HTTPConnectionManagerSettings settings)
  {
    connectionParams = new HttpConnectionManagerParams();
    connectionParams.setMaxTotalConnections(settings.getMaxTotalConnections());
    connectionParams.setDefaultMaxConnectionsPerHost(settings.getDefaultMaxConnectionsPerHost());
    if (settings.getConnectionTimeout() >= 0) {
      connectionParams.setConnectionTimeout(settings.getConnectionTimeout());
    }
    if (settings.getSocketTimeout() >= 0) {
      connectionParams.setSoTimeout(settings.getSocketTimeout());
    }
    connectionParams.setStaleCheckingEnabled(settings.isStaleCheckingEnabled());
    if (settings.getSendBufferSize() > 0) {
      connectionParams.setSendBufferSize(settings.getSendBufferSize());
    }
    if (settings.getReceiveBufferSize() > 0) {
      connectionParams.setReceiveBufferSize(settings.getReceiveBufferSize());
    }
    connectionParams.setTcpNoDelay(settings.isTcpNoDelay());
    connectionParams.setLinger(settings.getLinger());
    if (settings.getMaxConnectionsPerHost() != null)
    {
      Iterator it = settings.getMaxConnectionsPerHost().iterator();
      while (it.hasNext())
      {
        HostConfigurationSettings hcs = (HostConfigurationSettings)it.next();
        HostConfiguration hostConfig = new HostConfiguration();
        if (hcs.getProtocol() != null)
        {
          Protocol protocol = Protocol.getProtocol(hcs.getProtocol());
          hostConfig.setHost(hcs.getHost(), hcs.getPort(), protocol);
        }
        else if (hcs.getProtocolFactory() != null)
        {
          Protocol protocol = hcs.getProtocolFactory().getProtocol();
          if (hcs.getPort() > 0) {
            hostConfig.setHost(hcs.getHost(), hcs.getPort(), protocol);
          } else {
            hostConfig.setHost(hcs.getHost(), protocol.getDefaultPort(), protocol);
          }
        }
        else if (hcs.getPort() > 0)
        {
          hostConfig.setHost(hcs.getHost(), hcs.getPort());
        }
        else
        {
          hostConfig.setHost(hcs.getHost());
        }
        if (hcs.getVirtualHost() != null)
        {
          HostParams params = hostConfig.getParams();
          if (params != null) {
            params.setVirtualHost(hcs.getVirtualHost());
 
1 2 3

Further reading...

For more information on Java 1.5 Tiger, you may find Java 1.5 Tiger, A developer's Notebook by D. Flanagan and B. McLaughlin from O'Reilly of interest.

New!JAR listings


Copyright 2006-2017. Infinite Loop Ltd