flex-messaging-proxy-1.0

ttpMethod(headMethod);
    }
    else if ("PUT".equals(method))
    {
      PutMethod putMethod = new PutMethod(encodedPath);
      context.setHttpMethod(putMethod);
    }
    else if ("OPTIONS".equals(method))
    {
      OptionsMethod optionsMethod = new OptionsMethod(encodedPath);
      context.setHttpMethod(optionsMethod);
    }
    else if ("DELETE".equals(method))
    {
      DeleteMethod deleteMethod = new DeleteMethod(encodedPath);
      context.setHttpMethod(deleteMethod);
    }
    else if ("TRACE".equals(method))
    {
      TraceMethod traceMethod = new TraceMethod(encodedPath);
      context.setHttpMethod(traceMethod);
    }
    else
    {
      ProxyException pe = new ProxyException(10719);
      pe.setDetails(10719, "1", new Object[] { method });
      throw pe;
    }
    HttpMethodBase httpMethod = context.getHttpMethod();
    if ((httpMethod instanceof EntityEnclosingMethod)) {
      ((EntityEnclosingMethod)httpMethod).setContentChunked(context.getContentChunked());
    }
  }
  
  public static void copyCookiesToEndpoint(ProxyContext context)
  {
    HttpServletRequest clientRequest = FlexContext.getHttpRequest();
    HttpState initState;
    Iterator iterator;
    if (clientRequest != null)
    {
      javax.servlet.http.Cookie[] cookies = clientRequest.getCookies();
      initState = context.getHttpClient().getState();
      if (cookies != null)
      {
        TreeMap cookieMap = new TreeMap();
        for (int i = 0; i < cookies.length; i++)
        {
          javax.servlet.http.Cookie cookie = cookies[i];
          CookieInfo origCookie = new CookieInfo(cookie.getName(), cookie.getDomain(), cookie.getName(), cookie.getValue(), cookie.getPath(), cookie.getMaxAge(), null, cookie.getSecure());
          
          CookieInfo newCookie = RequestUtil.createCookie(origCookie, context, context.getTarget().getUrl().getHost(), context.getTarget().getUrl().getPath());
          if (newCookie != null)
          {
            Integer pathInt = new Integer(0 - path.length());
            ArrayList list = (ArrayList)cookieMap.get(pathInt);
            if (list == null)
            {
              list = new ArrayList();
              cookieMap.put(pathInt, list);
            }
            list.add(newCookie);
          }
        }
        for (iterator = cookieMap.values().iterator(); iterator.hasNext();)
        {
          ArrayList list = (ArrayList)iterator.next();
          for (iterator2 = list.iterator(); iterator2.hasNext();)
          {
            CookieInfo cookieInfo = (CookieInfo)iterator2.next();
            if (Log.isInfo())
            {
              String str = "-- Cookie in request: " + cookieInfo;
              Log.getLogger("Service.HTTP").debug(str);
            }
            org.apache.commons.httpclient.Cookie cookie = new org.apache.commons.httpclient.Cookie(domain, name, value, path, maxAge, secure);
            
            initState.addCookie(cookie);
          }
        }
      }
    }
    Iterator iterator2;
  }
  
  public static void copyHeadersToEndpoint(ProxyContext context)
  {
    HttpServletRequest clientRequest = FlexContext.getHttpRequest();
    if (clientRequest != null)
    {
      Enumeration headerNames = clientRequest.getHeaderNames();
      while (headerNames.hasMoreElements())
      {
        String headerName = (String)headerNames.nextElement();
        if (!RequestUtil.ignoreHeader(headerName, context))
        {
          Enumeration headers = clientRequest.getHeaders(headerName);
          while (headers.hasMoreElements())
          {
            String value = (String)headers.nextElement();
            context.getHttpMethod().addRequestHeader(headerName, value);
            if (Log.isInfo()) {
              Log.getLogger("Service.HTTP").debug("-- Header in request: " + headerName + " : " + value);
            }
          }
        }
      }
    }
  }
  
  protected void addCustomHeaders(ProxyContext context)
  {
    HttpMethodBase httpMethod = context.getHttpMethod();
    
    String contentType = context.getContentType();
    if (contentType != null) {
      httpMethod.setRequestHeader("Content-Type", contentType);
    }
    Map customHeaders = context.getHeaders();
    if (customHeaders != null)
    {
      Iterator it = customHeaders.keySet().iterator();
      while (it.hasNext())
      {
        String name = (String)it.next();
        Object value = customHeaders.get(name);
        if (value == null)
        {
          httpMethod.setRequestHeader(name, "");
        }
        else if ((value instanceof String))
        {
          httpMethod.setRequestHeader(name, (String)value);
        }
        else
        {
          Iterator iterator;
          if ((value instanceof List))
          {
            List valueList = (List)value;
            for (iterator = valueList.iterator(); iterator.hasNext();)
            {
              Object currentValue = iterator.next();
              if (currentValue == null) {
                httpMethod.addRequestHeader(name, "");
              } else {
                httpMethod.addRequestHeader(name, (String)currentValue);
              }
            }
          }
          else if (value.getClass().isArray())
          {
            Object[] valueArray = (Object[])value;
            for (int i = 0; i < valueArray.length; i++)
            {
              Object currentValue = valueArray[i];
              if (currentValue == null) {
                httpMethod.addRequestHeader(name, "");
              } else {
                httpMethod.addRequestHeader(name, (String)currentValue);
              }
            }
          }
        }
      }
    }
    if (context.isSoapRequest())
    {
      context.getHttpMethod().setRequestHeader("Content-Type", "text/xml; charset=utf-8");
      
      String soapAction = null;
      
      Header header = context.getHttpMethod().getRequestHeader("SOAPAction");
      if (header != null) {
        soapAction = header.getValue();
      }
      if (soapAction == null)
      {
        HttpServletRequest clientRequest = FlexContext.getHttpRequest();
        if (clientRequest != null) {
          soapAction = clientRequest.getHeader("SOAPAction");
        }
        if ((soapAction != null) && (!soapAction.startsWith("\"")) && (!soapAction.endsWith("\""))) {
          soapAction = "\"" + soapAction + "\"";
        }
        context.getHttpMethod().setRequestHeader("SOAPAction", soapAction);
      }
    }
  }
  
  protected void recordRequestHeaders(ProxyContext context)
  {
    if (context.getRecordHeaders())
    {
      Header[] headers = context.getHttpMethod().getRequestHeaders();
      if (headers != null)
      {
        HashMap recordedHeaders = new HashMap();
        for (int i = 0; i < headers.length; i++)
        {
          Header header = headers[i];
          String headerName = header.getName();
          String headerValue = header.getValue();
          Object existingHeaderValue = recordedHeaders.get(headerName);
          if (existingHeaderValue != null)
          {
            if ((existingHeaderValue instanceof String))
            {
              ArrayList headerValues = new ArrayList();
              headerValues.add(existingHeaderValue);
              headerValues.add(headerValue);
              recordedHeaders.put(headerName, headerValues);
            }
            else if ((existingHeaderValue instanceof ArrayList))
            {
              ArrayList headerValues = (ArrayList)existingHeaderValue;
              headerValues.add(headerValue);
            }
          }
          else {
            recordedHeaders.put(headerName, headerValue);
          }
        }
        context.setRequestHeaders(recordedHeaders);
      }
    }
  }
  
  protected void sendRequest(ProxyContext context)
  {
    Target target = context.getTarget();
    String method = context.getMethod();
    HttpMethod httpMethod = context.getHttpMethod();
    if ((httpMethod instanceof EntityEnclosingMethod))
    {
      Object data = processBody(context);
      Class dataClass = data.getClass();
      if ((data instanceof String))
      {
        String requestString = (String)data;
        if (Log.isInfo())
        {
          Logger logger = Log.getLogger("Service.HTTP");
          logger.debug("-- Begin " + method + " request --");
          logger.debug(StringUtils.prettifyString(requestString));
          logger.debug("-- End " + method + " request --");
        }
        try
        {
          StringRequestEntity requestEntity = new StringRequestEntity(requestString, null, "UTF-8");
          ((EntityEnclosingMethod)httpMethod).setRequestEntity(requestEntity);
        }
        catch (UnsupportedEncodingException ex)
        {
          ProxyException pe = new ProxyException(10706);
          pe.setDetails(10706, "1", new Object[] { ex });
          throw pe;
        }
      }
      else if ((dataClass.isArray()) && (Byte.TYPE.equals(dataClass.getComponentType())))
      {
        byte[] dataBytes = (byte[])data;
        ByteArrayRequestEntity requestEntity = new ByteArrayRequestEntity(dataBytes, context.getContentType());
        ((EntityEnclosingMethod)httpMethod).setRequestEntity(requestEntity);
      }
      else if ((data instanceof InputStream))
      {
        InputStreamRequestEntity requestEntity = new InputStreamRequestEntity((InputStream)data, context.getContentType());
        ((EntityEnclosingMethod)httpMethod).setRequestEntity(requestEntity);
      }
    }
    else if ((httpMethod instanceof GetMethod))
    {
      Object req = processBody(context);
      if ((req instanceof String))
      {
        String requestString = (String)req;
        if (Log.isInfo())
        {
          Logger logger = Log.getLogger("Service.HTTP");
          logger.debug("-- Begin " + method + " request --");
          logger.debug(StringUtils.prettifyString(requestString));
          logger.debug("-- End " + method + " request --");
        }
        if (!"".equals(requestString))
        {
          String query = context.getHttpMethod().getQueryString();
          if (query != null) {
            query = query + "&" + requestString;
          } else {
            query = requestString;
          }
          context.getHttpMethod().setQueryString(query);
        }
      }
    }
    context.getHttpClient().setHostConfiguration(target.getHostConfig());
    try
    {
      context.getHttpClient().executeMethod(context.getHttpMethod());
    }
    catch (UnknownHostException uhex)
    {
      ProxyException pe = new ProxyException();
      pe.setMessage(10707, new Object[] { uhex.getMessage() });
      pe.setCode("Server.Proxy.Request.Failed");
      throw pe;
    }
    catch (Exception ex)
    {
      ProxyException pe = new ProxyException(10706);
      pe.setDetails(10706, "1", new Object[] { ex.getMessage() });
      pe.setCode("Server.Proxy.Request.Failed");
      throw pe;
    }
  }
  
  protected Object processBody(ProxyContext context)
  {
    Object body = context.getBody();
    if (body == null) {
      return "";
    }
    if ((body instanceof String)) {
      return (String)body;
    }
    if ((body instanceof Map))
    {
      Map params = (Map)body;
      
      StringBuffer postData = new StringBuffer();
      
      boolean formValues = false;
      Iterator iter = params.keySet().iterator();
      while (iter.hasNext())
      {
        String name = (String)iter.next();
        if (!formValues) {
          formValues = true;
        } else {
          postData.append("&");
        }
        Object vals = params.get(name);
        if (vals == null) {
          encodeParam(postData, name, "");
        }
        if ((vals instanceof String))
        {
          String val = (String)vals;
          encodeParam(postData, name, val);
        }
        else if ((vals instanceof List))
        {
          List valLists = (List)vals;
          for (int i = 0; i < valLists.size(); i++)
          {
            Object o = valLists.get(i);
            String val = "";
            if (o != null) {
              val = o.toString();
            }
            if (i > 0) {
              postData.append("&");
            }
            encodeParam(postData, name, val);
          }
        }
        else if (vals.getClass().isArray())
        {
          for (int i = 0; i < Array.getLength(vals); i++)
          {
            Object o = Array.get(vals, i);
            String val = "";
            if (o != null) {
              val = o.toString();
            }
            if (i > 0) {
              postData.append("&");
            }
            encodeParam(postData, name, val);
          }
        }
      }
      return postData.toString();
    }
    if (body.getClass().isArray()) {
      return body;
    }
    if ((body instanceof InputStream)) {
      return body;
    }
    return body.toString();
  }
  
  protected void encodeParam(StringBuffer buf, String name, String val)
  {
    name = URLEncoder.encode(name);
    val = URLEncoder.encode(val);
    
    buf.append(name);
    buf.append("=");
    buf.append(val);
  }
}

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

