User: pra     
  Date: 02/03/06 09:27:52

  Added:       src/main/org/jboss/mq/sm/file DynamicLoginModule.java
                        DynamicStateManager.java
                        DynamicStateManagerMBean.java OldStateManager.java
                        OldStateManagerMBean.java
  Log:
  Commit of JBossMQ new JAAS based security architecture
  
  Revision  Changes    Path
  1.1                  jbossmq/src/main/org/jboss/mq/sm/file/DynamicLoginModule.java
  
  Index: DynamicLoginModule.java
  ===================================================================
  /*
   * JBoss, the OpenSource J2EE webOS
   *
   * Distributable under LGPL license.
   * See terms of license at gnu.org.
   */
  package org.jboss.mq.sm.file;
  
  import java.util.Map;
  import java.util.ArrayList;
  
  import java.security.acl.Group;
  import javax.security.auth.Subject;
  import javax.security.auth.callback.CallbackHandler;
  import javax.security.auth.login.LoginException;
  
  import org.jboss.security.SimpleGroup;
  import org.jboss.security.SimplePrincipal;
  import org.jboss.security.auth.spi.UsernamePasswordLoginModule;
  /**
   * JAAS LoginModule that is backed by the DynamicStateManager.
   *
   * Must have the attribute sm.objectname set,
   * and may have the unauthenticatedIdentity set to some value.
   * @author     <a href="[EMAIL PROTECTED]">Peter Antman</a>
   * @version $Revision: 1.1 $
   */
  
  public class DynamicLoginModule   extends UsernamePasswordLoginModule{
     static final String DEFAULT_SM_NAME = "jboss.mq:service=StateManager";
     
     DynamicStateManager sm = null;
     public DynamicLoginModule() {
        
     }
     
     public void initialize(Subject subject, CallbackHandler callbackHandler, Map 
sharedState, Map options)
      {
          super.initialize(subject, callbackHandler, sharedState, options);
          try
          {
             String smName = (String) options.get("sm.objectname");
             if( smName == null )
                smName  = DEFAULT_SM_NAME;
             
             javax.management.ObjectName smObjectName = new 
javax.management.ObjectName(smName);
             
             // Lokup the state manager. FIXME
             ArrayList l = javax.management.MBeanServerFactory.findMBeanServer(null);
             if (l != null && l.size() > 0) {
                javax.management.MBeanServer server = 
                   (javax.management.MBeanServer)l.get(0);
                sm = (DynamicStateManager)server.getAttribute( smObjectName, 
"Instance");
                
                
             }
             
          }catch(Exception ex) {
             super.log.error("Failed to load DynamicSecurityManager", ex);
          }
          
      }
     
     /**
      * Check we have contact to a state manager.
      */
     public boolean login() throws LoginException
      {
          if( sm == null )
              throw new LoginException("StateManager is null");
  
          return super.login();
      }
     
  
     /** Overriden to return an empty password string as typically one cannot
      obtain a user's password. We also override the validatePassword so
      this is ok.
      @return and empty password String
      */
     protected String getUsersPassword() throws LoginException
     {
        return "";
     }
     /**
      * Validate the password againts the state manager.
      *
      * @param inputPassword the password to validate.
      * @param expectedPassword ignored
      */
     protected boolean validatePassword(String inputPassword, String expectedPassword)
     {
        boolean valid = false;
        try {
           valid =  sm.validatePassword( getUsername(), inputPassword);
        } catch(Exception ex) {
           super.log.error("Could not validate password for user "+getUsername(), ex);
        }
        return valid;
  
     }
  
     /** Overriden by subclasses to return the Groups that correspond to the
      *  to the role sets assigned to the user. Subclasses should create at
      *   least a Group named "Roles" that contains the roles assigned to the user.
      *  A second common group is "CallerPrincipal" that provides the application
      *   identity of the user rather than the security domain identity.
      *
      * Only a Roles Group is returned.
      *  @return Group[] containing the sets of roles 
     */
     protected Group[] getRoleSets() throws LoginException
     {
        SimpleGroup userRoles = new SimpleGroup("Roles");
        String[] roles = null;
        try {
           roles = sm.getRoles( getUsername() );
        }catch(Exception ex) {
           super.log.error("Could not get roleSets for user "+getUsername(), ex);
           throw new LoginException("Could not get roleSets for user");
        }
        if(roles != null) {
           for (int i =0; i < roles.length;i++) {
              userRoles.addMember(new SimplePrincipal(roles[i]));
           }
        }
  
        Group[] roleSets = {userRoles};
        return roleSets;
     }
  } // DynamicLoginModule
  
  
  
  
  
  
  1.1                  jbossmq/src/main/org/jboss/mq/sm/file/DynamicStateManager.java
  
  Index: DynamicStateManager.java
  ===================================================================
  /*
   * JBoss, the OpenSource J2EE webOS
   *
   * Distributable under LGPL license.
   * See terms of license at gnu.org.
   */
  package org.jboss.mq.sm.file;
  
  import java.io.File;
  import java.io.FileOutputStream;
  import java.io.PrintStream;
  import java.io.InputStream;
  import java.io.BufferedInputStream;
  import java.io.IOException;
  import java.net.URL;
  import java.util.ArrayList;
  import java.util.Collection;
  import java.util.Enumeration;
  
  import javax.jms.InvalidClientIDException;
  import javax.jms.JMSException;
  import javax.jms.JMSSecurityException;
  
  import org.jboss.system.server.ServerConfigImplMBean;
  import org.jboss.mq.DurableSubscriptionID;
  import org.jboss.mq.SpyTopic;
  import org.jboss.mq.SpyJMSException;
  import org.jboss.mq.xml.XElement;
  import org.jboss.mq.xml.XElementException;
  
  import org.jboss.mq.sm.StateManager;
  import org.jboss.mq.sm.AbstractStateManager;
  
  
  /**
   * A state manager that allowed durable subscriptions to be dynamically
   * created if configured to support it. Otherwise backward compatible with
   * the old StateManager.
   *
   * Backed by an XML file.
   *
   * @author     <a href="[EMAIL PROTECTED]">Norbert Lataille</a>
   * @author     <a href="[EMAIL PROTECTED]">Hiram Chirino</a>
   * @author     <a href="[EMAIL PROTECTED]">Peter Antman</a>
   * @version $Revision: 1.1 $
   */
  /*
  Example of fileformat
  <StateManager>
   <Users>
     <User>
      <Name>john</Name>
      <Password>needle</Password>
      <Id>DurableSubscriberExample</Id><!-- optional -->
     </User>
   </Users>
  
   <Roles>
    <Role name="guest">
      <UserName>john</UserName>
    </Role>
  
   </Roles>
  
   <DurableSubscriptions>
     <DurableSubscription>
       <ClientID>needle</ClientID>
       <Name>myDurableSub</Name>
       <TopicName>TestTopic...</TopicName>
     </DurableSubscription>
  
   </DurableSubscriptions>
  </StateManager>
   */
  public class DynamicStateManager  extends AbstractStateManager
                                            implements DynamicStateManagerMBean
  {
     
     class DynamicDurableSubscription extends DurableSubscription {
        XElement element;
        public  DynamicDurableSubscription(XElement element) throws XElementException{
           super(element.getField("ClientID"),
                element.getField("Name"),
                element.getField("TopicName")
                );
           this.element = element;
        }
        XElement getElement() { return element; }
        
        // Hm, I don't think we should mutate it without a sync.
        //public void setTopic(String topic) { 
        //   this.topic = topic;
        //   element.setField("Topic", topic);
        // }
        
     }
  
     /**
      * Do we have a security manager.
      *
      * By setting this to false, we may emulate the old behaviour of
      * the state manager and let it autenticate connections.
      */
     boolean hasSecurityManager = true; 
     
     XElement stateConfig = new XElement("StateManager");//So sync allways work
     private String stateFile = "conf/default/jbossmq-state.xml";
     private URL systemConfigURL;
     
     
     public DynamicStateManager() {
        
     }
     //
     // MBean methods
     //
     public StateManager getInstance()
     {
        return this;
     }
     
  
     protected void createService() throws Exception {
        // Get the system configuration URL
        systemConfigURL = (URL)
           server.getAttribute(ServerConfigImplMBean.OBJECT_NAME, "ServerConfigURL");
     }
     
     public void startService() throws Exception
     {
  
        loadConfig();
  
     }
     /**
      * Show the current configuration.
      */
     public String displayStateConfig() throws Exception
     {
        return stateConfig.toString();
     }
     /**
      * Set the name of the statefile.
      *
      * @param  newStateFile  java.lang.String
      */
     public void setStateFile(String newStateFile)
     {
        stateFile = newStateFile.trim();
     }
  
     /**
      * Get name of file.
      *
      * @return    java.lang.String
      */
     public String getStateFile()
     {
        return stateFile;
     }
  
     public boolean hasSecurityManager() {
        return hasSecurityManager;
     }
  
     public void setHasSecurityManager(boolean hasSecurityManager) {
        this.hasSecurityManager = hasSecurityManager;
     }
  
     public void loadConfig() throws IOException, XElementException
     {
        URL configURL = new URL(systemConfigURL, stateFile);
        if (log.isDebugEnabled()) {
           log.debug("Loading config from: " + configURL);
        }
        
        InputStream in = new BufferedInputStream(configURL.openStream());
        try {
           synchronized(stateConfig) {
              stateConfig = XElement.createFrom(in);
           }
        }
        finally {
           in.close();
        }
     }
  
     public void saveConfig() throws IOException
     {
        URL configURL = new URL(systemConfigURL, stateFile);
        
        if (configURL.getProtocol().equals("file")) {
           File file = new File(configURL.getFile());
           if (log.isDebugEnabled()) {
              log.debug("Saving config to: " + file);
           }
  
           PrintStream stream = new PrintStream(new FileOutputStream(file));
           try {
              synchronized(stateConfig) {
                 stream.print(stateConfig.toXML(true));
              }
           }
           finally {
              stream.close();
           }
        }
        else {
           log.error("Can not save configuration to non-file URL: " + configURL);
        }
     }
     //
     // Callback methods from AbstractStateManager
     //
     /**
      * Return preconfigured client id. Only if hasSecurityManager is false will
      * a password be required to get the clientID and will the method throw
      * a JMSSecurityException if the clientID was not found.
      */
     protected String getPreconfClientId(String login,String passwd) throws 
JMSException {
        try
        {
           synchronized (stateConfig)
           {
              
              Enumeration enum = stateConfig.getElementsNamed("Users/User");
              while (enum.hasMoreElements())
              {
                 XElement element = (XElement)enum.nextElement();
                 String name = element.getField("Name");
                 if (!name.equals(login))
                 {
                    continue;// until user is found
                 }
                 
                 // Onlyn check password if we do not have a security manager
                 if (!hasSecurityManager) {
                    String pw = element.getField("Password");
                    if (!passwd.equals(pw))
                    {
                       throw new JMSSecurityException("Bad password");
                    }
                 }
                 
                 String clientId = null;
                 if (element.containsField("Id"))
                 {
                    clientId = element.getField("Id");
                 }
  
                 //if (clientId != null)
                 return clientId;
              }
              if (!hasSecurityManager)
                 throw new JMSSecurityException("This user does not exist");
              else 
                 return null;
           }
        }
        catch (XElementException e)
        {
           log.error(e);
           throw new JMSException("Invalid server user configuration.");
        }
     }
     
     /**
      * Search for a configurated durable subscription.
      */ 
     protected DurableSubscription getDurableSubscription(DurableSubscriptionID sub) 
throws JMSException {
        boolean debug = log.isDebugEnabled();
        
        //Set the known Ids
        try {
           synchronized (stateConfig)
           {
              
              Enumeration enum = 
stateConfig.getElementsNamed("DurableSubscriptions/DurableSubscription");
              while (enum.hasMoreElements())
              {
                 
                 // Match ID
                 XElement dur = (XElement)enum.nextElement();
                 if (dur.containsField("ClientID") && 
dur.getField("ClientID").equals(sub.getClientID()))
                 {
                    // Check if this one has a DurableSubname that match
                    if (dur.getField("Name").equals(sub.getSubscriptionName())) {
                       // We have a match
                       if (debug)
                          log.debug("Found a matching ClientID configuration 
section.");
                       return new DynamicDurableSubscription(dur);
                    }
                    
                    
                 }            
              }
              // Nothing found
              return null;
           }
        }catch(XElementException e)
        {
           JMSException newE = new SpyJMSException("Could not find durable 
subscription");
           newE.setLinkedException(e);
           throw newE;
        }
     }
     
     /**
      * Check if the clientID belonges to a preconfigured user. If this
      * is the case, a  InvalidClientIDException  will be raised.
      */
     protected void checkLoggedOnClientId(String clientID) throws JMSException {
           synchronized (stateConfig)
           {
              
              Enumeration enum = stateConfig.getElementsNamed("Users/User");
              while (enum.hasMoreElements())
              {
                 XElement element = (XElement)enum.nextElement();
                 try
                 {
                    if (element.containsField("Id") && 
element.getField("Id").equals(clientID))
                    {
                       throw new InvalidClientIDException("This loggedOnClientIds is 
password protected !");
                    }
                 }
                 catch (XElementException ignore)
                 {
                 }
              }
           }
           
     }
     protected void saveDurableSubscription(DurableSubscription ds) throws 
JMSException {
        try {
           synchronized (stateConfig)
           {
              // Or logic here is simply this, if we get a DynamicDurableSubscription
              // Its reconfiguration, if not it is new
              if (ds instanceof DynamicDurableSubscription) {
                 XElement s = ((DynamicDurableSubscription)ds).getElement();
                 if (s != null) {
                    s.setField("TopicName",ds.getTopic());//In case it changed.
                 }else{
                    throw new JMSException("Can not save a null subscription");
                 }
              } else {
                 XElement dur = stateConfig.getElement("DurableSubscriptions");
                 XElement  subscription=  new XElement("DurableSubscription");
                 subscription.addField("ClientID", ds.getClientID());
                 subscription.addField("Name", ds.getName());
                 subscription.addField("TopicName", ds.getTopic());
                 dur.addElement(subscription);
              }
              saveConfig();
           }
        } catch (XElementException e)
        {
           JMSException newE = new SpyJMSException("Could not save the durable 
subscription");
            newE.setLinkedException(e);
            throw newE;
        } catch (IOException e)
        {
           JMSException newE = new SpyJMSException("Could not save the durable 
subscription");
            newE.setLinkedException(e);
            throw newE;
        }
     }
     protected void removeDurableSubscription(DurableSubscription ds) throws 
JMSException {
        try {
           // We only remove if it was our own dur sub.
           synchronized (stateConfig)
           {
              if (ds instanceof DurableSubscription) {
                 XElement s = ((DynamicDurableSubscription)ds).getElement();
                 if (s != null) {
                    s.removeFromParent();
                    saveConfig();
                 }else{
                    throw new JMSException("Can not remove a null subscription");
                 }
                 
              } else {
                 throw new JMSException("Only subscriptions of type 
DynamicDurableSubscription may be removed.");
              }
           }
        }catch (XElementException e)
        {
           JMSException newE = new SpyJMSException("Could not remove the durable 
subscription");
           newE.setLinkedException(e);
           throw newE;
        }catch (IOException e)
        {
           JMSException newE = new SpyJMSException("Could not remove the durable 
subscription");
           newE.setLinkedException(e);
           throw newE;
        }
     }
     
     public Collection getDurableSubscriptionIdsForTopic(SpyTopic topic)
        throws JMSException {
        Collection durableSubs = new ArrayList();
        try 
        {
           synchronized (stateConfig) {
              
              Enumeration enum = 
stateConfig.getElementsNamed("DurableSubscriptions/DurableSubscription");
              while (enum.hasMoreElements())
              {
                 XElement element = (XElement)enum.nextElement();
                 
                 String clientId = element.getField("ClientID");
                 String name = element.getField("Name");
                 String topicName = element.getField("TopicName");
                 if (topic.getName().equals(topicName)) 
                 {
                    durableSubs.add(new DurableSubscriptionID(clientId, name));
                 } // end of if ()
                 
              }
           }
        } 
        catch (XElementException e) 
        {
           JMSException jmse = new JMSException("Error in statemanager xml");
           jmse.setLinkedException(e);
           throw jmse;
        } // end of try-catch
        return durableSubs;
     }
  
     //
     // The methods that allow dynamic edititing of state manager.
     //
     public void addUser(String name, String password, String preconfID) throws 
Exception {
        if (findUser(name) != null)
           throw new Exception("Can not add, user exist");
        
        XElement users = stateConfig.getElement("Users");
        XElement user = new XElement("User");
        user.addField("Name",name);
        user.addField("Password",password);
        if (preconfID != null )
           user.addField("ID", preconfID);      
        users.addElement(user);
        saveConfig();
     }
  
     public void removeUser(String name) throws Exception {
        XElement user = findUser(name);
        if (user == null)
           throw new Exception("Cant remove user that does not exist");
        
        user.removeFromParent();
  
        // We should also remove the user from any roles it belonges to
        String[] roles = getRoles(name);
        if (roles != null) {
           for(int i = 0; i<roles.length;i++) {
              try {
                 removeUserFromRole(roles[i],name);
              }catch(Exception ex) { 
                 //Just move on
              }
           }
        }
  
        saveConfig();
     }
  
     public void addRole(String name) throws Exception {
        if(findRole(name)!=null)
           throw new Exception("Cant add role, it already exists");
        
        XElement roles = stateConfig.getElement("Roles");
        XElement role = new XElement("Role");
        role.setAttribute("name",name);
        roles.addElement(role);
        saveConfig();
     }
  
     public void removeRole(String name) throws Exception {
        XElement role = findRole(name);
        if (role == null)
           throw new Exception("Cant remove role that does not exist");
        
        role.removeFromParent();
        saveConfig();
     }
  
     // FIXME; no sanity check that the "real" user does exist.
     public void addUserToRole(String roleName, String user) throws Exception {
        XElement role = findRole(roleName);
        if (role == null)
           throw new Exception("Cant add to role that does not exist");
  
        if (findUser(user)==null)
           throw new Exception("Cant add user to role, user does to exist");
  
        if (findUserInRole(role,user) != null)
           throw new Exception("Cant add user to role, user already part of role");
        // FIXME; here I am not shure how XElement work
       XElement u = new XElement("UserName");
        u.setValue(user);
        role.addElement(u);
        saveConfig();      
     }
  
     public void removeUserFromRole(String roleName, String user) throws Exception {
        XElement role = findRole(roleName);
        if (role == null)
           throw new Exception("Cant remove user from role that does not exist");
  
        XElement u = findUserInRole(role,user);
        if (u == null)
           throw new Exception("Cant remove user from role, user does not exist");
        u.removeFromParent();
        saveConfig();
              
     }
  
     protected XElement findUser(String user) throws Exception{
        Enumeration enum = stateConfig.getElementsNamed("Users/User");
        while (enum.hasMoreElements())
              {
                 XElement element = (XElement)enum.nextElement();
                 if (element.getField("Name").equals(user))
                    return element;
              }
        return null;
     }
  
     protected XElement findRole(String role) throws Exception{ 
        Enumeration enum = stateConfig.getElementsNamed("Roles/Role");
        while (enum.hasMoreElements())
              {
                 XElement element = (XElement)enum.nextElement();
                 if (element.getAttribute("name").equals(role))
                    return element;
              }
        return null;
     }
     
     protected XElement findUserInRole(XElement role, String user) throws Exception{ 
        Enumeration enum = role.getElementsNamed("UserName");
        while (enum.hasMoreElements())
              {
                 XElement element = (XElement)enum.nextElement();
                 if (user.equals(element.getValue()) )
                    return element;
              }
        return null;
     }
     //
     // Methods to support LoginModule
     // 
     /**
      * We currently only support one Group type Roles. The role named
      * returned should typically be put into a Roles Group principal.
      */
     public String[] getRoles(String user) throws Exception {
        ArrayList roles = new ArrayList();
        Enumeration enum = stateConfig.getElementsNamed("Roles/Role");
        while (enum.hasMoreElements()) {
           XElement element = (XElement)enum.nextElement();
           XElement u = findUserInRole(element,user);
           if (u != null)
              roles.add( element.getAttribute("name") );
        }
        return (String[]) roles.toArray( new String[roles.size()] );
     }
     
     /**
      * Validate the user/password combination. A null inputPassword will
      * allways reurn false.
      */
     public boolean validatePassword(String user, String inputPassword) throws 
Exception {
        boolean valid = false;
        XElement u = findUser(user);
        if (u != null) {
           String pw = u.getField("Password");
           if (inputPassword != null && inputPassword.equals(pw))
              valid = true;
        }
        return valid;
     }
     
     //
     // Helper methods
     //      
  
  } // DynamicStateManager
  
  
  
  
  
  
  
  
  1.1                  
jbossmq/src/main/org/jboss/mq/sm/file/DynamicStateManagerMBean.java
  
  Index: DynamicStateManagerMBean.java
  ===================================================================
  /*
   * JBoss, the OpenSource J2EE webOS
   *
   * Distributable under LGPL license.
   * See terms of license at gnu.org.
   */
  
  package org.jboss.mq.sm.file;
  
  import java.io.IOException;
  import org.jboss.mq.xml.XElementException;
  
  import org.jboss.mq.sm.AbstractStateManagerMBean;
  
  /**
   * @author     <a href="[EMAIL PROTECTED]">Peter Antman</a>
   * @version $Revision: 1.1 $
   */
  
  public interface DynamicStateManagerMBean 
     extends AbstractStateManagerMBean
  {
     /**
      * Sets the name of the file state is stored in.
      *
      * @param newStateFile    The new StateFile value
      */
     void setStateFile(String newStateFile);
  
     /**
      * Get the name of the file state is stored in.
      *
      * @return    The StateFile value
      */
     String getStateFile();
  
     /**
      * Return a stringf representation of the statefile as it is in memmory.
      */
     String displayStateConfig() throws Exception;
  
     /**
      * Load or reload the internal state from the state file.
      */
     public void loadConfig() throws IOException, XElementException;
  
     /**
      * Save internal rep to state file.
      */
     public void saveConfig() throws IOException;
  
     public boolean hasSecurityManager();
  
     /**
      * Toggle comat mode. When set to false, it will assume no SecurityManager
      * is installed, and will therefor do autenticate when a preconf clienID
      * is accessed.
      */
     public void setHasSecurityManager(boolean hasSecurityManager);
  
     //
     // Methods to dynamically add data to the state manager
     //
     /**
      * Add a user with an optional preconfigred clientID.
      */
     public void addUser(String name, String password, String preconfID) throws 
Exception;
  
     /**
      * Remove user, and also the remove from all groups user belongs to.
      */
     public void removeUser(String name) throws Exception;
  
     /**
      * Ad a role.
      *
      * I a user that has already been autenticated is added to a role, that
      * new role for the user will not be vissable until the auth cache
      * for JassSecurityManager has refreshed itself, normaly 30 minutes.
      * To get new roles to be vissable, one may manually refresh the
      * cache through the JMX method flushAuthenticationCache("jbossmq") on
      * the JAAS security manager.
      */
     public void addRole(String role) throws Exception;
  
     /**
      * Remove a role.
      */
     public void removeRole(String role) throws Exception;
  
     /**
      * Ad a user to a role. The use must exist.
      */ 
     public void addUserToRole(String role, String user) throws Exception;
  
     /**
      * Remove user from role.
      */
     public void removeUserFromRole(String role, String user) throws Exception;
  
  } // DynamicStateManagerMBean
  
  
  
  
  1.1                  jbossmq/src/main/org/jboss/mq/sm/file/OldStateManager.java
  
  Index: OldStateManager.java
  ===================================================================
  /*
   * JBoss, the OpenSource J2EE webOS
   *
   * Distributable under LGPL license.
   * See terms of license at gnu.org.
   */
  
  package org.jboss.mq.sm.file;
  
  import java.io.File;
  import java.io.FileOutputStream;
  import java.io.PrintStream;
  import java.io.InputStream;
  import java.io.BufferedInputStream;
  import java.io.IOException;
  import java.net.URL;
  
  import java.util.ArrayList;
  import java.util.Collection;
  import java.util.Enumeration;
  import java.util.HashSet;
  import java.util.Hashtable;
  import java.util.Iterator;
  import java.util.Set;
  
  import javax.jms.InvalidClientIDException;
  import javax.jms.JMSException;
  import javax.jms.JMSSecurityException;
  import javax.naming.InitialContext;
  
  import org.jboss.mq.DurableSubscriptionID;
  import org.jboss.mq.SpyJMSException;
  import org.jboss.mq.SpyTopic;
  import org.jboss.mq.server.JMSServer;
  import org.jboss.mq.xml.XElement;
  import org.jboss.mq.xml.XElementException;
  import org.jboss.mq.sm.StateManager;
  import org.jboss.mq.server.JMSTopic;
  
  import org.jboss.system.ServiceMBeanSupport;
  import org.jboss.system.server.ServerConfigImplMBean;
  
  /**
   * This class is a simple User Manager. It handles credential issues.
   * This is the old state manager.
   * @author     Norbert Lataille ([EMAIL PROTECTED])
   * @author     <a href="[EMAIL PROTECTED]">Hiram Chirino</a>
   * @author     <a href="mailto:[EMAIL PROTECTED]";>Peter Antman</a>
   * @version    $Revision: 1.1 $
   */
  public class OldStateManager
     extends ServiceMBeanSupport
     implements StateManager, OldStateManagerMBean
  {
     XElement stateConfig;
  
     private final Set loggedOnClientIds = new HashSet();
     private String stateFile = "conf/default/jbossmq-state.xml";
     private URL systemConfigURL;
     
     /**
      *  Constructor for the StateManager object
      *
      * @exception  XElementException  Description of Exception
      */
     public OldStateManager() throws XElementException
     {
        //loggedOnClientIds = new HashSet();
     }
  
     protected void createService() throws Exception {
        // Get the system configuration URL
        systemConfigURL = (URL)
           server.getAttribute(ServerConfigImplMBean.OBJECT_NAME, "ServerConfigURL");
     }
     
     /**
      *  Insert the method's description here. Creation date: (7/10/2001 11:17:33
      *  PM)
      *
      * @param  newStateFile  java.lang.String
      */
     public void setStateFile(String newStateFile)
     {
        stateFile = newStateFile.trim();
     }
  
     public StateManager getInstance()
     {
        return this;
     }
  
     /**
      *  Sets the DurableSubscription attribute of the StateManager object
      *
      * @param  server            The new DurableSubscription value
      * @param  sub               The new DurableSubscription value
      * @param  topic             The new DurableSubscription value
      * @exception  JMSException  Description of Exception
      */
     public void setDurableSubscription(JMSServer server, DurableSubscriptionID sub, 
SpyTopic topic)
        throws JMSException
     {
        boolean debug = log.isDebugEnabled();
        if (debug)
           log.debug("Checking durable subscription: " + sub + ", on topic: " + topic);
        try
        {
           //Set the known Ids
           Enumeration enum = stateConfig.getElementsNamed("User");
           while (enum.hasMoreElements())
           {
  
              // Match the User.Name
              XElement user = (XElement)enum.nextElement();
              if (!user.containsField("Id") || 
!user.getField("Id").equals(sub.getClientID()))
              {
                 continue;
              }
  
              if (debug)
                 log.debug("Found a matching ClientID configuration section.");
  
              XElement subscription = null;
  
              // Match the User/DurableSubscription.Name
              Enumeration enum2 = user.getElementsNamed("DurableSubscription");
              while (enum2.hasMoreElements())
              {
                 XElement t = (XElement)enum2.nextElement();
                 if (t.getField("Name").equals(sub.getSubscriptionName()))
                 {
                    subscription = t;
                    break;
                 }
              }
  
              // A new subscription
              if (subscription == null)
              {
                 if (debug)
                    log.debug("The subscription was not previously registered.");
                 // it was not previously registered...
                 if (topic == null)
                 {
                    return;
                 }
  
                 JMSTopic dest = (JMSTopic)server.getJMSDestination(topic);
                 dest.createDurableSubscription(sub);
  
                 subscription = new XElement("DurableSubscription");
                 subscription.addField("Name", sub.getSubscriptionName());
                 subscription.addField("TopicName", topic.getName());
                 user.addElement(subscription);
  
                 saveConfig();
  
              }
              // An existing subscription...it was previously registered...
              // Check if it is an unsubscribe, or a change of subscription.
              else
              {
                 if (debug)
                    log.debug("The subscription was previously registered.");
                 
                 // The client wants an unsubscribe 
                 // TODO: we are not spec compliant since we neither check if
                 // the topic has an active subscriber or if there are messages
                 // destined for the client not yet acked by the session!!!
                 if (topic == null)
                 {
                    // we have to change the subscription...
                    SpyTopic prevTopic = new 
SpyTopic(subscription.getField("TopicName"));
                    JMSTopic dest = (JMSTopic)server.getJMSDestination(prevTopic);
                    // TODO here we should check if  the client still has 
                    // an active consumer
  
                    dest.destroyDurableSubscription(sub);
  
                    //straight deletion, remove subscription
                    subscription.removeFromParent();
                    saveConfig();
                 }
                 // The topic previously subscribed to is not the same as the
                 // one in the subscription request.
                 // TODO: we do currently no check if the selector has changed.
                 else if (!subscription.getField("TopicName").equals(topic.getName()))
                 {
                    //new topic so we have to change it
                    if (debug)
                       log.debug("But the topic was different, changing the 
subscription.");
                    // we have to change the subscription...
                    SpyTopic prevTopic = new 
SpyTopic(subscription.getField("TopicName"));
                    JMSTopic dest = (JMSTopic)server.getJMSDestination(prevTopic);
                    dest.destroyDurableSubscription(sub);
  
                    dest = (JMSTopic)server.getJMSDestination(topic);
                    dest.createDurableSubscription(sub);
  
                    //durable subscription has new topic
                    subscription.setField("TopicName", topic.getName());
                    saveConfig();
                 }
              }
              return;
           }
  
           // Could not find that user..
           throw new JMSException("ClientID '" + sub.getClientID() +
                                  "' cannot create durable subscriptions.");
        }
        catch (IOException e)
        {
           JMSException newE = new SpyJMSException("Could not setup the durable 
subscription");
           newE.setLinkedException(e);
           throw newE;
        }
        catch (XElementException e)
        {
           JMSException newE = new SpyJMSException("Could not setup the durable 
subscription");
           newE.setLinkedException(e);
           throw newE;
        }
  
     }
     
     /**
      * Get the destination a subscription is for.
      */
     public SpyTopic getDurableTopic(DurableSubscriptionID sub) throws JMSException
     {
        try {
           XElement subscription = getSubscription(sub);
           if (subscription == null)
              throw new JMSException("No durable subscription found for subscription: 
" + sub.getSubscriptionName());
           
           return new SpyTopic(subscription.getField("TopicName"));
        }catch(XElementException e)
        {
           JMSException newE = new SpyJMSException("Could not find durable 
subscription");
           newE.setLinkedException(e);
           throw newE;
        }
     }
     
     private XElement getSubscription(DurableSubscriptionID sub) throws 
JMSException,XElementException {
        boolean debug = log.isDebugEnabled();
  
        //Set the known Ids
        XElement subscription = null;
        Enumeration enum = stateConfig.getElementsNamed("User");
        while (enum.hasMoreElements())
        {
              
           // Match the User.Name
           XElement user = (XElement)enum.nextElement();
           if (!user.containsField("Id") || 
!user.getField("Id").equals(sub.getClientID()))
           {
              continue;
           }
  
           if (debug)
              log.debug("Found a matching ClientID configuration section.");
  
           //XElement subscription = null;
  
           // Match the User/DurableSubscription.Name
           Enumeration enum2 = user.getElementsNamed("DurableSubscription");
           while (enum2.hasMoreElements())
           {
              XElement t = (XElement)enum2.nextElement();
              if (t.getField("Name").equals(sub.getSubscriptionName()))
              {
                 subscription = t;
                 //break;
                 return subscription;
              }
           }
        }
        // Nothing found  will be null
        return subscription;
     }
  
     /**
      *  Insert the method's description here. Creation date: (7/10/2001 11:17:33
      *  PM)
      *
      * @return    java.lang.String
      */
     public String getStateFile()
     {
        return stateFile;
     }
  
     /**
      *  #Description of the Method
      *
      * @param  login             Description of Parameter
      * @param  passwd            Description of Parameter
      * @return                   Description of the Returned Value
      * @exception  JMSException  Description of Exception
      */
     public String checkUser(String login, String passwd) throws JMSException
     {
        try
        {
           synchronized (stateConfig)
           {
  
              Enumeration enum = stateConfig.getElementsNamed("User");
              while (enum.hasMoreElements())
              {
                 XElement element = (XElement)enum.nextElement();
                 String name = element.getField("Name");
                 if (!name.equals(login))
                 {
                    continue;
                 }
  
                 String pw = element.getField("Password");
                 if (!passwd.equals(pw))
                 {
                    throw new JMSException("Bad password");
                 }
  
                 String clientId = null;
                 if (element.containsField("Id"))
                 {
                    clientId = element.getField("Id");
                 }
  
                 if (clientId != null)
                 {
                    synchronized (loggedOnClientIds)
                    {
                       if (loggedOnClientIds.contains(clientId))
                       {
                          throw new JMSSecurityException
                             ("The login id has an assigned client id. " +
                              "That client id is already connected to the server!");
                       }
                       loggedOnClientIds.add(clientId);
                    }
                 }
  
                 return clientId;
              }
              throw new JMSSecurityException("This user does not exist");
           }
        }
        catch (XElementException e)
        {
           log.error(e);
           throw new JMSException("Invalid server user configuration.");
        }
     }
  
     /**
      *  Ad a logged in clientID to the statemanager.
      *
      * The clientID must not be active, and it must not be password protected.
      *
      * @param  ID                The feature to be added to the LoggedOnClientId
      *                           attribute
      * @exception  JMSException  Description of Exception
      */
     public void addLoggedOnClientId(String ID) throws JMSException
     {
  
        //Check : this ID must not be registered
        synchronized (loggedOnClientIds)
        {
           if (loggedOnClientIds.contains(ID))
           {
              throw new InvalidClientIDException("This loggedOnClientIds is already 
registered !");
           }
        }
  
        //Check : this ID must not be password protected
        synchronized (stateConfig)
        {
           Enumeration enum = stateConfig.getElementsNamed("User");
           while (enum.hasMoreElements())
           {
              XElement element = (XElement)enum.nextElement();
              try
              {
                 if (element.containsField("Id") && element.getField("Id").equals(ID))
                 {
                    throw new InvalidClientIDException("This loggedOnClientIds is 
password protected !");
                 }
              }
              catch (XElementException ignore)
              {
              }
           }
  
        }
        synchronized (loggedOnClientIds)
        {
           loggedOnClientIds.add(ID);
        }
     }
  
     /**
      *  #Description of the Method
      *
      * @param  ID  Description of Parameter
      */
     public void removeLoggedOnClientId(String ID)
     {
        synchronized (loggedOnClientIds)
        {
           loggedOnClientIds.remove(ID);
        }
     }
  
     /**
      *  #Description of the Method
      *
      * @exception  Exception  Description of Exception
      */
     public void startService() throws Exception
     {
  
        loadConfig();
  
        /*JMSServer server = (JMSServer)getServer().invoke(new 
ObjectName(org.jboss.mq.server.JBossMQServiceMBean.OBJECT_NAME), "getJMSServer", new 
Object[]{
          }, new String[]{
          });*/
        //server.setStateManager(this);
        //initDurableSubscriptions(server);
  
     }
  
     public Collection getDurableSubscriptionIdsForTopic(SpyTopic topic)
        throws JMSException
     {
        Collection durableSubs = new ArrayList();
        try 
        {
           Enumeration enum = stateConfig.getElementsNamed("User/DurableSubscription");
           while (enum.hasMoreElements())
           {
              XElement element = (XElement)enum.nextElement();
  
              String clientId = element.getField("../Id");
              String name = element.getField("Name");
              String topicName = element.getField("TopicName");
              if (topic.getName().equals(topicName)) 
              {
                 durableSubs.add(new DurableSubscriptionID(clientId, name));
              } // end of if ()
              
           }
        } 
        catch (XElementException e) 
        {
           JMSException jmse = new JMSException("Error in statemanager xml");
           jmse.setLinkedException(e);
           throw jmse;
        } // end of try-catch
        return durableSubs;
     }
     
     /**
      *  #Description of the Method
      *
      * @param  server                                  Description of Parameter
      * @exception  XElementException  Description of Exception
      */
     /*
       public void initDurableSubscriptions(JMSServer server) throws XElementException
       {
  
       //Set the known Ids
       Enumeration enum = stateConfig.getElementsNamed("User/DurableSubscription");
       while (enum.hasMoreElements())
       {
       XElement element = (XElement)enum.nextElement();
  
       String clientId = element.getField("../Id");
       String name = element.getField("Name");
       String topicName = element.getField("TopicName");
  
       try
       {
  
       log.debug("Restarting Durable Subscription: " + clientId + "," + name + "," + 
topicName);
       SpyTopic topic = new SpyTopic(topicName);
       JMSTopic dest = (JMSTopic)server.getJMSDestination(topic);
       if (dest == null)
       {
       log.warn("Subscription topic of not found: " + topicName);
       log.warn("Subscription cannot be initialized: " + clientId + "," + name);
       element.removeFromParent();
       }
       else
       {
       dest.createDurableSubscription(new DurableSubscriptionID(clientId, name));
       }
  
       }
       catch (JMSException e)
       {
       log.error("Could not initialize a durable subscription for : Client Id=" + 
clientId + ", Name=" + name + ", Topic Name=" + topicName, e);
       }
       }
  
       }
     */
     
     public void loadConfig() throws IOException, XElementException
     {
        URL configURL = new URL(systemConfigURL, stateFile);
        if (log.isDebugEnabled()) {
           log.debug("Loading config from: " + configURL);
        }
        
        InputStream in = new BufferedInputStream(configURL.openStream());
        try {
           stateConfig = XElement.createFrom(in);
        }
        finally {
           in.close();
        }
     }
  
     public void saveConfig() throws IOException
     {
        URL configURL = new URL(systemConfigURL, stateFile);
        
        if (configURL.getProtocol().equals("file")) {
           File file = new File(configURL.getFile());
           if (log.isDebugEnabled()) {
              log.debug("Saving config to: " + file);
           }
  
           PrintStream stream = new PrintStream(new FileOutputStream(file));
           try {
              stream.print(stateConfig.toXML(true));
           }
           finally {
              stream.close();
           }
        }
        else {
           log.error("Can not save configuration to non-file URL: " + configURL);
        }
     }
  
     public String displayStateConfig() throws Exception
     {
        return stateConfig.toString();
     }
     /*
       Does not seem to be used
     public class Identity
     {
        String login;
        String passwd;
        String loggedOnClientIds;
  
        Identity(final String login,
                 final String passwd,
                 final String loggedOnClientIds)
        {
           this.login = login;
           this.passwd = passwd;
           this.loggedOnClientIds = loggedOnClientIds;
        }
  
     }
     */
  }
  
  
  
  1.1                  jbossmq/src/main/org/jboss/mq/sm/file/OldStateManagerMBean.java
  
  Index: OldStateManagerMBean.java
  ===================================================================
  /*
   * JBoss, the OpenSource J2EE webOS
   *
   * Distributable under LGPL license.
   * See terms of license at gnu.org.
   */
  package org.jboss.mq.sm.file;
  
  import org.jboss.mq.sm.StateManager;
  import org.jboss.system.ServiceMBean;
  
  /**
   * MBean interface for the JBossMQ JMX service.
   *
   * @author     <a href="[EMAIL PROTECTED]">Hiram Chirino</a>
   * @version    $Revision: 1.1 $
   */
  public interface OldStateManagerMBean
     extends ServiceMBean
  {
     /**
      * Gets the StateFile attribute of the StateManagerMBean object
      *
      * @return    The StateFile value
      */
     String getStateFile();
  
     /**
      * Sets the StateFile attribute of the StateManagerMBean object
      *
      * @param newStateFile    The new StateFile value
      */
     void setStateFile(String newStateFile);
  
     StateManager getInstance();
  
     String displayStateConfig() throws Exception;
  }
  
  
  

_______________________________________________
Jboss-development mailing list
[EMAIL PROTECTED]
https://lists.sourceforge.net/lists/listinfo/jboss-development

Reply via email to