[jboss-cvs] JBossAS SVN: r76843 - trunk/tomcat/src/main/org/jboss/web/tomcat/service/modcluster/mcmp/impl.

jboss-cvs-commits at lists.jboss.org jboss-cvs-commits at lists.jboss.org
Fri Aug 8 15:10:33 EDT 2008


Author: pferraro
Date: 2008-08-08 15:10:33 -0400 (Fri, 08 Aug 2008)
New Revision: 76843

Modified:
   trunk/tomcat/src/main/org/jboss/web/tomcat/service/modcluster/mcmp/impl/DefaultMCMPHandler.java
Log:
Fixed bug in sendRequest(MCMPRequest, Proxy) where parameter names and all but last parameter value were excluded from the query string.
Code cleanup.

Modified: trunk/tomcat/src/main/org/jboss/web/tomcat/service/modcluster/mcmp/impl/DefaultMCMPHandler.java
===================================================================
--- trunk/tomcat/src/main/org/jboss/web/tomcat/service/modcluster/mcmp/impl/DefaultMCMPHandler.java	2008-08-08 19:05:38 UTC (rev 76842)
+++ trunk/tomcat/src/main/org/jboss/web/tomcat/service/modcluster/mcmp/impl/DefaultMCMPHandler.java	2008-08-08 19:10:33 UTC (rev 76843)
@@ -68,22 +68,15 @@
    /**
     * The string manager for this package.
     */
-   protected StringManager sm =
-       StringManager.getManager(Constants.Package);
+   protected StringManager sm = StringManager.getManager(Constants.Package);
 
-
    // -------------------------------------------------------------- Constants
 
-   
-   
+   // ----------------------------------------------------------------- Fields
 
-   
-   // ----------------------------------------------------------------- Fields
-   
    /** Our configuration */
-   private final MCMPHandlerConfiguration config;  
-   
-   
+   private final MCMPHandlerConfiguration config;
+
    /**
     * Source for reset requests when we need to reset a proxy.
     */
@@ -93,172 +86,168 @@
     * URL encoder used to generate requests bodies.
     */
    private UEncoder encoder = new UEncoder();
-   
+
    /**
     * Proxies.
     */
    private volatile Proxy[] proxies = new Proxy[0];
-   
-   
+
    /**
     * Add proxy list.
     */
-   private ArrayList<Proxy> addProxies = new ArrayList<Proxy>(); 
-   
-   
+   private List<Proxy> addProxies = new ArrayList<Proxy>();
+
    /**
     * Remove proxy list.
     */
-   private ArrayList<Proxy> removeProxies = new ArrayList<Proxy>();
-   
-   
+   private List<Proxy> removeProxies = new ArrayList<Proxy>();
+
    /**
     * Socket factory.
     */
    private JSSESocketFactory sslSocketFactory = null;
-   
+
    /** Initialization completion flag */
    private boolean init;
-   
+
    // -----------------------------------------------------------  Constructors
-   
+
    public DefaultMCMPHandler(MCMPHandlerConfiguration config, ResetRequestSource source)
    {
       this.config = config;
       this.resetRequestSource = source;
-      
-      if (this.config.isSsl()) {
-         sslSocketFactory = new JSSESocketFactory(this.config);
+
+      if (this.config.isSsl())
+      {
+         this.sslSocketFactory = new JSSESocketFactory(this.config);
       }
-   }  
-   
-   
+   }
+
    // -------------------------------------------------------------- Properties
 