import flex.messaging.log.Log;
import flex.messaging.log.Logger;

public class RequestUtil
{
  public static CookieInfo createCookie(CookieInfo cookie, SharedProxyContext context, String targetHost, String targetPath)
  {
    String path = cookie.path;
    String name = cookie.name;
    if (path == null) {
      path = "/";
    }
    String domain = null;String actualName = null;
    if ((name.startsWith("FLEX")) && (name.indexOf("_") != -1))
    {
      int startIndex = name.indexOf("_") + 1;
      int endIndex = name.indexOf("_", startIndex);
      if (endIndex == -1) {
        return null;
      }
      int domainHash;
      int pathHash;
      try
      {
        domainHash = Integer.parseInt(name.substring(startIndex, endIndex));
        startIndex = endIndex + 1;
        endIndex = name.indexOf("_", startIndex);
        if (endIndex == -1) {
          return null;
        }
        pathHash = Integer.parseInt(name.substring(startIndex, endIndex));
      }
      catch (NumberFormatException e)
      {
        Log.getLogger("Service.HTTP").error("Could not parse cookie hash value in: " + name + " (may be beta cookie)");
        return null;
      }
      startIndex = endIndex + 1;
      if (name.length() <= startIndex) {
        return null;
      }
      actualName = name.substring(startIndex);
      
      domain = targetHost;
      while ((domain != null) && (domainHash != domain.hashCode()))
      {
        int dotIndex = domain.indexOf(".", 1);
        if (dotIndex != -1) {
          domain = domain.substring(dotIndex);
        } else {
          domain = null;
        }
      }
      if (domain == null) {
        return null;
      }
      path = targetPath;
      while ((path != null) && (path.length() != 0) && (pathHash != path.hashCode())) {
        path = path.substring(0, path.length() - 1);
      }
      if ((path == null) || (path.length() == 0)) {
        return null;
      }
    }
    else if (context.isLocalDomain())
    {
      domain = cookie.domain;
      if (domain == null) {
        domain = targetHost;
      }
      actualName = cookie.name;
    }
    else
    {
      return null;
    }
    CookieInfo cookieInfo = new CookieInfo(name, domain, actualName, value, path, maxAge, maxAgeObj, secure);
    
    return cookieInfo;
  }
  
