[Mulgara-svn] r718 - in trunk/src/jar: server/java/org/mulgara/server server-beep/java/org/mulgara/server/beep server-rmi/java/org/mulgara/server/rmi

pag at mulgara.org pag at mulgara.org
Fri Mar 28 03:48:16 UTC 2008


Author: pag
Date: 2008-03-27 20:48:15 -0700 (Thu, 27 Mar 2008)
New Revision: 718

Modified:
   trunk/src/jar/server-beep/java/org/mulgara/server/beep/BEEPServer.java
   trunk/src/jar/server-rmi/java/org/mulgara/server/rmi/RmiServer.java
   trunk/src/jar/server/java/org/mulgara/server/AbstractServer.java
Log:
Fixed port handling in URIs for servers. Fixed formatting while there.

Modified: trunk/src/jar/server/java/org/mulgara/server/AbstractServer.java
===================================================================
--- trunk/src/jar/server/java/org/mulgara/server/AbstractServer.java	2008-03-27 02:43:41 UTC (rev 717)
+++ trunk/src/jar/server/java/org/mulgara/server/AbstractServer.java	2008-03-28 03:48:15 UTC (rev 718)
@@ -31,7 +31,6 @@
 import java.io.*;
 import java.lang.reflect.*;
 import java.net.*;