-   public ResetRequestSource getResetRequestSource() 
-   { 
-      return this.resetRequestSource; 
+   public ResetRequestSource getResetRequestSource()
+   {
+      return this.resetRequestSource;
    }
-   
+
    // ------------------------------------------------------------  MCMPHandler
-   
+
    public MCMPHandlerConfiguration getConfiguration()
    {
       return this.config;
    }
-   
+
    public synchronized void init(List<AddressPort> initialProxies)
    {
-      if (this.init)
-         return;
-      
+      if (this.init) return;
+
       if (initialProxies != null)
       {
          for (AddressPort initialProxy : initialProxies)
          {
-            addProxy(initialProxy.address, initialProxy.port);
+            this.addProxy(initialProxy.address, initialProxy.port);
          }
       }
-      
-      status(false);
-      
+
+      this.status(false);
+
       this.init = true;
-      
+
    }
-   
+
    public synchronized void shutdown()
-   {  
-      if (!this.init)
-         return;
-      
-      for (int i = 0; i < proxies.length; i++) {
-         synchronized (proxies[i])
+   {
+      if (!this.init) return;
+
+      for (Proxy proxy : this.proxies)
+      {
+         synchronized (proxy)
          {
-            proxies[i].closeConnection();
+            proxy.closeConnection();
          }
       }
-      
+
       this.init = false;
    }
-   
-   public void addProxy(String address) {
-       
-       AddressPort ap = MCMPUtils.parseAddressPort(address);
-       addProxy(ap.address, ap.port);
-   }   
-   
-   public synchronized void addProxy(String host, int port) 
+
+   public void addProxy(String address)
    {
-      InetAddress address = null;
-      try {
-         address = InetAddress.getByName(host);
-      } catch (Exception e) {
+      AddressPort ap = MCMPUtils.parseAddressPort(address);
+      this.addProxy(ap.address, ap.port);
+   }
+
+   public synchronized void addProxy(String host, int port)
+   {
+      try
+      {
+         InetAddress address = InetAddress.getByName(host);
+
+         this.addProxyInternal(address, port);
+      }
+      catch (Exception e)
+      {
          throw new IllegalArgumentException(e);
       }
-      
-      addProxyInternal(address, port); 
    }
-   
+
    public synchronized void addProxy(InetAddress address, int port)
-   {       
-      addProxyInternal(address, port); 
+   {
+      this.addProxyInternal(address, port);
    }
-   
+
    private synchronized Proxy addProxyInternal(InetAddress address, int port)
-   {      
-      for (Proxy candidate : proxies)
+   {
+      for (Proxy candidate : this.proxies)
       {
-         if (candidate.getAddress().equals(address) && candidate.getPort() == port)
-            return candidate;
+         if (candidate.getAddress().equals(address) && candidate.getPort() == port) return candidate;
       }
-      for (Proxy candidate : addProxies)
+      for (Proxy candidate : this.addProxies)
       {
-         if (candidate.getAddress().equals(address) && candidate.getPort() == port)
-            return candidate;
+         if (candidate.getAddress().equals(address) && candidate.getPort() == port) return candidate;
       }
-      for (Proxy candidate : removeProxies)
+      for (Proxy candidate : this.removeProxies)
       {
-         if (candidate.getAddress().equals(address) && candidate.getPort() == port)
-            return candidate;
+         if (candidate.getAddress().equals(address) && candidate.getPort() == port) return candidate;
       }
-      
+
       Proxy proxy = new Proxy(address, port, this.sslSocketFactory, this.config.getSocketTimeout());
       proxy.setState(Proxy.State.ERROR);
-      addProxies.add(proxy);   
+      this.addProxies.add(proxy);
       return proxy;
    }
-   
+
    public synchronized void addProxy(InetAddress address, int port, boolean established)
-   {     
-      Proxy proxy = addProxyInternal(address, port);
+   {
+      Proxy proxy = this.addProxyInternal(address, port);
       proxy.setEstablished(established);
    }
-   
-   
-   public synchronized void removeProxy(String host, int port) 
+
+   public synchronized void removeProxy(String host, int port)
    {
-      InetAddress address = null;
-      try {
-         address = InetAddress.getByName(host);
-      } catch (Exception e) {
+      try
+      {
+         InetAddress address = InetAddress.getByName(host);
+         
+         this.removeProxy(address, port);
+      }
+      catch (Exception e)
+      {
          throw new IllegalArgumentException(e);
       }
-      removeProxy(address, port);
-   }   
-   
-   public synchronized void removeProxy(InetAddress address, int port) 
+   }
+
+   public synchronized void removeProxy(InetAddress address, int port)
    {
       Proxy proxy = new Proxy(address, port, this.sslSocketFactory, this.config.getSocketTimeout());
-      removeProxies.add(proxy);
+      this.removeProxies.add(proxy);
    }
-   
+
    @SuppressWarnings("unchecked")
    public synchronized Set<MCMPServerState> getProxyStates()
    {
       Proxy[] local = this.proxies;
-      if (local == null)
-         return java.util.Collections.EMPTY_SET;
-      
+      if (local == null) return java.util.Collections.EMPTY_SET;
+
       Set<MCMPServerState> result = new HashSet<MCMPServerState>(local.length);
       for (Proxy proxy : local)
       {
@@ -270,7 +259,7 @@
    public synchronized boolean isProxyHealthOK()
    {
       boolean ok = true;
-      Proxy[] local = proxies;
+      Proxy[] local = this.proxies;
       for (Proxy proxy : local)
       {
          if (proxy.getState() != MCMPServerState.State.OK)
@@ -281,10 +270,10 @@
       }
       return ok;
    }
-   
+
    public synchronized void markProxiesInError()
    {
-      Proxy[] local = proxies;
+      Proxy[] local = this.proxies;
       for (Proxy proxy : local)
       {
          synchronized (proxy)
@@ -296,7 +285,7 @@
          }
       }
    }
-   
+
    /**
     * Retrieves the full proxy configuration. To be used through JMX or similar.
     * 
@@ -312,28 +301,29 @@
     *
     * @return the proxy confguration
     */
-   public String getProxyConfiguration() {
-       HashMap<String, String> parameters = new HashMap<String, String>();
-       // Send DUMP * request
-       Proxy[] local = proxies;
-       StringBuffer result = new StringBuffer();
-       for (int i = 0; i < local.length; i++) {
-          
-           result.append("Proxy[").append(i).append("]: [").append(local[i].getAddress())
-                   .append(':').append(local[i].getPort()).append("]: \r\n");
-           synchronized (local[i])
-           {
-              result.append(sendRequest(new MCMPRequest(MCMPRequestType.DUMP, true, parameters), local[i]));
-           }
-           result.append("\r\n");
-       }
-       return result.toString();
+   public String getProxyConfiguration()
+   {
+      Map<String, String> parameters = new HashMap<String, String>();
+      // Send DUMP * request
+      Proxy[] local = this.proxies;
+      StringBuffer result = new StringBuffer();
+      for (int i = 0; i < local.length; i++)
+      {
+         result.append("Proxy[").append(i).append("]: [").append(local[i].getAddress())
+               .append(':').append(local[i].getPort()).append("]: \r\n");
+         synchronized (local[i])
+         {
+            result.append(this.sendRequest(new MCMPRequest(MCMPRequestType.DUMP, true, parameters), local[i]));
+         }
+         result.append("\r\n");
+      }
+      return result.toString();
    }
-   
+
    public InetAddress getLocalAddress() throws IOException
    {
       IOException firstException = null;
-      Proxy[] local = proxies;
+      Proxy[] local = this.proxies;
       for (Proxy proxy : local)
       {
          try
@@ -342,94 +332,98 @@
          }
          catch (IOException e)
          {
-            // Cache the exception in case no other connection works, 
-            // but keep trying 
+            // Cache the exception in case no other connection works,
+            // but keep trying
             if (firstException == null)
+            {
                firstException = e;
+            }
          }
       }
-      
-      if (firstException != null)
-         throw firstException;
-      
+
+      if (firstException != null) throw firstException;
+
       // We get here if there are no proxies
       return null;
    }
-   
-   
+
    /**
     * Reset a DOWN connection to the proxy up to ERROR, where the configuration will
     * be refreshed. To be used through JMX or similar.
     */
-   public void reset() {
-       Proxy[] local = proxies;
-       for (Proxy proxy : local) {
-          synchronized (proxy)
-          {
-           if (proxy.getState() == Proxy.State.DOWN) {
+   public void reset()
+   {
+      Proxy[] local = this.proxies;
+      for (Proxy proxy : local)
+      {
+         synchronized (proxy)
+         {
+            if (proxy.getState() == Proxy.State.DOWN)
+            {
                proxy.setState(Proxy.State.ERROR);
-           }
-          }
-       }
+            }
+         }
+      }
    }
 
-
    /**
     * Send a periodic status request. If in error state, the listener will attempt to refresh
     * the configuration on the front end server.
     * 
     * @param engine
     */
-   public synchronized void status() {
-       
-      if (!this.init)
-         return;
-      
-      status(true);
+   public synchronized void status()
+   {
+      if (!this.init) return;
+
+      this.status(true);
    }
-   
-   private synchronized void status(boolean sendResetRequests) {
-       processPendingDiscoveryEvents();
-       
-       // Attempt to reset any proxies in error
-       List<MCMPRequest> resetRequests = null;       
-       Proxy[] local = proxies;
-       for (Proxy proxy : local) {
-           synchronized (proxy)
-           {
-              if (proxy.getState() == Proxy.State.ERROR) {
-                 proxy.setState(Proxy.State.OK);
-                 
-                 sendRequest(MCMPUtils.getInfoRequest(), proxy);
-                 
-                 if (proxy.getState() == Proxy.State.OK)
-                 {
-                    // We recovered above; if we get another IOException 
-                    // we should log it                    
-                    proxy.setIoExceptionLogged(false);
-                    
-                    if (sendResetRequests)
-                    {
-                       if (resetRequests == null)
-                       {
-                          resetRequests = this.resetRequestSource.getResetRequests();
-                       }
-                       
-                       for (MCMPRequest request : resetRequests)
-                       {
-                          sendRequest(request, proxy);
-                       }
-                    }
-                 }
-              }
-           }
-       }
-       
+
+   private synchronized void status(boolean sendResetRequests)
+   {
+      this.processPendingDiscoveryEvents();
+
+      // Attempt to reset any proxies in error
+      List<MCMPRequest> resetRequests = null;
+      Proxy[] local = this.proxies;
+      for (Proxy proxy : local)
+      {
+         synchronized (proxy)
+         {
+            if (proxy.getState() == Proxy.State.ERROR)
+            {
+               proxy.setState(Proxy.State.OK);
+
+               this.sendRequest(MCMPUtils.getInfoRequest(), proxy);
+
+               if (proxy.getState() == Proxy.State.OK)
+               {
+                  // We recovered above; if we get another IOException
+                  // we should log it
+                  proxy.setIoExceptionLogged(false);
+
+                  if (sendResetRequests)
+                  {
+                     if (resetRequests == null)
+                     {
+                        resetRequests = this.resetRequestSource.getResetRequests();
+                     }
+
+                     for (MCMPRequest request : resetRequests)
+                     {
+                        this.sendRequest(request, proxy);
+                     }
+                  }
+               }
+            }
+         }
+      }
+
    }
-   
+
    /**
     * Send HTTP request, with the specified list of parameters. If an IO error occurs, the error state will
-    * be set. If the front end server reports an error, will mark as error Proxy.State. Other unexpected exceptions 
+    * be set. If the front end server reports an error, will mark as error Proxy.State. Other unexpected exceptions
     * will be thrown and the error state will be set.
     * 
     * @param command
@@ -437,258 +431,309 @@
     * @param parameters
     * @return the response body as a String; null if in error state or a normal error occurs
     */
-   public void sendRequest(MCMPRequest request) {
-       Proxy[] local = proxies;
-       for (Proxy proxy : local)
-       {
-          sendRequest(request, proxy);
-       }
+   public void sendRequest(MCMPRequest request)
+   {
+      Proxy[] local = this.proxies;
+      for (Proxy proxy : local)
+      {
+         this.sendRequest(request, proxy);
+      }
    }
-   
-   
 
    public void sendRequests(List<MCMPRequest> requests)
    {
-      Proxy[] local = proxies;
+      Proxy[] local = this.proxies;
       for (Proxy proxy : local)
       {
          for (MCMPRequest request : requests)
          {
-            sendRequest(request, proxy);
+            this.sendRequest(request, proxy);
          }
-      }      
+      }
    }
 
    // ----------------------------------------------------------------  Private
-   
+
    private synchronized void processPendingDiscoveryEvents()
    {
       // Check to add or remove proxies, and rebuild a new list if needed
-       if (!addProxies.isEmpty() || !removeProxies.isEmpty()) {
-            ArrayList<Proxy> currentProxies = new ArrayList<Proxy>();
-            for (int i = 0; i < proxies.length; i++) {
-                currentProxies.add(proxies[i]);
-            }
-            for (int i = 0; i < addProxies.size(); i++) {
-                if (!currentProxies.contains(addProxies.get(i))) {
-                    currentProxies.add(addProxies.get(i));
-                }
-            }
-            for (int i = 0; i < removeProxies.size(); i++) {
-                if (currentProxies.contains(removeProxies.get(i))) {
-                    currentProxies.remove(removeProxies.get(i));
-                }
-            }
-            addProxies.clear();
-            removeProxies.clear();
-            proxies = currentProxies.toArray(new Proxy[0]);
-            
-            // Reset all connections
-            for (Proxy proxy : proxies)
-            {                  
-               proxy.closeConnection();
-            }
-       }
+      if (!this.addProxies.isEmpty() || !this.removeProxies.isEmpty())
+      {
+         Set<Proxy> currentProxies = new HashSet<Proxy>();
+
+         for (Proxy proxy : this.proxies)
+         {
+            currentProxies.add(proxy);
+         }
+         
+         for (Proxy proxy: this.addProxies)
+         {
+            currentProxies.add(proxy);
+         }
+         for (Proxy proxy: this.removeProxies)
+         {
+            currentProxies.remove(proxy);
+         }
+         this.addProxies.clear();
+         this.removeProxies.clear();
+         this.proxies = currentProxies.toArray(new Proxy[0]);
+
+         // Reset all connections
+         for (Proxy proxy : this.proxies)
+         {
+            proxy.closeConnection();
+         }
+      }
    }
 
-   private synchronized String sendRequest(MCMPRequest request, Proxy proxy) {
-
+   private synchronized String sendRequest(MCMPRequest request, Proxy proxy)
+   {
       // If there was an error, do nothing until the next periodic event, where the whole configuration
       // will be refreshed
-      if (proxy.getState() != Proxy.State.OK) {
-          return null;
+      if (proxy.getState() != Proxy.State.OK) return null;
+
+      BufferedReader reader = null;
+      BufferedWriter writer = null;
+      CharChunk body = null;
+
+      String command = request.getRequestType().getCommand();
+      boolean wildcard = request.isWildcard();
+      Map<String, String> parameters = request.getParameters();
+
+      // First, encode the POST body
+      try
+      {
+         body = this.encoder.encodeURL("", 0, 0);
+         body.recycle();
+
+         Iterator<String> keys = parameters.keySet().iterator();
+
+         while (keys.hasNext())
+         {
+            String key = keys.next();
+            String value = parameters.get(key);
+
+            if (value == null)
+            {
+               throw new IllegalArgumentException(this.sm.getString("modcluster.error.nullAttribute", key));
+            }
+            
+            body.append(this.encoder.encodeURL(key, 0, key.length()));
+            body.append('=');
+            body.append(this.encoder.encodeURL(value, 0, value.length()));
+
+            if (keys.hasNext())
+            {
+               body.append('&');
+            }
+         }
       }
+      catch (IOException e)
+      {
+         if (body != null)
+         {
+            body.recycle();
+         }
+         // Error encoding URL, should not happen
+         throw new IllegalArgumentException(e);
+      }
 
-       BufferedReader reader = null;
-       BufferedWriter writer = null;
-       CharChunk body = null;
-       
-       String command = request.getRequestType().getCommand();
-       boolean wildcard = request.isWildcard();
-       Map<String, String> parameters = request.getParameters();
-       
-       // First, encode the POST body
-       try {
-           body = encoder.encodeURL("", 0, 0);
-           body.recycle();
-           Iterator<String> keys = parameters.keySet().iterator();
-           while (keys.hasNext()) {
-               String key = keys.next();
-               String value = parameters.get(key);
-               if (value == null) {
-                   throw new IllegalArgumentException(sm.getString("modcluster.error.nullAttribute", key));
-               }
-               body = encoder.encodeURL(key, 0, key.length());
-               body.append('=');
-               if (value != null) {
-                   body = encoder.encodeURL(value, 0, value.length());
-               }
-               if (keys.hasNext()) {
-                   body.append('&');
-               }
-           }
-       } catch (IOException e) {
-           body.recycle();
-           // Error encoding URL, should not happen
-           throw new IllegalArgumentException(e);
-       }
-        
-        if (log.isTraceEnabled()) {
-            log.trace(sm.getString("modcluster.request", command, wildcard, proxy));
-        }
-        
-        synchronized (proxy)
-        {
-        
-           try {
-   
-               // Then, connect to the proxy
+      if (log.isTraceEnabled())
+      {
+         log.trace(this.sm.getString("modcluster.request", command, new Boolean(wildcard), proxy));
+      }
+
+      synchronized (proxy)
+      {
+         try
+         {
+            // Then, connect to the proxy
+            proxy.getConnection();
+            writer = proxy.getConnectionWriter();
+            // Check connection to see if it is still alive (not really allowed,
+            // but httpd deals with the extra CRLF)
+            try
+            {
+               writer.write("\r\n");
+               writer.flush();
+            }
+            catch (IOException e)
+            {
+               // Get a new connection; if it fails this second time, it is an error
+               proxy.closeConnection();
                proxy.getConnection();
                writer = proxy.getConnectionWriter();
-               // Check connection to see if it is still alive (not really allowed, 
-               // but httpd deals with the extra CRLF)
-               try {
-                   writer.write("\r\n");
-                   writer.flush();
-               } catch (IOException e) {
-                   // Get a new connection; if it fails this second time, it is an error
-                   proxy.closeConnection();
-                   proxy.getConnection();
-                   writer = proxy.getConnectionWriter();
+            }
+
+            // Generate and write request
+            String url = this.config.getProxyURL();
+            
+            StringBuilder builder = new StringBuilder();
+            
+            builder.append(command).append(" ");
+            
+            if (url != null)
+            {
+               builder.append(url);
+            }
+            
+            if (builder.charAt(builder.length() - 1) != '/')
+            {
+               builder.append('/');
+            }
+            
+            if (wildcard)
+            {
+               builder.append('*');
+            }
+            
+            builder.append(" HTTP/1.0");
+            
+            writer.write(builder.toString());
+            writer.write("\r\n");
+            writer.write("Content-Length: " + body.getLength() + "\r\n");
+            writer.write("User-Agent: ClusterListener/1.0\r\n");
+            writer.write("Connection: Keep-Alive\r\n");
+            writer.write("\r\n");
+            writer.write(body.getBuffer(), body.getStart(), body.getLength());
+            writer.write("\r\n");
+            writer.flush();
+
+            // Read the response to a string
+            reader = proxy.getConnectionReader();
+            // Read the first response line and skip the rest of the HTTP header
+            String responseStatus = reader.readLine();
+            // Parse the line, which is formed like HTTP/1.x YYY Message
+            int status = 500;
+            String version = "0";
+            String message = null;
+            String errorType = null;
+            int contentLength = 0;
+            if (responseStatus != null)
+            {
+               try
+               {
+                  responseStatus = responseStatus.substring(responseStatus.indexOf(' ') + 1, responseStatus.indexOf(
+                        ' ', responseStatus.indexOf(' ') + 1));
+                  status = Integer.parseInt(responseStatus);
+                  String header = reader.readLine();
+                  while (!"".equals(header))
+                  {
+                     int colon = header.indexOf(':');
+                     String headerName = header.substring(0, colon).trim();
+                     String headerValue = header.substring(colon + 1).trim();
+                     if ("version".equalsIgnoreCase(headerName))
+                     {
+                        version = headerValue;
+                     }
+                     else if ("type".equalsIgnoreCase(headerName))
+                     {
+                        errorType = headerValue;
+                     }
+                     else if ("mess".equalsIgnoreCase(headerName))
+                     {
+                        message = headerValue;
+                     }
+                     else if ("content-length".equalsIgnoreCase(headerName))
+                     {
+                        contentLength = Integer.parseInt(headerValue);
+                     }
+                     header = reader.readLine();
+                  }
                }
-   
-               // Generate and write request
-               String url = this.config.getProxyURL();
-               if (url == null) {
-                   url = (wildcard) ? "/*" : "/";
-               } else {
-                   if (url.endsWith("/") && wildcard) {
-                       url = url + "*";
-                   } else if (wildcard) {
-                       url = url + "/*";
-                   }
+               catch (Exception e)
+               {
+                  log.info(this.sm.getString("modcluster.error.parse", command), e);
                }
-               String requestLine = command + " " + url + " HTTP/1.0";
-               writer.write(requestLine);
-               writer.write("\r\n");
-               writer.write("Content-Length: " + body.getLength() + "\r\n");
-               writer.write("User-Agent: ClusterListener/1.0\r\n");
-               writer.write("Connection: Keep-Alive\r\n");
-               writer.write("\r\n");
-               writer.write(body.getBuffer(), body.getStart(), body.getLength());
-               writer.write("\r\n");
-               writer.flush();
-   
-               // Read the response to a string
-               reader = proxy.getConnectionReader();
-               // Read the first response line and skip the rest of the HTTP header
-               String responseStatus = reader.readLine();
-               // Parse the line, which is formed like HTTP/1.x YYY Message
-               int status = 500;
-               String version = "0";
-               String message = null;
-               String errorType = null;
-               int contentLength = 0;
-               if (responseStatus != null) {
-                   try {
-                       responseStatus = responseStatus.substring(responseStatus.indexOf(' ') + 1, responseStatus.indexOf(' ', responseStatus.indexOf(' ') + 1));
-                       status = Integer.parseInt(responseStatus);
-                       String header = reader.readLine();
-                       while (!"".equals(header)) {
-                           int colon = header.indexOf(':');
-                           String headerName = header.substring(0, colon).trim();
-                           String headerValue = header.substring(colon + 1).trim();
-                           if ("version".equalsIgnoreCase(headerName)) {
-                               version = headerValue;
-                           } else if ("type".equalsIgnoreCase(headerName)) {
-                               errorType = headerValue;
-                           } else if ("mess".equalsIgnoreCase(headerName)) {
-                               message = headerValue;
-                           } else if ("content-length".equalsIgnoreCase(headerName)) {
-                               contentLength = Integer.parseInt(headerValue);
-                           }
-                           header = reader.readLine();
-                       }
-                   } catch (Exception e) {
-                       log.info(sm.getString("modcluster.error.parse", command), e);
-                   }
+            }
+
+            // Mark as error if the front end server did not return 200; the configuration will
+            // be refreshed during the next periodic event
+            if (status == 200)
+            {
+
+               // We know the request succeeded, so if appropriate
+               // mark the proxy as established before any possible
+               // later exception happens
+               if (request.getRequestType().getEstablishesServer())
+               {
+                  proxy.setEstablished(true);
                }
-   
-               // Mark as error if the front end server did not return 200; the configuration will
-               // be refreshed during the next periodic event 
-               if (status == 200) {
-                   
-                   // We know the request succeeded, so if appropriate
-                   // mark the proxy as established before any possible
-                   // later exception happens
-                   if (request.getRequestType().getEstablishesServer()) {
-                      proxy.setEstablished(true);
-                   }
-                   
-                   // Read the request body
-                   StringBuffer result = new StringBuffer();
-                   if (contentLength > 0) {
-                       int thisTime = contentLength;
-                       char[] buf = new char[512];
-                       while (contentLength > 0) {
-                           thisTime = (contentLength > buf.length) ? buf.length : contentLength;
-                           int n = reader.read(buf, 0, thisTime);
-                           if (n <= 0) {
-                               break;
-                           } else {
-                               result.append(buf, 0, n);
-                               contentLength -= n;
-                           }
-                       }
-                   }
-                   
-                   return result.toString();
-                   
-               } else {
-                   if ("SYNTAX".equals(errorType)) {
-                       // Syntax error means the protocol is incorrect, which cannot be automatically fixed
-                       proxy.setState(Proxy.State.DOWN);
-                       log.error(sm.getString("modcluster.error.syntax", command, proxy, errorType, message));
-                   } else {
-                       proxy.setState(Proxy.State.ERROR);
-                       log.error(sm.getString("modcluster.error.other", command, proxy, errorType, message));
-                   }
+
+               // Read the request body
+               StringBuilder result = new StringBuilder();
+               if (contentLength > 0)
+               {
+                  int thisTime = contentLength;
+                  char[] buf = new char[512];
+                  while (contentLength > 0)
+                  {
+                     thisTime = (contentLength > buf.length) ? buf.length : contentLength;
+                     int n = reader.read(buf, 0, thisTime);
+                     
+                     if (n <= 0) break;
+
+                     result.append(buf, 0, n);
+                     contentLength -= n;
+                  }
                }
-   
-           } catch (IOException e) {
-               // Most likely this is a connection error with the proxy
+
+               return result.toString();
+            }
+
+            if ("SYNTAX".equals(errorType))
+            {
+               // Syntax error means the protocol is incorrect, which cannot be automatically fixed
+               proxy.setState(Proxy.State.DOWN);
+               log.error(this.sm.getString("modcluster.error.syntax", command, proxy, errorType, message));
+            }
+            else
+            {
                proxy.setState(Proxy.State.ERROR);
-               
-               // Log it only if we haven't done so already. Don't spam the log
-               if (proxy.isIoExceptionLogged() == false) {                  
-                  log.info(sm.getString("modcluster.error.io", command, proxy), e);
-                  proxy.setIoExceptionLogged(true);
-               }
-           } finally {
-               // If there's an error of any sort, or if the proxy did not return 200, it is an error
-               if (proxy.getState() != Proxy.State.OK) {
-                   proxy.closeConnection();
-               }
-           }
-        }
+               log.error(this.sm.getString("modcluster.error.other", command, proxy, errorType, message));
+            }
+         }
+         catch (IOException e)
+         {
+            // Most likely this is a connection error with the proxy
+            proxy.setState(Proxy.State.ERROR);
 
-       return null;
-       
+            // Log it only if we haven't done so already. Don't spam the log
+            if (proxy.isIoExceptionLogged() == false)
+            {
+               log.info(this.sm.getString("modcluster.error.io", command, proxy), e);
+               proxy.setIoExceptionLogged(true);
+            }
+         }
+         finally
+         {
+            // If there's an error of any sort, or if the proxy did not return 200, it is an error
+            if (proxy.getState() != Proxy.State.OK)
+            {
+               proxy.closeConnection();
+            }
+         }
+      }
+
+      return null;
+
    }
-   
+
    /**
     * This class represents a front-end httpd server.
     */
    private static class Proxy implements MCMPServerState
    {
       public static final int DEFAULT_PORT = 8000;
-      
+
       private final InetAddress address;
       private final int port;
+      private final JSSESocketFactory sslSocketFactory;
+      private final int socketTimeout;
+
       private volatile State state = State.OK;
       private volatile boolean established;
-      private final JSSESocketFactory sslSocketFactory;
-      private final int socketTimeout;
+
       private Socket connection;
       private BufferedReader connectionReader;
       private BufferedWriter connectionWriter;
@@ -697,35 +742,34 @@
       /**
        * The string manager for this package.
        */
-      private final StringManager sm =
-          StringManager.getManager(Constants.Package);
-      
-      private Proxy(InetAddress address, int port, JSSESocketFactory sslSocketFactory, int socketTimeout)
+      private final StringManager sm = StringManager.getManager(Constants.Package);
+
+      Proxy(InetAddress address, int port, JSSESocketFactory sslSocketFactory, int socketTimeout)
       {
          if (address == null)
          {
-            throw new IllegalArgumentException(sm.getString("modcluster.error.iae.null", "address"));
+            throw new IllegalArgumentException(this.sm.getString("modcluster.error.iae.null", "address"));
          }
          if (port <= 0)
          {
-            throw new IllegalArgumentException(sm.getString("modcluster.error.iae.invalid", port, "port"));
+            throw new IllegalArgumentException(this.sm.getString("modcluster.error.iae.invalid", new Integer(port), "port"));
          }
-         
+
          this.address = address;
          this.port = port;
          this.sslSocketFactory = sslSocketFactory;
          this.socketTimeout = socketTimeout;
-      }       
-      
+      }
+
       // -------------------------------------------- MCMPServerConnectionState
-      
+
       public synchronized State getState()
       {
          return this.state;
-      }       
-      
+      }
+
       // ----------------------------------------------------------- MCMPServer
-      
+
       public InetAddress getAddress()
       {
          return this.address;
@@ -735,39 +779,42 @@
       {
          return this.port;
       }
-      
+
       public boolean isEstablished()
       {
          return this.established;
       }
-      
+
       // ------------------------------------------------------------ Overrides
 
-      public String toString() {
-         if (this.address == null) {
-            return ":" + this.port;
-         } else {
-            return this.address.getHostAddress() + ":" + this.port;
+      @Override
+      public String toString()
+      {
+         StringBuilder builder = new StringBuilder();
+         
+         if (this.address != null)
+         {
+            builder.append(this.address.getHostAddress());
          }
+         
+         return builder.append(':').append(this.port).toString();
       }
 
       @Override
-      public boolean equals(Object o) {
-         if (o instanceof Proxy) {
+      public boolean equals(Object o)
+      {
+         if (o instanceof Proxy)
+         {
             Proxy compare = (Proxy) o;
-            if (this.port != compare.port) {
-               return false;
+            if (this.port != compare.port) return false;
+            if (compare.address == null)
+            {
+               if (this.address == null) return true;
             }
-            if (compare.address == null) {
-               if (this.address == null) {
-                  return true;
-               }
-            } else if ((compare.address.equals(this.address)) && this.port == compare.port) {
-               return true;
-            }
+            else if ((compare.address.equals(this.address)) && this.port == compare.port) return true;
          }
          return false;
-      } 
+      }
 
       @Override
       public int hashCode()
@@ -777,157 +824,167 @@
          result += 23 * this.port;
          return result;
       }
-      
+
       // -------------------------------------------------------------- Private
 
-      private synchronized void setState(State state)
+      synchronized void setState(State state)
       {
          if (state == null)
-         {
-            throw new IllegalArgumentException(sm.getString("modcluster.error.iae.null", "state"));
-         }
+            throw new IllegalArgumentException(this.sm.getString("modcluster.error.iae.null", "state"));
          this.state = state;
       }
-      
-      private synchronized void setEstablished(boolean established)
+
+      synchronized void setEstablished(boolean established)
       {
          this.established = established;
-      }      
-      
+      }
+
       /**
        * Return a reader to the proxy.
        */
-      private synchronized Socket getConnection()
-          throws IOException {
-          if (connection == null || connection.isClosed()) {
-              if (this.sslSocketFactory != null) {
-                  connection = this.sslSocketFactory.createSocket(this.address, this.port);
-              } else {
-                  connection = new Socket(this.address, this.port);
-              }
-              connection.setSoTimeout(this.socketTimeout);
-          }
-          return connection;
+      synchronized Socket getConnection() throws IOException
+      {
+         if (this.connection == null || this.connection.isClosed())
+         {
+            if (this.sslSocketFactory != null)
+            {
+               this.connection = this.sslSocketFactory.createSocket(this.address, this.port);
+            }
+            else
+            {
+               this.connection = new Socket(this.address, this.port);
+            }
+            this.connection.setSoTimeout(this.socketTimeout);
+         }
+         return this.connection;
       }
-      
 
       /**
        * Return a reader to the proxy.
        */
-      private synchronized BufferedReader getConnectionReader()
-          throws IOException {
-          if (this.connectionReader == null) {
-              this.connectionReader = new BufferedReader(new InputStreamReader(this.connection.getInputStream()));
-          }
-          return this.connectionReader;
+      synchronized BufferedReader getConnectionReader() throws IOException
+      {
+         if (this.connectionReader == null)
+         {
+            this.connectionReader = new BufferedReader(new InputStreamReader(this.connection.getInputStream()));
+         }
+         return this.connectionReader;
       }
-      
 
       /**
        * Return a writer to the proxy.
        */
-      private synchronized BufferedWriter getConnectionWriter()
-          throws IOException {
-          if (connectionWriter == null) {
-              connectionWriter = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));
-          }
-          return connectionWriter;
+      synchronized BufferedWriter getConnectionWriter() throws IOException
+      {
+         if (this.connectionWriter == null)
+         {
+            this.connectionWriter = new BufferedWriter(new OutputStreamWriter(this.connection.getOutputStream()));
+         }
+         return this.connectionWriter;
       }
-      
 
       /**
        * Close connection.
        */
-      private synchronized void closeConnection() {
-          try {
-              if (connectionReader != null) {
-                  connectionReader.close();
-              }
-          } catch (IOException e) {
-              // Ignore
-          }
-          connectionReader = null;
-          try {
-              if (connectionWriter != null) {
-                  connectionWriter.close();
-              }
-          } catch (IOException e) {
-              // Ignore
-          }
-          connectionWriter = null;
-          try {
-              if (connection != null) {
-                  connection.close();
-              }
-          } catch (IOException e) {
-              // Ignore
-          }
-          connection = null;
+      synchronized void closeConnection()
+      {
+         try
+         {
+            if (this.connectionReader != null)
+            {
+               this.connectionReader.close();
+            }
+         }
+         catch (IOException e)
+         {
+            // Ignore
+         }
+         this.connectionReader = null;
+         try
+         {
+            if (this.connectionWriter != null)
+            {
+               this.connectionWriter.close();
+            }
+         }
+         catch (IOException e)
+         {
+            // Ignore
+         }
+         this.connectionWriter = null;
+         try
+         {
+            if (this.connection != null)
+            {
+               this.connection.close();
+            }
+         }
+         catch (IOException e)
+         {
+            // Ignore
+         }
+         this.connection = null;
       }
 
-      private boolean isIoExceptionLogged()
+      boolean isIoExceptionLogged()
       {
          return this.ioExceptionLogged;
       }
 
-      private void setIoExceptionLogged(boolean ioErrorLogged)
+      void setIoExceptionLogged(boolean ioErrorLogged)
       {
          this.ioExceptionLogged = ioErrorLogged;
       }
-      
-      
    }
-   
+
    @Immutable
    private static class MCMPServerStateImpl implements MCMPServerState, Serializable
    {
       /** The serialVersionUID */
       private static final long serialVersionUID = 5219680414337319908L;
-      
+
       private final State state;
       private final InetAddress address;
       private final int port;
       private final boolean established;
-      
-      private MCMPServerStateImpl(MCMPServerState source)
+
+      MCMPServerStateImpl(MCMPServerState source)
       {
          this.state = source.getState();
          this.address = source.getAddress();
          this.port = source.getPort();
          this.established = source.isEstablished();
       }
-      
+
       public State getState()
       {
-         return state;
+         return this.state;
       }
 
       public InetAddress getAddress()
       {
-         return address;
+         return this.address;
       }
 
       public int getPort()
       {
-         return port;
+         return this.port;
       }
 
       public boolean isEstablished()
       {
-         return established;
+         return this.established;
       }
 
       @Override
       public boolean equals(Object obj)
       {
-         if (this == obj)
-            return true;
-         
+         if (this == obj) return true;
+
          if (obj instanceof MCMPServerStateImpl)
          {
             MCMPServerStateImpl other = (MCMPServerStateImpl) obj;
-            return (this.port == other.port && this.address.equals(other.address) 
-                        && this.state == other.state && this.established == other.established);
+            return (this.port == other.port && this.address.equals(other.address) && this.state == other.state && this.established == other.established);
          }
          return false;
       }
@@ -946,14 +1003,12 @@
       @Override
       public String toString()
       {
-         StringBuilder sb = new StringBuilder(getClass().getSimpleName()); 
-         sb.append("{address=").append(address)
-           .append(",port=").append(port)
-           .append(",state=").append(state)
-           .append(",established").append(established).append("}");
+         StringBuilder sb = new StringBuilder(this.getClass().getSimpleName());
+         sb.append("{address=").append(this.address)
+           .append(",port=").append(this.port)
+           .append(",state=").append(this.state)
+           .append(",established").append(this.established).append("}");
          return sb.toString();
       }
-      
    }
-
 }




More information about the jboss-cvs-commits mailing list