  public static boolean ignoreHeader(String headerName, SharedProxyContext context)
  {
    boolean ignoreHeader = false;
    if (("Host".equalsIgnoreCase(headerName)) || ("Accept-Encoding".equalsIgnoreCase(headerName)) || ("Content-Length".equalsIgnoreCase(headerName)) || ("Set-Cookie".equalsIgnoreCase(headerName)) || ("Set-Cookie2".equalsIgnoreCase(headerName)) || ("Cookie".equalsIgnoreCase(headerName)) || ("Connection".equalsIgnoreCase(headerName)) || (ProxyConstants.HEADER_CREDENTIALS.equalsIgnoreCase(headerName)) || (("Authorization".equalsIgnoreCase(headerName)) && ((context.hasAuthorization()) || (!context.isLocalDomain())))) {
      ignoreHeader = true;
    }
    return ignoreHeader;
  }
}

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

import flex.messaging.FlexContext;
import flex.messaging.log.Log;
import flex.messaging.log.Logger;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethodBase;
import org.apache.commons.httpclient.HttpState;
import org.apache.commons.httpclient.StatusLine;
import org.apache.commons.httpclient.methods.OptionsMethod;

public class ResponseFilter
  extends ProxyFilter
{
  public static int RESPONSE_CHUNK = 4096;
  private static final int STATUS_ERROR = 10708;
  private static final int NULL_RESPONSE_STREAM = 10709;
  private static final int CANNOT_STREAM_NOT_HTTP = 10710;
  private static final int ERROR_WRITING_RESPONSE = 10711;
  
  public void invoke(ProxyContext context)
  {
    if (next != null) {
      next.invoke(context);
    }
    checkStatusCode(context);
    copyCookiesFromEndpoint(context);
    copyHeadersFromEndpoint(context);
    recordResponseHeaders(context);
    setupResponse(context);
  }
  
  protected void checkStatusCode(ProxyContext context)
  {
    int statusCode = context.getStatusCode();
    if (statusCode >= 400) {
      if (((statusCode != 401 ? 1 : 0) & (statusCode != 403 ? 1 : 0)) != 0) {
        if (!context.isSoapRequest())
        {
          StatusLine statusLine = context.getHttpMethod().getStatusLine();
          String reason = null;
          if (statusLine != null) {
            reason = statusLine.toString();
          }
          if ((reason == null) || ("".equals(reason))) {
            reason = "" + statusCode;
          }
          ProxyException pe = new ProxyException();
          pe.setMessage(10708, new Object[] { reason });
          pe.setCode("Server.Proxy.Request.Failed");
          pe.setDetails(10708, "1", new Object[] { reason });
          throw pe;
        }
      }
    }
  }
  
  protected void copyCookiesFromEndpoint(ProxyContext context)
  {
    HttpServletResponse clientResponse = FlexContext.getHttpResponse();
    if (clientResponse != null)
    {
      org.apache.commons.httpclient.Cookie[] cookies = context.getHttpClient().getState().getCookies();
      for (int i = 0; i < cookies.length; i++)
      {
        String domain = cookies[i].getDomain();
        String path = cookies[i].getPath();
        String name = cookies[i].getName();
        String value = cookies[i].getValue();
        
        String clientName = ResponseUtil.getCookieName(context, path, name, domain);
        if (Log.isInfo())
        {
          String str = "-- Cookie in response: domain = '" + domain + "', path = '" + path + "', client name = '" + clientName + "', endpoint name = '" + name + "', value = '" + value;
          
          Log.getLogger("Service.HTTP").debug(str);
        }
        javax.servlet.http.Cookie cookie = new javax.servlet.http.Cookie(clientName, value);
        
        Date expiry = cookies[i].getExpiryDate();
        if (expiry != null)
        {
          int maxAge = (int)((expiry.getTime() - System.currentTimeMillis()) / 1000L);
          cookie.setMaxAge(maxAge);
        }
        cookie.setSecure(cookies[i].getSecure());
        cookie.setPath("/");
        
        clientResponse.addCookie(cookie);
      }
    }
  }
  
  protected void copyHeadersFromEndpoint(ProxyContext context)
  {
    HttpServletResponse clientResponse = FlexContext.getHttpResponse();
    if (clientResponse != null)
    {
      Header[] headers = context.getHttpMethod().getResponseHeaders();
      for (int i = 0; i < headers.length; i++)
      {
        Header header = headers[i];
        String name = header.getName();
        String value = header.getValue();
        if (!ResponseUtil.ignoreHeader(name, context)) {
          if ((name != null) && (value != null))
          {
            clientResponse.addHeader(name, value);
            if (Log.isInfo()) {
              Log.getLogger("Service.HTTP").debug("-- Header in response: " + name + " : " + value);
            }
          }
        }
      }
      clientResponse.setHeader("Pragma", "public");
    }
  }
  
  protected void recordResponseHeaders(ProxyContext context)
  {
    String method = context.getMethod();
    if ((context.getRecordHeaders()) || ("HEAD".equals(method)))
    {
      Header[] headers = context.getHttpMethod().getResponseHeaders();
      HashMap responseHeaders = new HashMap();
      for (int i = 0; i < headers.length; i++)
      {
        Header header = headers[i];
        String headerName = header.getName();
        String headerValue = header.getValue();
        Object existingHeaderValue = responseHeaders.get(headerName);
        if (existingHeaderValue != null)
        {
          if ((existingHeaderValue instanceof String))
          {
            ArrayList headerValues = new ArrayList();
            headerValues.add(existingHeaderValue);
            headerValues.add(headerValue);
            responseHeaders.put(headerName, headerValues);
          }
          else if ((existingHeaderValue instanceof ArrayList))
          {
            ArrayList headerValues = (ArrayList)existingHeaderValue;
            headerValues.add(headerValue);
          }
        }
        else {
          responseHeaders.put(headerName, headerValue);
        }
      }
      context.setResponseHeaders(responseHeaders);
    }
  }
  
  protected void setupResponse(ProxyContext context)
  {
    String method = context.getMethod();
    HttpMethodBase httpMethod = context.getHttpMethod();
    if ("POST".equals(method))
    {
      writeResponse(context);
    }
    else if ("GET".equals(method))
    {
      writeResponse(context);
    }
    else if ("OPTIONS".equals(method))
    {
      OptionsMethod optionsMethod = (OptionsMethod)httpMethod;
      Enumeration options = optionsMethod.getAllowedMethods();
      if (options != null)
      {
        List ops = new ArrayList();
        while (options.hasMoreElements())
        {
          Object option = options.nextElement();
          ops.add(option);
        }
        Object[] o = ops.toArray();
        context.setResponse(o);
      }
    }
    else if ("TRACE".equals(method))
    {
      writeResponse(context);
    }
    else if (!"DELETE".equals(method))
    {
      if ("HEAD".equals(method)) {
        context.setResponse(context.getResponseHeaders());
      } else if (!"PUT".equals(method)) {}
    }
  }
  
  protected void writeResponse(ProxyContext context)
  {
    try
    {
      InputStream in = context.getHttpMethod().getResponseBodyAsStream();
      if (in == null) {
        throw new ProxyException(10709);
      }
      int length = (int)context.getHttpMethod().getResponseContentLength();
      if (context.streamResponseToClient())
      {
        HttpServletResponse clientResponse = FlexContext.getHttpResponse();
        if (clientResponse != null)
        {
          OutputStream out = clientResponse.getOutputStream();
          if (length != -1) {
            clientResponse.setContentLength(length);
          }
          writeStreamedResponse(in, out, context);
        }
        else
        {
          throw new ProxyException(10710);
        }
      }
      else
      {
        writeResponseAsString(in, length, context);
      }
    }
    catch (IOException ioe)
    {
      ProxyException pe = new ProxyException();
      pe.setMessage(10711, new Object[] { ioe.getMessage() });
      throw pe;
    }
  }
  
  protected void writeStreamedResponse(InputStream inStream, OutputStream out, ProxyContext context)
    throws IOException
  {
    byte[] tmp = new byte[RESPONSE_CHUNK];
    int i = 0;
    while ((i = inStream.read(tmp)) >= 0) {
      out.write(tmp, 0, i);
    }
  }
  
  protected void writeResponseAsString(InputStream inStream, int length, ProxyContext context)
    throws IOException
  {
    char[] tmp = new char[RESPONSE_CHUNK];
    
    StringBuffer sb = new StringBuffer(length < 0 ? 16 : length);
    BufferedInputStream bufferedIn = new BufferedInputStream(inStream);
    String charset = context.getHttpMethod().getResponseCharSet();
    
    bufferedIn.mark(4);
    
    boolean hasBOM = false;
    int read = bufferedIn.read();
    if (read > 0)
    {
      if (239 == (read & 0xFF))
      {
        read = bufferedIn.read();
        if (187 == (read & 0xFF))
        {
          read = bufferedIn.read();
          if (191 == (read & 0xFF))
          {
            hasBOM = true;
            charset = "UTF-8";
          }
        }
      }
      else if (255 == (read & 0xFF))
      {
        read = bufferedIn.read();
        if (254 == (read & 0xFF))
        {
          hasBOM = true;
          charset = "UTF16-LE";
          
          bufferedIn.mark(2);
          read = bufferedIn.read();
          if (0 == (read & 0xFF))
          {
            read = bufferedIn.read();
            if (0 == (read & 0xFF)) {
              charset = "UTF32-LE";
            } else {
              bufferedIn.reset();
            }
          }
          else
          {
            bufferedIn.reset();
          }
        }
      }
      else if (254 == (read & 0xFF))
      {
        read = bufferedIn.read();
        if (255 == (read & 0xFF))
        {
          hasBOM = true;
          charset = "UTF16-BE";
        }
      }
      else if (0 == (read & 0xFF))
      {
        read = bufferedIn.read();
        if (0 == (read & 0xFF))
        {
          read = bufferedIn.read();
          if (254 == (read & 0xFF))
          {
            read = bufferedIn.read();
            if (255 == (read & 0xFF))
            {
              hasBOM = true;
              charset = "UTF32-BE";
            }
          }
        }
      }
      if (!hasBOM) {
        bufferedIn.reset();
      }
    }
    BufferedReader reader = new BufferedReader(new InputStreamReader(bufferedIn, charset));
    int charactersRead = -1;
    while ((charactersRead = reader.read(tmp, 0, tmp.length)) >= 0) {
      sb.append(new String(tmp, 0, charactersRead));
    }
    context.setResponse(sb.toString());
  }
}

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