-import javax.naming.*;
 
 // Third party packages
 /*
@@ -54,51 +53,27 @@
  * access to the database.
  *
  * @created 2001-09-15
- *
  * @author <a href="http://staff.pisoftware.com/raboczi">Simon Raboczi</a>
- *
- * @version $Revision: 1.9 $
- *
- * @modified $Date: 2005/01/05 04:58:59 $
- *
- * @maintenanceAuthor $Author: newmana $
- *
- * @company <A href="mailto:info at PIsoftware.com">Plugged In Software</A>
- *
- * @copyright &copy;2001 <a href="http://www.pisoftware.com/">Plugged In
- *      Software Pty Ltd</a>
- *
+ * @copyright &copy;2001 <a href="http://www.pisoftware.com/">Plugged In Software Pty Ltd</a>
  * @licence <a href="{@docRoot}/../../LICENCE">Mozilla Public License v1.1</a>
- *
  * @see <a href="http://developer.java.sun.com/developer/JDCTechTips/2001/tt0327.html#jndi">
  *      <cite>JNDI lookup in distributed systems</cite> </a>
  */
 public abstract class AbstractServer implements ServerMBean {
 
-  /**
-   * Logger. This is named after the classname.
-   */
-  private final static Logger logger =
-      Logger.getLogger(AbstractServer.class.getName());
+  /** Logger. This is named after the classname. */
+  private final static Logger logger = Logger.getLogger(AbstractServer.class.getName());
 
-  /**
-   * The class name of the {@link SessionFactory} implementation.
-   */
+  /** The class name of the {@link SessionFactory} implementation. */
   private String providerClassName;
 
-  /**
-   * The directory where the server can write files.
-   */
+  /** The directory where the server can write files. */
   private File dir;
 
-  /**
-   * The directory where the server can write temporary files.
-   */
+  /** The directory where the server can write temporary files. */
   private File tempdir;
 
-  /**
-   * The server URI.
-   */
+  /** The server URI. */
   private URI uri;
 
   /**
@@ -106,81 +81,67 @@
    */
   private int portNumber = -1;
 
-  /**
-   * The hostname of the server.
-   */
+  /** The hostname of the server. */
   protected String hostname = null;
 
-  /**
-   * State.
-   */
+  /** State. */
   private int state = UNINITIALIZED;
 
-  /**
-   * The server object.
-   */
+  /** The server object. */
   private SessionFactory sessionFactory;
 
   /** The session factory config object */
   private MulgaraConfig sessionConfig;
 
-  /**
-   * ZeroConf server.
-   */
-  /*
-  private JmDNS jmdns;
-  */
+  // /** ZeroConf server. */
+  // private JmDNS jmdns;
 
   /**
    * Returns the hostname of the server.
-   *
    * @return The Hostname value
    */
   public String getHostname() {
-
     return hostname;
   }
 
+  /**
+   * Sets the server port.
+   * @param newPortNumber The new port to bind to.
+   */
   public void setPortNumber(int newPortNumber) {
-
+    // Prevent the port from being changed while the server is up
+    if (this.getState() == STARTED) {
+      throw new IllegalStateException("Can't change server port without first stopping the server");
+    }
     portNumber = newPortNumber;
+    if (uri != null && uri.getPort() == -1) uri = updateUriPort(uri);
+    // else expect URI to be updated now
   }
 
   /**
    * Returns the port number that the server is to bind to.
-   *
    * @return the port number value.
    */
   public int getPortNumber() {
-
     return portNumber;
   }
 
   /**
    * Sets the hostname of the server.
-   *
-   * @param newHostname  the hostname of the server, if <code>null</code>
-   *     <code>localhost</code> will be used
-   * @throws IllegalStateException if the service is started or if the
-   *      underlying session factory already has a fixed hostname
+   * @param newHostname  the hostname of the server, if <code>null</code> <code>localhost</code> will be used
+   * @throws IllegalStateException if the service is started or if the underlying session factory already has a fixed hostname
    */
   public void setHostname(String newHostname) {
-
     // Prevent the hostname from being changed while the server is up
     if (this.getState() == STARTED) {
-
-      throw new IllegalStateException(
-          "Can't change hostname without first stopping the server");
+      throw new IllegalStateException("Can't change hostname without first stopping the server");
     }
 
     // Reset the field
-    if (hostname == null) {
-
+    if (newHostname == null) {
       this.hostname = "localhost";
       logger.warn("Hostname supplied is null, defaulting to localhost");
-    }
-    else {
-
+    } else {
       hostname = newHostname;
     }
   }
@@ -191,13 +152,11 @@
    * @param dir The new Dir value
    */
   public void setDir(File dir) {
-
     this.dir = dir;
   }
 
   /**
    * Set the temporary database directory.
-   *
    * @param tempdir The new Dir value
    */
   public void setTempDir(File tempdir) {
@@ -207,11 +166,9 @@
 
   /**
    * Set the database provider classname.
-   *
    * @param providerClassName The new ProviderClassName value
    */
   public void setProviderClassName(String providerClassName) {
-
     this.providerClassName = providerClassName;
   }
 
@@ -221,62 +178,50 @@
 
   /**
    * Read the server state.
-   *
    * @return The current server state.
    */
   public int getState() {
-
     return state;
   }
 
   /**
    * Read the database directory.
-   *
    * @return The Dir value
    */
   public File getDir() {
-
     return dir;
   }
 
   /**
    * Read the temporary database directory.
-   *
    * @return The tempdir value
    */
   public File getTempDir() {
-
     return tempdir;
   }
 
   /**
    * Read the database provider classname.
-   *
    * @return The ProviderClassName value
    */
   public String getProviderClassName() {
-
     return providerClassName;
   }
 
   /**
    * Read the database URI.
-   *
    * @return The URI value
    */
   public URI getURI() {
-
     return uri;
   }
 
   /**
    * Allow access by subclasses to the session factory.
-   *
-   * @return <code>null</code> in the {@link #UNINITIALIZED} state, the {@link
-   *      SessionFactory} instance otherwise
+   * @return <code>null</code> in the {@link #UNINITIALIZED} state, the {@link SessionFactory}
+   *         instance otherwise
    */
   public SessionFactory getSessionFactory() {
-
     return sessionFactory;
   }
 
@@ -289,91 +234,61 @@
    * database. Initialization requires a non-null <var>name</var> and <var>
    * providerClassName</var> .
    *
-   * @throws ClassNotFoundException if the <var>providerClassName</var> isn't in
-   *      the classpath
-   * @throws IOException if the persistence directory doesn't exist and can't be
-   *      created
-   * @throws NoSuchMethodException if the <var>providerClassName</var> doesn't
-   *      have a constructor with the correct signature
-   * @throws IllegalAccessException EXCEPTION TO DO
-   * @throws InstantiationException EXCEPTION TO DO
-   * @throws InvocationTargetException EXCEPTION TO DO
+   * @throws ClassNotFoundException if the <var>providerClassName</var> isn't in the classpath
+   * @throws IOException if the persistence directory doesn't exist and can't be created
+   * @throws NoSuchMethodException if the <var>providerClassName</var> doesn't have a
+   *         constructor with the correct signature
+   * @throws IllegalAccessException There was a permissions error during setup.
+   * @throws InstantiationException The {@link SessionFactory} could not be created.
+   * @throws InvocationTargetException  The {@link SessionFactory} had an error during construction.
    */
   public final void init() throws ClassNotFoundException,
       IllegalAccessException, InstantiationException, InvocationTargetException,
       IOException, NoSuchMethodException {
 
-    // Create the server
-    if (logger.isInfoEnabled()) {
-      logger.info("Create server");
-    }
+    if (logger.isInfoEnabled()) logger.info("Create server");
 
     // Validate state
-    if (dir == null) {
+    if (dir == null) throw new IllegalStateException("Must set \"dir\" property");
+    if (tempdir == null) throw new IllegalStateException("Must set \"tempdir\" property");
+    if (providerClassName == null) throw new IllegalStateException("Must set \"providerClassName\" property");
 
-      throw new IllegalStateException("Must set \"dir\" property");
-    }
-
-    if (tempdir == null) {
-
-      throw new IllegalStateException("Must set \"tempdir\" property");
-    }
-
-    if (providerClassName == null) {
-
-      throw new IllegalStateException("Must set \"providerClassName\" property");
-    }
-
     // Create the directory if necessary
-    if (!dir.exists()) {
+    if (!dir.exists()) dir.mkdir();
 
-      dir.mkdir();
-    }
-
     // create the temporary directory
     tempdir.mkdirs();
 
     // Log provider class name
-    if (logger.isInfoEnabled()) {
-      logger.info("Provider class is " + providerClassName);
-    }
+    if (logger.isInfoEnabled()) logger.info("Provider class is " + providerClassName);
 
     if (sessionConfig == null) {
-
       // Create the session factory using the two parameter constructor if we
       // have no configuration
       sessionFactory =
-          (SessionFactory) Class.forName(providerClassName)
-          .getConstructor(new Class[] {
-                          URI.class, File.class})
-          .newInstance(new Object[] {
-                       getURI(), dir});
+          (SessionFactory)Class.forName(providerClassName)
+          .getConstructor(new Class[] {URI.class, File.class})
+          .newInstance(new Object[] {getURI(), dir});
     } else {
-
       // Create the session factory using the three parameter constructor if we
       // have a configuration to use
       sessionFactory =
-          (SessionFactory) Class.forName(providerClassName)
-          .getConstructor(new Class[] {
-                          URI.class, File.class, MulgaraConfig.class})
-          .newInstance(new Object[] {
-                       getURI(), dir, sessionConfig});
+          (SessionFactory)Class.forName(providerClassName)
+          .getConstructor(new Class[] {URI.class, File.class, MulgaraConfig.class})
+          .newInstance(new Object[] {getURI(), dir, sessionConfig});
     }
 
-    //assert sessionFactory != null;
     state = STOPPED;
 
     // Log successful creation
-    if (logger.isInfoEnabled()) {
-      logger.info("Created server");
-    }
+    if (logger.isInfoEnabled()) logger.info("Created server");
   }
 
   /**
    * Make the server available over the network. If successful the new state
    * should be {@link #STARTED}.
-   *
-   * @throws Exception EXCEPTION TO DO
+   * @throws IllegalStateException The service is not configured, or is already running.
+   * @throws Exception A service specific error occurred during startup.
    */
   public final void start() throws Exception {
 
@@ -389,42 +304,35 @@
         throw new IllegalStateException("Already started");
     }
 
-    //assert state == STOPPED
+    assert state == STOPPED;
+
     // Invariant tests for the STOPPED state
-    if (sessionFactory == null) {
+    if (sessionFactory == null) throw new AssertionError("Null \"sessionFactory\" parameter");
 
-      throw new AssertionError("Null \"sessionFactory\" parameter");
-    }
-
     startService();
 
-    /*
     // Start advertising the service via ZeroConf
-    if (jmdns == null) {
-      try {
-        logger.info("Starting ZeroConf server");
-        jmdns = new JmDNS(InetAddress.getLocalHost());
-        logger.info("Started ZeroConf server");
+    // if (jmdns == null) {
+    //   try {
+    //     logger.info("Starting ZeroConf server");
+    //     jmdns = new JmDNS(InetAddress.getLocalHost());
+    //     logger.info("Started ZeroConf server");
 
-        String type = "_rmi._tcp.local";
-        logger.info(
-          "Registering as itql."+type+" on port 1099 with ZeroConf server"
-        );
-        jmdns.registerService(new ServiceInfo(
-          type,           // type
-          "itql."+type,   // name
-          1099,           // port
-          0,              // weight
-          0,              // priority
-          "path=server1"  // text
-        ));
-        logger.info("Registered with ZeroConf server");
-      }
-      catch (IOException e) {
-        logger.warn("Couldn't start ZeroConf server", e);
-      }
-    }
-    */
+    //     String type = "_rmi._tcp.local";
+    //     logger.info("Registering as itql."+type+" on port 1099 with ZeroConf server");
+    //     jmdns.registerService(new ServiceInfo(
+    //       type,           // type
+    //       "itql."+type,   // name
+    //       1099,           // port
+    //       0,              // weight
+    //       0,              // priority
+    //       "path=server1"  // text
+    //     ));
+    //     logger.info("Registered with ZeroConf server");
+    //   } catch (IOException e) {
+    //     logger.warn("Couldn't start ZeroConf server", e);
+    //   }
+    // }
 
     state = STARTED;
     logger.info("Started");
@@ -432,27 +340,21 @@
 
   /**
    * Make the server unavailable over the network. If successful the new state
-   * should be {@link #STOPPED}.
-   *
-   * @throws Exception EXCEPTION TO DO
+   * will be {@link #STOPPED}.
+   * @throws IllegalStateException If the server is not running
+   * @throws Exception There was a service specific error in shutting down.
    */
   public final void stop() throws Exception {
 
     logger.info("Shutting down");
 
     // Validate state
-    if (state != STARTED) {
+    if (state != STARTED) throw new IllegalStateException("Server is not started");
 
-      throw new IllegalStateException("Server is not started");
-    }
-
-    //assert state == STARTED;
-    /*
-    if (jmdns != null) {
-      logger.info("Unregistering from ZeroConf server");
-      jmdns.unregisterAllServices();
-    }
-    */
+    // if (jmdns != null) {
+    //   logger.info("Unregistering from ZeroConf server");
+    //   jmdns.unregisterAllServices();
+    // }
     stopService();
     state = STOPPED;
     logger.info("Shut down");
@@ -460,24 +362,19 @@
 
   /**
    * Destroy the server.
-   *
    */
   public final void destroy() {
-
     logger.info("Destroying");
 
     try {
       sessionFactory.close();
+    } catch (QueryException e) {
+      logger.warn("Couldn't close server " + uri, e);
     }
-    catch (QueryException e) {
-      logger.warn("Couldn't close server "+uri, e);
-    }
 
-    /*
-    if (jmdns != null) {
-      jmdns.unregisterAllServices();
-    }
-    */
+    // if (jmdns != null) {
+    //   jmdns.unregisterAllServices();
+    // }
     sessionFactory = null;
     state = UNINITIALIZED;
     logger.info("Destroyed");
@@ -487,58 +384,75 @@
    * Set the database URI. Implementing subclasses would typically derive a URI
    * from other properties and call this method whenever those properties are
    * modified.
-   *
    * @param uri the desired server URI, or <code>null</code>
    * @throws IllegalStateException if the service is started or if the
    *      underlying session factory already has a fixed URI
    */
   protected void setURI(URI uri) {
-
     // Prevent the URI from being changed while the server is up
-    if (state == STARTED) {
-
-      throw new IllegalStateException(
-          "Can't change URI without first stopping the server");
-    }
-
-    // Reset the field
+    if (state == STARTED) throw new IllegalStateException("Can't change URI without first stopping the server");
     this.uri = uri;
   }
 
   /**
- * Retrieves the configuration used when initialising a session factory.
- *
- * @return The configuration used when initialising a session factory
- */
-public MulgaraConfig getConfig() {
+   * Retrieves the configuration used when initialising a session factory.
+   * @return The configuration used when initialising a session factory
+   */
+  public MulgaraConfig getConfig() {
+    return sessionConfig;
+  }
+  
+  /**
+   * Sets the configuration to be used when bringing up a session factory.
+   * @param config The configuration to be used when bringing up a sessionfactory
+   */
+  public void setConfig(MulgaraConfig config) {
+    // Store the new configuration item
+    sessionConfig = config;
+  }
 
-  return sessionConfig;
-}
+  /**
+   * Utility to check that the URI has the port set correctly.
+   * If the port is not specified in the URI and this server instance has a non-default port,
+   * then the URI is updated to the new port with a warning. If the port is specified and it does
+   * not match the server port, then an IllegalArgumentException is thrown.
+   * @param u The port to check.
+   * @return IllegalArgumentException If the port specified in the URI is different to the
+   *         port in use by this server.
+   */
+  protected URI updateUriPort(URI u) {
+    int port = u.getPort();
+    if (port == -1) {
+      if (portNumber != getDefaultPort()) {
+        try {
+          u = new URI(u.getScheme(), u.getUserInfo(), u.getHost(), portNumber, u.getPath(), u.getQuery(), u.getFragment());
+        } catch (URISyntaxException e) {
+          throw new IllegalArgumentException("URI has unexpected structure: " + u);
+        }
+        logger.warn("Setting server URI without configured port.  Changing to: ");
+      }
+    } else {
+      if (port != portNumber) throw new IllegalArgumentException("Server URI must match the port <" + uri +"> port:" + portNumber);
+    }
+    return u;
+  }
 
-/**
- * Sets the configuration to be used when bringing up a session factory.
- *
- * @param config The configuration to be used when bringing up a session
- *               factory
- */
-public void setConfig(MulgaraConfig config) {
+  /**
+   * Indicates the default port used by this server's protocol. This is a static final value
+   * and should correspond to the scheme in the URI (e.g. http => port 80).
+   * @return The default port for this server.
+   */
+  protected abstract int getDefaultPort();
 
-  // Store the new configuration item
-  sessionConfig = config;
-}
-
-
   /**
-   * METHOD TO DO
-   *
-   * @throws Exception EXCEPTION TO DO
+   * Start the service that this server provides.
+   * @throws Exception Indicating an error in server startup.
    */
   protected abstract void startService() throws Exception;
 
   /**
-   * METHOD TO DO
-   *
-   * @throws Exception EXCEPTION TO DO
+   * Stop the service that this server provides.
+   * @throws Exception Indicating an error in server shutdown.
    */
   protected abstract void stopService() throws Exception;
 }

Modified: trunk/src/jar/server-beep/java/org/mulgara/server/beep/BEEPServer.java
===================================================================
--- trunk/src/jar/server-beep/java/org/mulgara/server/beep/BEEPServer.java	2008-03-27 02:43:41 UTC (rev 717)
+++ trunk/src/jar/server-beep/java/org/mulgara/server/beep/BEEPServer.java	2008-03-28 03:48:15 UTC (rev 718)
@@ -40,8 +40,6 @@
 
 // Locally written packages
 import org.mulgara.server.AbstractServer;
-import org.mulgara.server.Session;
-import org.mulgara.server.SessionFactory;
 
 /**
 * Mulgara server using a BEEP-based ITQL application protocol.
@@ -49,59 +47,36 @@
 * @created 2004-03-21
 * @author <a href="http://staff.pisoftware.com/raboczi">Simon Raboczi</a>
 * @author <a href="http://staff.pisoftware.com/david">David Makepeace</a>
-* @version $Revision: 1.9 $
-* @modified $Date: 2005/01/05 04:59:00 $ by $Author: newmana $
-* @company <a href="mailto:info at PIsoftware.com">Plugged In Software</a>
-* @copyright &copy;2004 <a href="http://www.pisoftware.com/">Plugged In
-*      Software Pty Ltd</a>
+* @copyright &copy;2004 <a href="http://www.pisoftware.com/">Plugged In Software Pty Ltd</a>
 * @licence <a href="{@docRoot}/../../LICENCE">Mozilla Public License v1.1</a>
 */
-public class BEEPServer extends AbstractServer
-{
-  /**
-  * Logger.
-  */
-  private static final Logger logger =
-    Logger.getLogger(BEEPServer.class.getName());
+public class BEEPServer extends AbstractServer {
+  /** Logger. */
+  private static final Logger logger = Logger.getLogger(BEEPServer.class.getName());
 
-  /**
-  * The server port.
-  *
-  * BEEP's default port is 10288.
-  */
-  final int port = 10288;
+  /** BEEP's default port is 10288. */
+  static final int DEFAULT_PORT = 10228;
 
-  /**
-  * Socket accepting session requests from clients.
-  */
+  /** The server port. BEEP's default port is 10288. */
+  final int port = DEFAULT_PORT;
+
+  /** Socket accepting session requests from clients. */
   private ServerSocket serverSocket = null;
 
-  /**
-  * The collection of supported BEEP profiles.
-  *
-  * We add only the ITQL profile.
-  */
+  /** The collection of supported BEEP profiles. We add only the ITQL profile. */
   private ProfileRegistry profileRegistry = null;
 
   /**
-  * The thread which accepts session requests on the {@link #serverSocket}.
-  *
-  * This field is <code>null</code> whenever the server isn't {@link #STARTED}.
-  */
+   * The thread which accepts session requests on the {@link #serverSocket}.
+   * This field is <code>null</code> whenever the server isn't {@link #STARTED}.
+   */
   private Thread thread;
 
-  //
-  // Constructor
-  //
-
   /**
-  * Create a BEEP server MBean.
-  *
-  * @throws UnknownHostException  if the DNS name of the local host can't be
-  *                               determined
-  */
-  public BEEPServer() throws UnknownHostException
-  {
+   * Create a BEEP server MBean.
+   * @throws UnknownHostException if the DNS name of the local host can't be determined
+   */
+  public BEEPServer() throws UnknownHostException {
     // Generate server URI
     try {
       setURI(new URI("beep",                                    // scheme
@@ -111,8 +86,7 @@
                      null,                                      // path
                      null,                                      // query
                      null));
-    }
-    catch (URISyntaxException e) {
+    } catch (URISyntaxException e) {
       throw new Error("Bad generated URI", e);
     }
   }
@@ -122,19 +96,15 @@
   //
 
   /**
-  * Sets the hostname of the server.
-  *
-  * @param hostname  the hostname of the server; if <code>null</code>, the
-  *   local host name of the machine will be used if it can be found,
-  *   otherwise <code>localhost</code> will be used.
-  */
-  public void setHostname(String hostname)
-  {
+   * Sets the hostname of the server.
+   * @param hostname  the hostname of the server; if <code>null</code>, the
+   *   local host name of the machine will be used if it can be found,
+   *   otherwise <code>localhost</code> will be used.
+   */
+  public void setHostname(String hostname) {
     // prevent the hostname from being changed while the server is up
     if (this.getState() == STARTED) {
-      throw new IllegalStateException(
-        "Can't change hostname without first stopping the server"
-      );
+      throw new IllegalStateException("Can't change hostname without first stopping the server");
     }
 
     // get the hostname
@@ -142,8 +112,7 @@
       // try to use the local host name
       try {
         hostname = InetAddress.getLocalHost().getHostName();
-      }
-      catch (Exception e) {
+      } catch (Exception e) {
         logger.warn("Problem getting host name! - using localhost");
         hostname = "localhost";
       }
@@ -161,8 +130,7 @@
                      null,                            // path
                      null,                            // query
                      null));
-    }
-    catch (URISyntaxException e) {
+    } catch (URISyntaxException e) {
       throw new Error("Bad generated URI", e);
     }
   }
@@ -172,22 +140,18 @@
   //
 
   /**
-  * Returns the hostname of the server.
-  *
-  * @return the hostname of the server
-  */
-  public String getHostname()
-  {
+   * Returns the hostname of the server.
+   * @return the hostname of the server
+   */
+  public String getHostname() {
     return hostname;
   }
 
   /**
-  * Start the server.
-  *
-  * @throws Exception EXCEPTION TO DO
-  */
-  protected void startService() throws Exception
-  {
+   * Start the server.
+   * @throws Exception EXCEPTION TO DO
+   */
+  protected void startService() throws Exception {
     if (thread == null) {
       serverSocket = new ServerSocket(port);
 
@@ -210,28 +174,22 @@
       );
 
       // Launch the server thread
-      thread = new Thread()
-      {
-        public void run()
-        {
+      thread = new Thread() {
+        public void run() {
           try {
             while (true) {
               Socket socket = serverSocket.accept();
               TCPSession.createListener(socket, profileRegistry);
             }
-          }
-          catch (InterruptedIOException ex) {
+          } catch (InterruptedIOException ex) {
             // Stop the thread.
-          }
-          catch (Exception ex) {
+          } catch (Exception ex) {
             logger.error("Exception in ServerThread: " + ex);
-          }
-          finally {
+          } finally {
             if (serverSocket != null) {
               try {
                 serverSocket.close();
-              }
-              catch (IOException ex) {
+              } catch (IOException ex) {
                 // ignore failures
               }
             }
@@ -246,12 +204,10 @@
   }
 
   /**
-  * Stop the server.
-  *
-  * @throws Exception EXCEPTION TO DO
-  */
-  protected void stopService() throws Exception
-  {
+   * Stop the server.
+   * @throws IOException I/O error closing the server socket.
+   */
+  protected void stopService() throws IOException {
     if (thread != null) {
       thread.interrupt();
       thread          = null;
@@ -261,10 +217,17 @@
     if (serverSocket != null) {
       try {
         serverSocket.close();
-      }
-      finally {
+      } finally {
         serverSocket = null;
       }
     }
   }
+
+  /**
+   * Informs the base class what the default port for this protocol is.
+   * @see org.mulgara.server.AbstractServer#getDefaultPort()
+   */
+  protected int getDefaultPort() {
+    return DEFAULT_PORT;
+  }
 }

Modified: trunk/src/jar/server-rmi/java/org/mulgara/server/rmi/RmiServer.java
===================================================================
--- trunk/src/jar/server-rmi/java/org/mulgara/server/rmi/RmiServer.java	2008-03-27 02:43:41 UTC (rev 717)
+++ trunk/src/jar/server-rmi/java/org/mulgara/server/rmi/RmiServer.java	2008-03-28 03:48:15 UTC (rev 718)
@@ -29,8 +29,6 @@
 
 
 // Java 2 standard packages
-import java.io.*;
-import java.lang.reflect.Constructor;
 import java.net.*;
 import java.rmi.*;
 import java.rmi.server.UnicastRemoteObject;
@@ -46,54 +44,35 @@
  * Java RMI server.
  *
  * @author <a href="http://staff.pisoftware.com/raboczi">Simon Raboczi</a>
- *
  * @created 2002-01-12
- *
- * @version $Revision: 1.9 $
- *
- * @modified $Date: 2005/01/05 04:59:02 $
- *
- * @maintenanceAuthor $Author: newmana $
- *
- * @company <A href="mailto:info at PIsoftware.com">Plugged In Software</A>
- *
- * @copyright &copy; 2002-2003 <A href="http://www.PIsoftware.com/">Plugged In
- *      Software Pty Ltd</A>
- *
+ * @copyright &copy; 2002-2003 <A href="http://www.PIsoftware.com/">Plugged In Software Pty Ltd</A>
  * @licence <a href="{@docRoot}/../../LICENCE">Mozilla Public License v1.1</a>
- *
  * @see <a href="http://developer.java.sun.com/developer/JDCTechTips/2001/tt0327.html#jndi"/>
  *      <cite>JNDI lookup in distributed systems</cite> </a>
  */
 public class RmiServer extends AbstractServer implements RmiServerMBean {
 
-  /**
-   * Logger. This is named after the classname.
-   */
-  private final static Logger logger =
-    Logger.getLogger(RmiServer.class.getName());
+  /** Logger. This is named after the classname. */
+  private final static Logger logger = Logger.getLogger(RmiServer.class.getName());
 
-  /**
-   * The Java RMI registry naming context.
-   */
+  /** The default port used for RMI. */
+  public static final int DEFAULT_PORT = 1099;
+
+  /** The Java RMI registry naming context. */
   private Context rmiRegistryContext;
 
-  /**
-   * The RMI registry name of this server.
-   */
+  /** The RMI registry name of this server. */
   private String name;
 
   /**
    * The local copy of the RMI session factory. This reference must be held
    * because the garbage collector isn't aware of remote stubs on distant JVMs.
-   *
    */
   private RemoteSessionFactory remoteSessionFactory;
 
   /**
    * An RMI stub that proxies for {@link #remoteSessionFactory}. This instance
    * can be serialized and distributed to remote JVMs.
-   *
    */
   private RemoteSessionFactory exportedRemoteSessionFactory;
 
@@ -102,18 +81,13 @@
    * set <var>name</var> to <code>null</code>, but the
    * {@link org.mulgara.server.ServerMBean#start} action can't be used in that
    * case. The <var>name</var> cannot be set while the server is started.
-   *
    * @param name the new value
-   * @throws IllegalStateException if the server is started or if the database
-   *      already has a fixed URI
+   * @throws IllegalStateException if the server is started or if the database already has a fixed URI
    */
   public void setName(String name) {
-
     // Prevent the name from being changed while the server is up
     if (this.getState() == STARTED) {
-
-      throw new IllegalStateException(
-          "Can't change name without first stopping the server");
+      throw new IllegalStateException("Can't change name without first stopping the server");
     }
 
     // Set field
@@ -124,45 +98,44 @@
   /**
    * Sets the hostname of the server.
    *
-   * @param hostname the hostname of the server, if <code>null</code> <code>localhost</code>
-   *      will be used
-   * @throws IllegalStateException if the service is started or if the
-   *      underlying session factory already has a fixed hostname
+   * @param hostname the hostname of the server, if <code>null</code> <code>localhost</code> will be used
+   * @throws IllegalStateException if the service is started or if the underlying session factory already has a fixed hostname
    */
   public void setHostname(String hostname) {
-
     // Prevent the hostname from being changed while the server is up
     if (this.getState() == STARTED) {
-
-      throw new IllegalStateException(
-          "Can't change hostname without first stopping the server");
+      throw new IllegalStateException("Can't change hostname without first stopping the server");
     }
 
     // Reset the field
     if (hostname == null) {
-
       this.hostname = "localhost";
       logger.warn("Hostname supplied is null, defaulting to localhost");
-    }
-    else {
-
+    } else {
       this.hostname = hostname;
     }
 
     updateURI();
   }
 
+  /**
+   * Sets the server port.
+   * @param newPortNumber The new port to bind to.
+   */
+  public void setPortNumber(int newPortNumber) {
+    super.setPortNumber(newPortNumber);
+    updateURI();
+  }
+
   //
   // MBean properties
   //
 
   /**
    * Read the name the server is bound to in the RMI registry.
-   *
    * @return The bound name of the server.
    */
   public String getName() {
-
     return name;
   }
 
@@ -172,7 +145,6 @@
 
   /**
    * Start the server.
-   *
    * @throws IllegalStateException if <var>name</var> is <code>null</code>
    * @throws NamingException Error accessing RMI registry.
    * @throws RemoteException Error accessing RMI services.
@@ -180,19 +152,14 @@
   protected void startService() throws NamingException, RemoteException {
 
     // Validate "name" property
-    if (name == null) {
+    if (name == null) throw new IllegalStateException("Must set \"name\" property");
 
-      throw new IllegalStateException("Must set \"name\" property");
-    }
-
     // Initialize fields
     rmiRegistryContext = new InitialContext();
 
     // Apply RMI wrapper to the session factory
     remoteSessionFactory = new RemoteSessionFactoryImpl(getSessionFactory());
-    exportedRemoteSessionFactory =
-        (RemoteSessionFactory) UnicastRemoteObject.exportObject(
-        remoteSessionFactory);
+    exportedRemoteSessionFactory = (RemoteSessionFactory)UnicastRemoteObject.exportObject(remoteSessionFactory);
 
     // Bind the service to the RMI registry
     rmiRegistryContext.rebind(name, exportedRemoteSessionFactory);
@@ -200,55 +167,47 @@
 
   /**
    * Stop the server.
-   *
-   * @throws NamingException EXCEPTION TO DO
-   * @throws NoSuchObjectException EXCEPTION TO DO
+   * @throws NamingException Error accessing the registry.
+   * @throws NoSuchObjectException The current server is not registered in the registry.
    */
   protected void stopService() throws NamingException, NoSuchObjectException {
-
     rmiRegistryContext.unbind(name);
     UnicastRemoteObject.unexportObject(remoteSessionFactory, true);
   }
 
+  /**
+   * Creates a new URI for the current hostname/servicename/port and sets this service
+   * to register with that name.
+   * @throws Error if the hostname or service name cannot be encoded in a URI.
+   */
   private void updateURI() {
-
     URI newURI = null;
 
-    // A not null name means to override the default.  A null name will derive
-    // it from the RMIRegistry.
-    if (name != null) {
-
-      if (this.getHostname() == null) {
-
-        // try to use the local host name
-        try {
-
-          hostname = InetAddress.getLocalHost().getCanonicalHostName();
-        }
-        catch (Exception e) {
-
-          logger.warn("Problem getting host name! - using localhost");
-          hostname = "localhost";
-        }
+    if (hostname == null) {
+      // try to use the local host name
+      try {
+        hostname = InetAddress.getLocalHost().getCanonicalHostName();
+      } catch (Exception e) {
+        logger.warn("Problem getting host name! - using \"localhost\"");
+        hostname = "localhost";
       }
-      else {
-
-        hostname = this.getHostname();
-      }
     }
 
     // Generate new server URI
     try {
-
-      newURI = new URI("rmi", null, hostname, getPortNumber(), "/" + name, null,
-          null);
-    }
-    catch (URISyntaxException e) {
-
+      String path = "/" + (name == null ? "" : name);
+      int portValue = getPortNumber() == DEFAULT_PORT ? -1 : getPortNumber();
+      newURI = new URI("rmi", null, hostname, portValue, path, null, null);
+    } catch (URISyntaxException e) {
       throw new Error("Bad generated URI", e);
     }
 
     // Set URI.
     setURI(newURI);
   }
+  
+  /** @see org.mulgara.server.AbstractServer#getDefaultPort() */
+  protected int getDefaultPort() {
+    return DEFAULT_PORT;
+  }
 }




More information about the Mulgara-svn mailing list