public class ResponseUtil
{
  public static String getCookieName(ProxyContext context, String path, String name, String domain)
  {
    String clientName;
    String clientName;
    if ((context.isLocalDomain()) && ((path == null) || (path.equals("/"))))
    {
      clientName = name;
    }
    else
    {
      StringBuffer nameBuf = new StringBuffer(40);
      nameBuf.append("FLEX");
      nameBuf.append("_");
      nameBuf.append(domain.hashCode());
      nameBuf.append("_");
      nameBuf.append(path.hashCode());
      nameBuf.append("_");
      nameBuf.append(name);
      clientName = nameBuf.toString();
    }
    return clientName;
  }
  
  public static boolean ignoreHeader(String name, ProxyContext context)
  {
    boolean ignoreHeader = false;
    if (("Content-Length".equalsIgnoreCase(name)) || ("Set-Cookie".equalsIgnoreCase(name)) || ("Set-Cookie2".equalsIgnoreCase(name)) || ("Cookie".equalsIgnoreCase(name)) || ("Transfer-Encoding".equalsIgnoreCase(name)) || ("Connection".equalsIgnoreCase(name)) || ((context.disableCaching()) && (("Cache-Control".equalsIgnoreCase(name)) || ("Expires".equalsIgnoreCase(name)) || ("Pragma".equalsIgnoreCase(name))))) {
      ignoreHeader = true;
    }
    return ignoreHeader;
  }
}

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

import flex.messaging.FlexContext;
import flex.messaging.log.Log;
import flex.messaging.log.Logger;
import flex.messaging.util.Base64.Decoder;
import java.net.URL;
import java.util.Enumeration;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethodBase;
import org.apache.commons.httpclient.HttpState;
import org.apache.commons.httpclient.StatusLine;
import org.apache.commons.httpclient.UsernamePasswordCredentials;

public class SecurityFilter
  extends ProxyFilter
{
  private static final int EMPTY_ERROR = 10708;
  private static final int ONLY_HTTP_HTTPS = 10712;
  private static final int NO_HTTPS_VIA_HTTP = 10713;
  private static final int NO_BASIC_NOT_HTTP = 10714;
  private static final int NO_BASIC_FOR_SOAP = 10715;
  private static final int DOMAIN_ERROR = 10716;
  private static final int LOGIN_REQUIRED = 10717;
  private static final int UNAUTHORIZED_ERROR = 10718;
  
  public void invoke(ProxyContext context)
  {
    checkURL(context);
    setCredentials(context);
    if (next != null) {
      next.invoke(context);
    }
    sendSecurityInfo(context);
  }
  
  private void checkURL(ProxyContext context)
  {
    Target target = context.getTarget();
    if ((!context.getTarget().getUrl().getProtocol().equalsIgnoreCase("http")) && (!target.isHTTPS()))
    {
      Log.getLogger("Service.HTTP").warn("PROXY SECURITY : Invalid URL - only HTTP or HTTPS URLs allowed");
      throw new ProxyException(10712);
    }
    if ((target.isHTTPS()) && (!context.isClientHttps()))
    {
      Log.getLogger("Service.HTTP").warn("PROXY SECURITY : Invalid URL - can't access HTTPS URLs when accessing proxy via HTTP.");
      
      throw new ProxyException(10713);
    }
  }
  
  private void setCredentials(ProxyContext context)
  {
    String user = null;String password = null;
    
    user = context.getTarget().getRemoteUsername();
    password = context.getTarget().getRemotePassword();
    
    String fromRequest = null;
    HttpServletRequest clientRequest = FlexContext.getHttpRequest();
    if (clientRequest != null) {
      fromRequest = clientRequest.getHeader(ProxyConstants.HEADER_CREDENTIALS);
    }
    if (fromRequest == null) {
      fromRequest = context.getCredentialsHeader();
    }
    if (fromRequest != null)
    {
      Base64.Decoder decoder = new Base64.Decoder();
      decoder.decode(fromRequest);
      String decoded = new String(decoder.drain());
      int colonIdx = decoded.indexOf(":");
      if (colonIdx != -1) {
        user = decoded.substring(0, colonIdx);
      }
      password = decoded.substring(colonIdx + 1);
    }
    if (clientRequest != null)
    {
      Enumeration headers = clientRequest.getHeaders("Authorization");
      if (headers != null) {
        while (headers.hasMoreElements())
        {
          String value = (String)headers.nextElement();
          if (value.startsWith("Basic")) {
            if (!context.isLocalDomainAndPort())
            {
              if (Log.isInfo()) {
                Log.getLogger("Service.HTTP").debug("Not sending on Authentication header. Proxy domain:port of " + clientRequest.getServerName() + ":" + clientRequest.getServerPort() + " does not match target domain:port of " + context.getTarget().getUrl().getHost() + ":" + context.getTarget().getUrl().getPort());
              }
            }
            else
            {
              Base64.Decoder decoder = new Base64.Decoder();
              String encoded = value.substring(6);
              decoder.decode(encoded);
              String decoded = new String(decoder.drain());
              int colonIdx = decoded.indexOf(":");
              user = decoded.substring(0, colonIdx);
              password = decoded.substring(colonIdx + 1);
            }
          }
        }
      }
    }
    if (user != null)
    {
      UsernamePasswordCredentials cred = new UsernamePasswordCredentials(user, password);
      
      context.getHttpClient().getState().setCredentials(ProxyUtil.getDefaultAuthScope(), cred);
      context.setAuthorization(true);
      if (Log.isInfo()) {
        Log.getLogger("Service.HTTP").info("-- Authentication header being sent for " + user);
      }
    }
  }
  
  private void sendSecurityInfo(ProxyContext context)
  {
    Target target = context.getTarget();
    String targetHost = target.getUrl().getHost();
    
    int statusCode = 200;
    
    boolean customAuth = target.useCustomAuthentication();
    
    StatusLine statusLine = context.getHttpMethod().getStatusLine();
    if (statusLine != null) {
      statusCode = statusLine.getStatusCode();
    }
    context.setStatusCode(statusCode);
    if ((statusCode == 401) || (statusCode == 403)) {
      if (!customAuth)
      {
        if (!context.isHttpRequest()) {
          throw new ProxyException(10714);
        }
        if (context.isSoapRequest()) {
          throw new ProxyException(10715);
        }
        if (!context.isLocalDomainAndPort())
        {
          HttpServletRequest clientRequest = FlexContext.getHttpRequest();
          
          String errorMessage = "The Flex proxy and the specified endpoint do not have the same domain, and so basic authentication cannot be used.  Please specify use-custom-authentication or run-as for services not located on the same domain as the Flex proxy. . The proxy domain:port is " + clientRequest.getServerName() + ":" + clientRequest.getServerPort() + " and the target domain:port is " + targetHost + ":" + target.getUrl().getPort();
          
          Log.getLogger("Service.HTTP").error(errorMessage);
          
          throw new ProxyException(10716);
        }
        HttpServletResponse clientResponse = FlexContext.getHttpResponse();
        clientResponse.setStatus(statusCode);
      }
      else
      {
        String message = null;
        if (statusLine != null) {
          message = statusLine.toString();
        }
        if (statusCode == 401)
        {
          ProxyException se = new ProxyException();
          se.setCode("Client.Authentication");
          if (message == null) {
            se.setMessage(10717);
          } else {
            se.setMessage(10708, new Object[] { message });
          }
          Header header = context.getHttpMethod().getResponseHeader(ProxyConstants.HEADER_AUTHENTICATE);
          if (header != null) {
            se.setDetails(header.getValue());
          }
          throw se;
        }
        ProxyException se = new ProxyException();
        se.setCode("Client.Authentication");
        if (message == null) {
          se.setMessage(10718);
        } else {
          se.setMessage(10708, new Object[] { message });
        }
        throw se;
      }
    }
  }
}

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

public class SharedProxyContext
{
  private String method;
  private boolean isSoapRequest;
  private boolean isHttpRequest;
  private boolean isClientHttps;
  private boolean hasAuthorization;
  private boolean localDomain;
  private boolean localPort;
  private boolean disableCaching;
  private boolean clientTarget;
  
  public String getMethod()
  {
    return method;
  }
  
  public void setMethod(String method)
  {
    this.method = method;
  }
  
  public boolean isSoapRequest()
  {
    return isSoapRequest;
  }
  
  public void setSoapRequest(boolean s)
  {
    isSoapRequest = s;
  }
  
  public boolean isHttpRequest()
  {
    return isHttpRequest;
  }
  
  public void setHttpRequest(boolean h)
  {
    isHttpRequest = h;
  }
  
  public boolean isClientHttps()
  {
    return isClientHttps;
  }
  
  public void setClientHttps(boolean h)
  {
    isClientHttps = h;
  }
  
  public boolean hasAuthorization()
  {
    return hasAuthorization;
  }
  
  public void setAuthorization(boolean hasAuthorization)
  {
    this.hasAuthorization = hasAuthorization;
  }
  
  public boolean isLocalDomain()
  {
    return localDomain;
  }
  
  public void setLocalDomain(boolean localDomain)
  {
    this.localDomain = localDomain;
  }
  
  public boolean isLocalPort()
  {
    return localPort;
  }
  
  public void setLocalPort(boolean localPort)
  {
    this.localPort = localPort;
  }
  
  public boolean isLocalDomainAndPort()
  {
    return (localDomain) && (localPort);
  }
  
  public boolean disableCaching()
  {
    return disableCaching;
  }
  
  public void setDisableCaching(boolean disableCaching)
  {
    this.disableCaching = disableCaching;
  }
  
  public boolean isClientTarget()
  {
    return clientTarget;
  }
  
  public void setClientTarget(boolean clientTarget)
  {
    this.clientTarget = clientTarget;
  }
}

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

import java.net.URL;
import org.apache.commons.httpclient.HostConfiguration;

public class Target
{
  private URL url;
  private boolean useCustomAuthentication = true;
  private boolean isHTTPS;
  private String encodedPath;
  private String remoteUsername;
  private String remotePassword;
  private HostConfiguration hostConfig;
  
  public URL getUrl()
  {
    return url;
  }
  
  public void setUrl(URL url)
  {
    this.url = url;
  }
  
  public boolean isHTTPS()
  {
    return isHTTPS;
  }
  
  public void setHTTPS(boolean HTTPS)
  {
    isHTTPS = HTTPS;
  }
  
  public String getEncodedPath()
  {
    return encodedPath;
  }
  
  public void setEncodedPath(String encodedPath)
  {
    this.encodedPath = encodedPath;
  }
  
  public HostConfiguration getHostConfig()
  {
    return hostConfig;
  }
  
  public void setHostConfig(HostConfiguration hostConfig)
  {
    this.hostConfig = hostConfig;
  }
  
  public String getRemoteUsername()
  {
    return remoteUsername;
  }
  
  public void setRemoteUsername(String name)
  {
    remoteUsername = name;
  }
  
  public String getRemotePassword()
  {
    return remotePassword;
  }
  
  public void setRemotePassword(String pass)
  {
    remotePassword = pass;
  }
  
  public boolean useCustomAuthentication()
  {
    return useCustomAuthentication;
  }
  
  public void setUseCustomAuthentication(boolean b)
  {
    useCustomAuthentication = b;
  }
}

/* Location:
 * Qualified Name:     flex.messaging.services.http.proxy.Target
 * Java Class Version: 1.4 (48.0)
 * JD-Core Version:    0.7.1
 */
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