Exemplo n.º 1
1
 protected void unregister(Http11Processor processor) {
   if (proto.getDomain() != null) {
     synchronized (this) {
       try {
         RequestInfo rp = processor.getRequest().getRequestProcessor();
         rp.setGlobalProcessor(null);
         ObjectName rpName = rp.getRpName();
         if (log.isDebugEnabled()) {
           log.debug("Unregister " + rpName);
         }
         Registry.getRegistry(null, null).unregisterComponent(rpName);
         rp.setRpName(null);
       } catch (Exception e) {
         log.warn("Error unregistering request", e);
       }
     }
   }
 }
Exemplo n.º 2
0
  /**
   * Invoke a pre-startup initialization. This is used to allow connectors to bind to restricted
   * ports under Unix operating environments.
   */
  public void initialize() throws LifecycleException {
    if (initialized) {
      log.info(sm.getString("standardServer.initialize.initialized"));
      return;
    }
    lifecycle.fireLifecycleEvent(INIT_EVENT, null);
    initialized = true;

    if (oname == null) {
      try {
        oname = new ObjectName("Catalina:type=Server");
        Registry.getRegistry(null, null).registerComponent(this, oname, null);
      } catch (Exception e) {
        log.error("Error registering ", e);
      }
    }

    // Register global String cache
    try {
      ObjectName oname2 = new ObjectName(oname.getDomain() + ":type=StringCache");
      Registry.getRegistry(null, null).registerComponent(new StringCache(), oname2, null);
    } catch (Exception e) {
      log.error("Error registering ", e);
    }

    // Initialize our defined Services
    for (int i = 0; i < services.length; i++) {
      services[i].initialize();
    }
  }
  public void execute() throws Exception {
    if (registry == null) registry = Registry.getRegistry(null, null);
    long t1 = System.currentTimeMillis();
    try {
      InputStream stream = null;
      if (source instanceof URL) {
        stream = ((URL) source).openStream();
      }
      if (source instanceof InputStream) {
        stream = (InputStream) source;
      }
      if (stream == null) {
        throw new Exception("Can't process " + source);
      }
      ObjectInputStream ois = new ObjectInputStream(stream);
      Thread.currentThread().setContextClassLoader(ManagedBean.class.getClassLoader());
      Object obj = ois.readObject();
      // log.info("Reading " + obj);
      ManagedBean beans[] = (ManagedBean[]) obj;
      // after all are read without error
      for (int i = 0; i < beans.length; i++) {
        registry.addManagedBean(beans[i]);
      }

    } catch (Exception ex) {
      log.error("Error reading descriptors " + source + " " + ex.toString(), ex);
      throw ex;
    }
    long t2 = System.currentTimeMillis();
    log.info("Reading descriptors ( ser ) " + (t2 - t1));
  }
Exemplo n.º 4
0
  public void stop() {
    // Clean up the handlers
    MBeanServer s = Registry.getRegistry(null, null).getMBeanServer();
    for (int i = 0; i < wEnv.getHandlerCount(); i++) {
      JkHandler handler = wEnv.getHandler(i);
      if (handler != null) {
        String handlerName = handler.getName();
        try {
          handler.destroy();
        } catch (IOException ex) {
          log.error("Error stopping " + handlerName, ex);
        }
        if (domain != null) {
          try {
            ObjectName handlerOname =
                new ObjectName(this.domain + ":" + "type=JkHandler,name=" + handlerName);
            if (s.isRegistered(handlerOname)) {
              s.unregisterMBean(handlerOname);
            }
          } catch (Exception e) {
            log.error("Error unregistering " + handlerName, e);
          }
        }
      }
    }

    started = false;

    // De-register JMX for Env
    if (domain != null) {
      try {
        ObjectName wEnvName = new ObjectName(domain + ":type=JkWorkerEnv");
        if (s.isRegistered(wEnvName)) {
          s.unregisterMBean(wEnvName);
        }
      } catch (Exception e) {
        log.error("Error unregistering JkWorkerEnv", e);
      }
    }

    // De-register JMX for JkMain
    if (oname != null) {
      if (s.isRegistered(oname)) {
        try {
          Registry.getRegistry(null, null).unregisterComponent(oname);
        } catch (Exception e) {
          log.error("Error unregistering jkmain " + e);
        }
      }
    }
  }
Exemplo n.º 5
0
 private JkHandler newHandler(String type, String localName, String fullName) {
   JkHandler handler;
   String classN = modules.getProperty(type);
   if (classN == null) {
     log.error("No class name for " + fullName + " " + type);
     return null;
   }
   try {
     Class channelclass = Class.forName(classN);
     handler = (JkHandler) channelclass.newInstance();
   } catch (Throwable ex) {
     handler = null;
     log.error("Can't create " + fullName, ex);
     return null;
   }
   if (this.domain != null) {
     try {
       ObjectName handlerOname =
           new ObjectName(this.domain + ":" + "type=JkHandler,name=" + fullName);
       Registry.getRegistry(null, null).registerComponent(handler, handlerOname, classN);
     } catch (Exception e) {
       log.error("Error registering " + fullName, e);
     }
   }
   wEnv.addHandler(fullName, handler);
   return handler;
 }
Exemplo n.º 6
0
 public void destroy() {
   if (org.apache.tomcat.util.Constants.ENABLE_MODELER) {
     if (oname != null) Registry.getRegistry(null, null).unregisterComponent(oname);
   }
   initialized = false;
   oname = null;
 }
Exemplo n.º 7
0
  public void init() {
    if (initialized) return;
    initialized = true;

    StandardContext ctx = (StandardContext) this.getContainer();
    distributable = ctx.getDistributable();
    if (org.apache.tomcat.util.Constants.ENABLE_MODELER) {
      if (oname == null) {
        try {
          Engine eng = (Engine) ctx.getParent().getParent();
          domain = ctx.getEngineName();
          StandardHost hst = (StandardHost) ctx.getParent();
          String path = ctx.getPath();
          if (path.equals("")) {
            path = "/";
          }
          oname = new ObjectName(domain + ":type=Manager,path=" + path + ",host=" + hst.getName());
          Registry.getRegistry(null, null).registerComponent(this, oname, null);
        } catch (Exception e) {
          CatalinaLogger.SESSION_LOGGER.failedSessionManagerJmxRegistration(oname, e);
        }
      }
    }

    if (CatalinaLogger.SESSION_LOGGER.isDebugEnabled())
      CatalinaLogger.SESSION_LOGGER.debug("Registering " + oname);
  }
Exemplo n.º 8
0
  public void init() {
    if (initialized) return;
    initialized = true;

    log = Logger.getLogger(ManagerBase.class);

    StandardContext ctx = (StandardContext) this.getContainer();
    distributable = ctx.getDistributable();
    if (org.apache.tomcat.util.Constants.ENABLE_MODELER) {
      if (oname == null) {
        try {
          Engine eng = (Engine) ctx.getParent().getParent();
          domain = ctx.getEngineName();
          StandardHost hst = (StandardHost) ctx.getParent();
          String path = ctx.getPath();
          if (path.equals("")) {
            path = "/";
          }
          oname = new ObjectName(domain + ":type=Manager,path=" + path + ",host=" + hst.getName());
          Registry.getRegistry(null, null).registerComponent(this, oname, null);
        } catch (Exception e) {
          log.error("Error registering ", e);
        }
      }
    }

    if (log.isDebugEnabled()) log.debug("Registering " + oname);
  }
Exemplo n.º 9
0
 protected void register(Http11Processor processor) {
   if (proto.getDomain() != null) {
     synchronized (this) {
       try {
         long count = registerCount.incrementAndGet();
         RequestInfo rp = processor.getRequest().getRequestProcessor();
         rp.setGlobalProcessor(global);
         ObjectName rpName =
             new ObjectName(
                 proto.getDomain()
                     + ":type=RequestProcessor,worker="
                     + proto.getName()
                     + ",name=HttpRequest"
                     + count);
         if (log.isDebugEnabled()) {
           log.debug("Register " + rpName);
         }
         Registry.getRegistry(null, null).registerComponent(rp, rpName, null);
         rp.setRpName(rpName);
       } catch (Exception e) {
         log.warn("Error registering request");
       }
     }
   }
 }
Exemplo n.º 10
0
/**
 * A <strong>ModelMBean</strong> implementation for the <code>org.apache.catalina.Role</code>
 * component.
 *
 * @author Craig R. McClanahan
 */
public class RoleMBean extends BaseModelMBean {

  // ----------------------------------------------------------- Constructors

  /**
   * Construct a <code>ModelMBean</code> with default <code>ModelMBeanInfo</code> information.
   *
   * @exception MBeanException if the initializer of an object throws an exception
   * @exception RuntimeOperationsException if an IllegalArgumentException occurs
   */
  public RoleMBean() throws MBeanException, RuntimeOperationsException {

    super();
  }

  // ----------------------------------------------------- Instance Variables

  /** The configuration information registry for our managed beans. */
  protected Registry registry = MBeanUtils.createRegistry();

  /** The <code>MBeanServer</code> in which we are registered. */
  protected MBeanServer mserver = MBeanUtils.createServer();

  /** The <code>ManagedBean</code> information describing this MBean. */
  protected ManagedBean managed = registry.findManagedBean("Role");

  // ------------------------------------------------------------- Attributes

  // ------------------------------------------------------------- Operations

}
Exemplo n.º 11
0
  @Override
  public void destroy() {
    if (getLog().isInfoEnabled()) {
      getLog().info(sm.getString("abstractProtocolHandler.destroy", getName()));
    }
    try {
      endpoint.destroy();
    } catch (Exception e) {
      getLog().error(sm.getString("abstractProtocolHandler.destroyError", getName()), e);
    }

    if (oname != null) {
      Registry.getRegistry(null, null).unregisterComponent(oname);
    }

    if (tpOname != null) Registry.getRegistry(null, null).unregisterComponent(tpOname);
    if (rgOname != null) Registry.getRegistry(null, null).unregisterComponent(rgOname);
  }
Exemplo n.º 12
0
  public void start() throws Exception {
    if (this.domain != null) {
      try {
        tpOname = new ObjectName(domain + ":" + "type=ThreadPool,name=" + getName());
        Registry.getRegistry(null, null).registerComponent(endpoint, tpOname, null);
      } catch (Exception e) {
        log.error("Can't register endpoint");
      }
      rgOname = new ObjectName(domain + ":type=GlobalRequestProcessor,name=" + getName());
      Registry.getRegistry(null, null).registerComponent(cHandler.global, rgOname, null);
    }

    try {
      endpoint.start();
    } catch (Exception ex) {
      log.error(sm.getString("http11protocol.endpoint.starterror"), ex);
      throw ex;
    }
    if (log.isInfoEnabled()) log.info(sm.getString("http11protocol.start", getName()));
  }
  /**
   * Set the specified resources in the naming context.
   *
   * @param name the name of the resource which should be removed
   */
  public void removeResource(String name) {

    try {
      envCtx.unbind(name);
    } catch (NamingException e) {
      logger.error(sm.getString("naming.unbindFailed", e));
    }

    ObjectName on = objectNames.get(name);
    if (on != null) {
      Registry.getRegistry(null, null).unregisterComponent(on);
    }
  }
Exemplo n.º 14
0
  /** Process a "start" event for this Host. */
  public void start() {

    if (log.isDebugEnabled()) log.debug(sm.getString("hostConfig.start"));

    try {
      ObjectName hostON = new ObjectName(host.getObjectName());
      oname = new ObjectName(hostON.getDomain() + ":type=Deployer,host=" + host.getName());
      Registry.getRegistry(null, null).registerComponent(this, oname, this.getClass().getName());
    } catch (Exception e) {
      log.error(sm.getString("hostConfig.jmx.register", oname), e);
    }

    if (host.getDeployOnStartup()) deployApps();
  }
Exemplo n.º 15
0
  @Override
  public void init() throws Exception {
    if (getLog().isInfoEnabled())
      getLog().info(sm.getString("abstractProtocolHandler.init", getName()));

    if (oname == null) {
      // Component not pre-registered so register it
      oname = createObjectName();
      if (oname != null) {
        Registry.getRegistry(null, null).registerComponent(this, oname, null);
      }
    }

    if (this.domain != null) {
      try {
        tpOname = new ObjectName(domain + ":" + "type=ThreadPool,name=" + getName());
        Registry.getRegistry(null, null).registerComponent(endpoint, tpOname, null);
      } catch (Exception e) {
        getLog()
            .error(
                sm.getString("abstractProtocolHandler.mbeanRegistrationFailed", tpOname, getName()),
                e);
      }
      rgOname = new ObjectName(domain + ":type=GlobalRequestProcessor,name=" + getName());
      Registry.getRegistry(null, null).registerComponent(getHandler().getGlobal(), rgOname, null);
    }

    String endpointName = getName();
    endpoint.setName(endpointName.substring(1, endpointName.length() - 1));

    try {
      endpoint.init();
    } catch (Exception ex) {
      getLog().error(sm.getString("abstractProtocolHandler.initError", getName()), ex);
      throw ex;
    }
  }
Exemplo n.º 16
0
 public void start() {
   try {
     if (oname != null && getJkMain().getDomain() == null) {
       try {
         ObjectName jkmainOname = new ObjectName(oname.getDomain() + ":type=JkMain");
         Registry.getRegistry(null, null).registerComponent(getJkMain(), jkmainOname, "JkMain");
       } catch (Exception e) {
         log.error("Error registering jkmain " + e);
       }
     }
     getJkMain().start();
   } catch (Exception ex) {
     log.error("Error during startup", ex);
   }
 }
Exemplo n.º 17
0
  /** Process a "stop" event for this Host. */
  public void stop() {

    if (log.isDebugEnabled()) log.debug(sm.getString("hostConfig.stop"));

    undeployApps();

    if (oname != null) {
      try {
        Registry.getRegistry(null, null).unregisterComponent(oname);
      } catch (Exception e) {
        log.error(sm.getString("hostConfig.jmx.unregister", oname), e);
      }
    }
    oname = null;
    appBase = null;
    configBase = null;
  }
 private void unregisterJMX() {
   // unregister this component
   if (oname != null) {
     try {
       Registry.getRegistry(null, null).unregisterComponent(oname);
       if (log.isDebugEnabled())
         log.debug(
             sm.getString(
                 "applicationFilterConfig.jmxUnregister", getFilterClass(), getFilterName()));
     } catch (Exception ex) {
       log.error(
           sm.getString(
               "applicationFilterConfig.jmxUnregisterFail", getFilterClass(), getFilterName()),
           ex);
     }
   }
 }
  private void registerJMX() {
    String parentName = context.getName();
    if (!parentName.startsWith("/")) {
      parentName = "/" + parentName;
    }

    String hostName = context.getParent().getName();
    hostName = (hostName == null) ? "DEFAULT" : hostName;

    // domain == engine name
    String domain = context.getParent().getParent().getName();

    String webMod = "//" + hostName + parentName;
    String onameStr = null;
    String filterName = filterDef.getFilterName();
    if (Util.objectNameValueNeedsQuote(filterName)) {
      filterName = ObjectName.quote(filterName);
    }
    if (context instanceof StandardContext) {
      StandardContext standardContext = (StandardContext) context;
      onameStr =
          domain
              + ":j2eeType=Filter,WebModule="
              + webMod
              + ",name="
              + filterName
              + ",J2EEApplication="
              + standardContext.getJ2EEApplication()
              + ",J2EEServer="
              + standardContext.getJ2EEServer();
    } else {
      onameStr = domain + ":j2eeType=Filter,name=" + filterName + ",WebModule=" + webMod;
    }
    try {
      oname = new ObjectName(onameStr);
      Registry.getRegistry(null, null).registerComponent(this, oname, null);
    } catch (Exception ex) {
      log.info(
          sm.getString(
              "applicationFilterConfig.jmxRegisterFail", getFilterClass(), getFilterName()),
          ex);
    }
  }
  /**
   * Set the specified resources in the naming context.
   *
   * @param resource the resource descriptor
   */
  public void addResource(ContextResource resource) {

    // Create a reference to the resource.
    Reference ref =
        new ResourceRef(
            resource.getType(),
            resource.getDescription(),
            resource.getScope(),
            resource.getAuth(),
            resource.getSingleton());
    // Adding the additional parameters, if any
    Iterator<String> params = resource.listProperties();
    while (params.hasNext()) {
      String paramName = params.next();
      String paramValue = (String) resource.getProperty(paramName);
      StringRefAddr refAddr = new StringRefAddr(paramName, paramValue);
      ref.add(refAddr);
    }
    try {
      if (logger.isDebugEnabled()) {
        logger.debug("  Adding resource ref " + resource.getName() + "  " + ref);
      }
      createSubcontexts(envCtx, resource.getName());
      envCtx.bind(resource.getName(), ref);
    } catch (NamingException e) {
      logger.error(sm.getString("naming.bindFailed", e));
    }

    if ("javax.sql.DataSource".equals(ref.getClassName()) && resource.getSingleton()) {
      try {
        ObjectName on = createObjectName(resource);
        Object actualResource = envCtx.lookup(resource.getName());
        Registry.getRegistry(null, null).registerComponent(actualResource, on, null);
        objectNames.put(resource.getName(), on);
      } catch (Exception e) {
        logger.warn(sm.getString("naming.jmxRegistrationFailed", e));
      }
    }
  }
Exemplo n.º 21
0
 protected void unregister(Processor<S> processor) {
   if (getProtocol().getDomain() != null) {
     synchronized (this) {
       try {
         Request r = processor.getRequest();
         if (r == null) {
           // Probably an UpgradeProcessor
           return;
         }
         RequestInfo rp = r.getRequestProcessor();
         rp.setGlobalProcessor(null);
         ObjectName rpName = rp.getRpName();
         if (getLog().isDebugEnabled()) {
           getLog().debug("Unregister " + rpName);
         }
         Registry.getRegistry(null, null).unregisterComponent(rpName);
         rp.setRpName(null);
       } catch (Exception e) {
         getLog().warn("Error unregistering request", e);
       }
     }
   }
 }
/**
 * A <strong>ModelMBean</strong> implementation for the <code>
 * org.apache.catalina.users.MemoryUserDatabase</code> component.
 *
 * @author Craig R. McClanahan
 */
public class MemoryUserDatabaseMBean extends BaseModelMBean {

  // ----------------------------------------------------------- Constructors

  /**
   * Construct a <code>ModelMBean</code> with default <code>ModelMBeanInfo</code> information.
   *
   * @exception MBeanException if the initializer of an object throws an exception
   * @exception RuntimeOperationsException if an IllegalArgumentException occurs
   */
  public MemoryUserDatabaseMBean() throws MBeanException, RuntimeOperationsException {

    super();
  }

  // ----------------------------------------------------- Instance Variables

  /** The configuration information registry for our managed beans. */
  protected Registry registry = MBeanUtils.createRegistry();

  /** The <code>ManagedBean</code> information describing this MBean. */
  protected ManagedBean managed = registry.findManagedBean("MemoryUserDatabase");

  /** The <code>ManagedBean</code> information describing Group MBeans. */
  protected ManagedBean managedGroup = registry.findManagedBean("Group");

  /** The <code>ManagedBean</code> information describing Group MBeans. */
  protected ManagedBean managedRole = registry.findManagedBean("Role");

  /** The <code>ManagedBean</code> information describing User MBeans. */
  protected ManagedBean managedUser = registry.findManagedBean("User");

  // ------------------------------------------------------------- Attributes

  /** Return the MBean Names of all groups defined in this database. */
  public String[] getGroups() {

    UserDatabase database = (UserDatabase) this.resource;
    ArrayList<String> results = new ArrayList<String>();
    Iterator<Group> groups = database.getGroups();
    while (groups.hasNext()) {
      Group group = groups.next();
      results.add(findGroup(group.getGroupname()));
    }
    return results.toArray(new String[results.size()]);
  }

  /** Return the MBean Names of all roles defined in this database. */
  public String[] getRoles() {

    UserDatabase database = (UserDatabase) this.resource;
    ArrayList<String> results = new ArrayList<String>();
    Iterator<Role> roles = database.getRoles();
    while (roles.hasNext()) {
      Role role = roles.next();
      results.add(findRole(role.getRolename()));
    }
    return results.toArray(new String[results.size()]);
  }

  /** Return the MBean Names of all users defined in this database. */
  public String[] getUsers() {

    UserDatabase database = (UserDatabase) this.resource;
    ArrayList<String> results = new ArrayList<String>();
    Iterator<User> users = database.getUsers();
    while (users.hasNext()) {
      User user = users.next();
      results.add(findUser(user.getUsername()));
    }
    return results.toArray(new String[results.size()]);
  }

  // ------------------------------------------------------------- Operations

  /**
   * Create a new Group and return the corresponding MBean Name.
   *
   * @param groupname Group name of the new group
   * @param description Description of the new group
   */
  public String createGroup(String groupname, String description) {

    UserDatabase database = (UserDatabase) this.resource;
    Group group = database.createGroup(groupname, description);
    try {
      MBeanUtils.createMBean(group);
    } catch (Exception e) {
      IllegalArgumentException iae =
          new IllegalArgumentException("Exception creating group [" + groupname + "] MBean");
      iae.initCause(e);
      throw iae;
    }
    return (findGroup(groupname));
  }

  /**
   * Create a new Role and return the corresponding MBean Name.
   *
   * @param rolename Group name of the new group
   * @param description Description of the new group
   */
  public String createRole(String rolename, String description) {

    UserDatabase database = (UserDatabase) this.resource;
    Role role = database.createRole(rolename, description);
    try {
      MBeanUtils.createMBean(role);
    } catch (Exception e) {
      IllegalArgumentException iae =
          new IllegalArgumentException("Exception creating role [" + rolename + "] MBean");
      iae.initCause(e);
      throw iae;
    }
    return (findRole(rolename));
  }

  /**
   * Create a new User and return the corresponding MBean Name.
   *
   * @param username User name of the new user
   * @param password Password for the new user
   * @param fullName Full name for the new user
   */
  public String createUser(String username, String password, String fullName) {

    UserDatabase database = (UserDatabase) this.resource;
    User user = database.createUser(username, password, fullName);
    try {
      MBeanUtils.createMBean(user);
    } catch (Exception e) {
      IllegalArgumentException iae =
          new IllegalArgumentException("Exception creating user [" + username + "] MBean");
      iae.initCause(e);
      throw iae;
    }
    return (findUser(username));
  }

  /**
   * Return the MBean Name for the specified group name (if any); otherwise return <code>null</code>
   * .
   *
   * @param groupname Group name to look up
   */
  public String findGroup(String groupname) {

    UserDatabase database = (UserDatabase) this.resource;
    Group group = database.findGroup(groupname);
    if (group == null) {
      return (null);
    }
    try {
      ObjectName oname = MBeanUtils.createObjectName(managedGroup.getDomain(), group);
      return (oname.toString());
    } catch (MalformedObjectNameException e) {
      IllegalArgumentException iae =
          new IllegalArgumentException("Cannot create object name for group [" + groupname + "]");
      iae.initCause(e);
      throw iae;
    }
  }

  /**
   * Return the MBean Name for the specified role name (if any); otherwise return <code>null</code>.
   *
   * @param rolename Role name to look up
   */
  public String findRole(String rolename) {

    UserDatabase database = (UserDatabase) this.resource;
    Role role = database.findRole(rolename);
    if (role == null) {
      return (null);
    }
    try {
      ObjectName oname = MBeanUtils.createObjectName(managedRole.getDomain(), role);
      return (oname.toString());
    } catch (MalformedObjectNameException e) {
      IllegalArgumentException iae =
          new IllegalArgumentException("Cannot create object name for role [" + rolename + "]");
      iae.initCause(e);
      throw iae;
    }
  }

  /**
   * Return the MBean Name for the specified user name (if any); otherwise return <code>null</code>.
   *
   * @param username User name to look up
   */
  public String findUser(String username) {

    UserDatabase database = (UserDatabase) this.resource;
    User user = database.findUser(username);
    if (user == null) {
      return (null);
    }
    try {
      ObjectName oname = MBeanUtils.createObjectName(managedUser.getDomain(), user);
      return (oname.toString());
    } catch (MalformedObjectNameException e) {
      IllegalArgumentException iae =
          new IllegalArgumentException("Cannot create object name for user [" + username + "]");
      iae.initCause(e);
      throw iae;
    }
  }

  /**
   * Remove an existing group and destroy the corresponding MBean.
   *
   * @param groupname Group name to remove
   */
  public void removeGroup(String groupname) {

    UserDatabase database = (UserDatabase) this.resource;
    Group group = database.findGroup(groupname);
    if (group == null) {
      return;
    }
    try {
      MBeanUtils.destroyMBean(group);
      database.removeGroup(group);
    } catch (Exception e) {
      IllegalArgumentException iae =
          new IllegalArgumentException("Exception destroying group [" + groupname + "] MBean");
      iae.initCause(e);
      throw iae;
    }
  }

  /**
   * Remove an existing role and destroy the corresponding MBean.
   *
   * @param rolename Role name to remove
   */
  public void removeRole(String rolename) {

    UserDatabase database = (UserDatabase) this.resource;
    Role role = database.findRole(rolename);
    if (role == null) {
      return;
    }
    try {
      MBeanUtils.destroyMBean(role);
      database.removeRole(role);
    } catch (Exception e) {
      IllegalArgumentException iae =
          new IllegalArgumentException("Exception destroying role [" + rolename + "] MBean");
      iae.initCause(e);
      throw iae;
    }
  }

  /**
   * Remove an existing user and destroy the corresponding MBean.
   *
   * @param username User name to remove
   */
  public void removeUser(String username) {

    UserDatabase database = (UserDatabase) this.resource;
    User user = database.findUser(username);
    if (user == null) {
      return;
    }
    try {
      MBeanUtils.destroyMBean(user);
      database.removeUser(user);
    } catch (Exception e) {
      IllegalArgumentException iae =
          new IllegalArgumentException("Exception destroying user [" + username + "] MBean");
      iae.initCause(e);
      throw iae;
    }
  }
}
  public void execute() throws Exception {
    if (registry == null) registry = Registry.getRegistry(null, null);

    try {
      InputStream stream = (InputStream) source;
      long t1 = System.currentTimeMillis();
      Document doc = DomUtil.readXml(stream);
      // Ignore for now the name of the root element
      Node descriptorsN = doc.getDocumentElement();
      // Node descriptorsN=DomUtil.getChild(doc, "mbeans-descriptors");
      if (descriptorsN == null) {
        log.error("No descriptors found");
        return;
      }

      Node firstMbeanN = null;
      if ("mbean".equals(descriptorsN.getNodeName())) {
        firstMbeanN = descriptorsN;
      } else {
        firstMbeanN = DomUtil.getChild(descriptorsN, "mbean");
      }

      if (firstMbeanN == null) {
        log.error(" No mbean tags ");
        return;
      }

      // Process each <mbean> element
      for (Node mbeanN = firstMbeanN; mbeanN != null; mbeanN = DomUtil.getNext(mbeanN)) {

        // Create a new managed bean info
        ManagedBean managed = new ManagedBean();
        DomUtil.setAttributes(managed, mbeanN);
        Node firstN;

        // Process descriptor subnode
        /*Node mbeanDescriptorN =
            DomUtil.getChild(mbeanN, "descriptor");
        if (mbeanDescriptorN != null) {
            Node firstFieldN =
                DomUtil.getChild(mbeanDescriptorN, "field");
            for (Node fieldN = firstFieldN; fieldN != null;
                 fieldN = DomUtil.getNext(fieldN)) {
                FieldInfo fi = new FieldInfo();
                DomUtil.setAttributes(fi, fieldN);
                managed.addField(fi);
            }
        }*/

        // process attribute nodes
        firstN = DomUtil.getChild(mbeanN, "attribute");
        for (Node descN = firstN; descN != null; descN = DomUtil.getNext(descN)) {

          // Create new attribute info
          AttributeInfo ai = new AttributeInfo();
          DomUtil.setAttributes(ai, descN);

          // Process descriptor subnode
          /*Node descriptorN =
              DomUtil.getChild(descN, "descriptor");
          if (descriptorN != null) {
              Node firstFieldN =
                  DomUtil.getChild(descriptorN, "field");
              for (Node fieldN = firstFieldN; fieldN != null;
                   fieldN = DomUtil.getNext(fieldN)) {
                  FieldInfo fi = new FieldInfo();
                  DomUtil.setAttributes(fi, fieldN);
                  ai.addField(fi);
              }
          }
          */

          // Add this info to our managed bean info
          managed.addAttribute(ai);
          if (log.isTraceEnabled()) {
            log.trace("Create attribute " + ai);
          }
        }

        // process constructor nodes
        /*
        firstN=DomUtil.getChild( mbeanN, "constructor");
        for (Node descN = firstN; descN != null;
             descN = DomUtil.getNext( descN )) {

            // Create new constructor info
            ConstructorInfo ci=new ConstructorInfo();
            DomUtil.setAttributes(ci, descN);

            // Process descriptor subnode
            Node firstDescriptorN =
                DomUtil.getChild(descN, "descriptor");
            if (firstDescriptorN != null) {
                Node firstFieldN =
                    DomUtil.getChild(firstDescriptorN, "field");
                for (Node fieldN = firstFieldN; fieldN != null;
                     fieldN = DomUtil.getNext(fieldN)) {
                    FieldInfo fi = new FieldInfo();
                    DomUtil.setAttributes(fi, fieldN);
                    ci.addField(fi);
                }
            }

            // Process parameter subnodes
            Node firstParamN=DomUtil.getChild( descN, "parameter");
            for (Node paramN = firstParamN;  paramN != null;
                 paramN = DomUtil.getNext(paramN))
            {
                ParameterInfo pi=new ParameterInfo();
                DomUtil.setAttributes(pi, paramN);
                ci.addParameter( pi );
            }

            // Add this info to our managed bean info
            managed.addConstructor( ci );
            if (log.isTraceEnabled()) {
                log.trace("Create constructor " + ci);
            }

        }*/

        // process notification nodes
        firstN = DomUtil.getChild(mbeanN, "notification");
        for (Node descN = firstN; descN != null; descN = DomUtil.getNext(descN)) {

          // Create new notification info
          NotificationInfo ni = new NotificationInfo();
          DomUtil.setAttributes(ni, descN);

          // Process descriptor subnode
          /*Node firstDescriptorN =
              DomUtil.getChild(descN, "descriptor");
          if (firstDescriptorN != null) {
              Node firstFieldN =
                  DomUtil.getChild(firstDescriptorN, "field");
              for (Node fieldN = firstFieldN; fieldN != null;
                   fieldN = DomUtil.getNext(fieldN)) {
                  FieldInfo fi = new FieldInfo();
                  DomUtil.setAttributes(fi, fieldN);
                  ni.addField(fi);
              }
          }*/

          // Process notification-type subnodes
          Node firstParamN = DomUtil.getChild(descN, "notification-type");
          for (Node paramN = firstParamN; paramN != null; paramN = DomUtil.getNext(paramN)) {
            ni.addNotifType(DomUtil.getContent(paramN));
          }

          // Add this info to our managed bean info
          managed.addNotification(ni);
          if (log.isTraceEnabled()) {
            log.trace("Created notification " + ni);
          }
        }

        // process operation nodes
        firstN = DomUtil.getChild(mbeanN, "operation");
        for (Node descN = firstN; descN != null; descN = DomUtil.getNext(descN)) {

          // Create new operation info
          OperationInfo oi = new OperationInfo();
          DomUtil.setAttributes(oi, descN);

          // Process descriptor subnode
          /*Node firstDescriptorN =
              DomUtil.getChild(descN, "descriptor");
          if (firstDescriptorN != null) {
              Node firstFieldN =
                  DomUtil.getChild(firstDescriptorN, "field");
              for (Node fieldN = firstFieldN; fieldN != null;
                   fieldN = DomUtil.getNext(fieldN)) {
                  FieldInfo fi = new FieldInfo();
                  DomUtil.setAttributes(fi, fieldN);
                  oi.addField(fi);
              }
          }*/

          // Process parameter subnodes
          Node firstParamN = DomUtil.getChild(descN, "parameter");
          for (Node paramN = firstParamN; paramN != null; paramN = DomUtil.getNext(paramN)) {
            ParameterInfo pi = new ParameterInfo();
            DomUtil.setAttributes(pi, paramN);
            if (log.isTraceEnabled()) log.trace("Add param " + pi.getName());
            oi.addParameter(pi);
          }

          // Add this info to our managed bean info
          managed.addOperation(oi);
          if (log.isTraceEnabled()) {
            log.trace("Create operation " + oi);
          }
        }

        // Add the completed managed bean info to the registry
        registry.addManagedBean(managed);
      }

      long t2 = System.currentTimeMillis();
      log.debug("Reading descriptors ( dom ) " + (t2 - t1));
    } catch (Exception ex) {
      log.error("Error reading descriptors ", ex);
    }
  }
  /**
   * Acknowledge the occurrence of the specified event.
   *
   * @param event LifecycleEvent that has occurred
   */
  @Override
  public void lifecycleEvent(LifecycleEvent event) {

    container = event.getLifecycle();

    if (container instanceof Context) {
      namingResources = ((Context) container).getNamingResources();
      logger = log;
      token = ((Context) container).getNamingToken();
    } else if (container instanceof Server) {
      namingResources = ((Server) container).getGlobalNamingResources();
      token = ((Server) container).getNamingToken();
    } else {
      return;
    }

    if (Lifecycle.CONFIGURE_START_EVENT.equals(event.getType())) {

      if (initialized) return;

      try {
        Hashtable<String, Object> contextEnv = new Hashtable<>();
        namingContext = new NamingContext(contextEnv, getName());
        ContextAccessController.setSecurityToken(getName(), token);
        ContextAccessController.setSecurityToken(container, token);
        ContextBindings.bindContext(container, namingContext, token);
        if (log.isDebugEnabled()) {
          log.debug("Bound " + container);
        }

        // Configure write when read-only behaviour
        namingContext.setExceptionOnFailedWrite(getExceptionOnFailedWrite());

        // Setting the context in read/write mode
        ContextAccessController.setWritable(getName(), token);

        try {
          createNamingContext();
        } catch (NamingException e) {
          logger.error(sm.getString("naming.namingContextCreationFailed", e));
        }

        namingResources.addPropertyChangeListener(this);

        // Binding the naming context to the class loader
        if (container instanceof Context) {
          // Setting the context in read only mode
          ContextAccessController.setReadOnly(getName());
          try {
            ContextBindings.bindClassLoader(
                container, token, ((Context) container).getLoader().getClassLoader());
          } catch (NamingException e) {
            logger.error(sm.getString("naming.bindFailed", e));
          }
        }

        if (container instanceof Server) {
          org.apache.naming.factory.ResourceLinkFactory.setGlobalContext(namingContext);
          try {
            ContextBindings.bindClassLoader(container, token, this.getClass().getClassLoader());
          } catch (NamingException e) {
            logger.error(sm.getString("naming.bindFailed", e));
          }
          if (container instanceof StandardServer) {
            ((StandardServer) container).setGlobalNamingContext(namingContext);
          }
        }

      } finally {
        // Regardless of success, so that we can do cleanup on configure_stop
        initialized = true;
      }

    } else if (Lifecycle.CONFIGURE_STOP_EVENT.equals(event.getType())) {

      if (!initialized) return;

      try {
        // Setting the context in read/write mode
        ContextAccessController.setWritable(getName(), token);
        ContextBindings.unbindContext(container, token);

        if (container instanceof Context) {
          ContextBindings.unbindClassLoader(
              container, token, ((Context) container).getLoader().getClassLoader());
        }

        if (container instanceof Server) {
          namingResources.removePropertyChangeListener(this);
          ContextBindings.unbindClassLoader(container, token, this.getClass().getClassLoader());
        }

        ContextAccessController.unsetSecurityToken(getName(), token);
        ContextAccessController.unsetSecurityToken(container, token);

        // unregister mbeans.
        if (!objectNames.isEmpty()) {
          Collection<ObjectName> names = objectNames.values();
          Registry registry = Registry.getRegistry(null, null);
          for (ObjectName objectName : names) {
            registry.unregisterComponent(objectName);
          }
        }
      } finally {
        objectNames.clear();

        namingContext = null;
        envCtx = null;
        compCtx = null;
        initialized = false;
      }
    }
  }
Exemplo n.º 25
0
 public void destroy() throws Exception {
   if (log.isInfoEnabled()) log.info(sm.getString("http11protocol.stop", getName()));
   endpoint.destroy();
   if (tpOname != null) Registry.getRegistry(null, null).unregisterComponent(tpOname);
   if (rgOname != null) Registry.getRegistry(null, null).unregisterComponent(rgOname);
 }
Exemplo n.º 26
0
/**
 * A <strong>ModelMBean</strong> implementation for the <code>org.apache.catalina.Group</code>
 * component.
 *
 * @author Craig R. McClanahan
 * @version $Id: GroupMBean.java,v 1.1 2011/06/28 21:14:10 rherrmann Exp $
 */
public class GroupMBean extends BaseModelMBean {

  // ----------------------------------------------------------- Constructors

  /**
   * Construct a <code>ModelMBean</code> with default <code>ModelMBeanInfo</code> information.
   *
   * @exception MBeanException if the initializer of an object throws an exception
   * @exception RuntimeOperationsException if an IllegalArgumentException occurs
   */
  public GroupMBean() throws MBeanException, RuntimeOperationsException {

    super();
  }

  // ----------------------------------------------------- Instance Variables

  /** The configuration information registry for our managed beans. */
  protected Registry registry = MBeanUtils.createRegistry();

  /** The <code>ManagedBean</code> information describing this MBean. */
  protected ManagedBean managed = registry.findManagedBean("Group");

  // ------------------------------------------------------------- Attributes

  /** Return the MBean Names of all authorized roles for this group. */
  public String[] getRoles() {

    Group group = (Group) this.resource;
    ArrayList<String> results = new ArrayList<String>();
    Iterator<Role> roles = group.getRoles();
    while (roles.hasNext()) {
      Role role = null;
      try {
        role = roles.next();
        ObjectName oname = MBeanUtils.createObjectName(managed.getDomain(), role);
        results.add(oname.toString());
      } catch (MalformedObjectNameException e) {
        IllegalArgumentException iae =
            new IllegalArgumentException("Cannot create object name for role " + role);
        iae.initCause(e);
        throw iae;
      }
    }
    return results.toArray(new String[results.size()]);
  }

  /** Return the MBean Names of all users that are members of this group. */
  public String[] getUsers() {

    Group group = (Group) this.resource;
    ArrayList<String> results = new ArrayList<String>();
    Iterator<User> users = group.getUsers();
    while (users.hasNext()) {
      User user = null;
      try {
        user = users.next();
        ObjectName oname = MBeanUtils.createObjectName(managed.getDomain(), user);
        results.add(oname.toString());
      } catch (MalformedObjectNameException e) {
        IllegalArgumentException iae =
            new IllegalArgumentException("Cannot create object name for user " + user);
        iae.initCause(e);
        throw iae;
      }
    }
    return results.toArray(new String[results.size()]);
  }

  // ------------------------------------------------------------- Operations

  /**
   * Add a new {@link Role} to those this group belongs to.
   *
   * @param rolename Role name of the new role
   */
  public void addRole(String rolename) {

    Group group = (Group) this.resource;
    if (group == null) {
      return;
    }
    Role role = group.getUserDatabase().findRole(rolename);
    if (role == null) {
      throw new IllegalArgumentException("Invalid role name '" + rolename + "'");
    }
    group.addRole(role);
  }

  /**
   * Remove a {@link Role} from those this group belongs to.
   *
   * @param rolename Role name of the old role
   */
  public void removeRole(String rolename) {

    Group group = (Group) this.resource;
    if (group == null) {
      return;
    }
    Role role = group.getUserDatabase().findRole(rolename);
    if (role == null) {
      throw new IllegalArgumentException("Invalid role name '" + rolename + "'");
    }
    group.removeRole(role);
  }
}
Exemplo n.º 27
0
  /** {@inheritDoc} */
  public synchronized void start(StartContext context) throws StartException {
    if (org.apache.tomcat.util.Constants.ENABLE_MODELER) {
      // Set the MBeanServer
      final MBeanServer mbeanServer = this.mbeanServer.getOptionalValue();
      if (mbeanServer != null) {
        Registry.getRegistry(null, null).setMBeanServer(mbeanServer);
      }
    }

    System.setProperty(
        "catalina.home", pathManagerInjector.getValue().getPathEntry(TEMP_DIR).resolvePath());
    server = new StandardServer();

    //        final StandardService service = new StandardService();
    //        service.setName(JBOSS_SIP);
    //        service.setServer(server);
    //        server.addService(service);

    //        final Engine engine = new StandardEngine();
    //        engine.setName(JBOSS_SIP);
    //        engine.setService(service);
    //        engine.setDefaultHost(defaultHost);
    //        if (instanceId != null) {
    //            engine.setJvmRoute(instanceId);
    //        }
    //
    //        service.setContainer(engine);

    //        if (useNative) {
    //            final AprLifecycleListener apr = new AprLifecycleListener();
    //            apr.setSSLEngine("on");
    //            server.addLifecycleListener(apr);
    //        }
    //        server.addLifecycleListener(new JasperListener());

    sipService = new SipStandardService();
    // https://code.google.com/p/sipservlets/issues/detail?id=277
    // Add the Service and sip app dispatched right away so apps can get the needed objects
    // when they deploy fast
    server.addService(sipService);

    if (sipAppDispatcherClass != null) {
      sipService.setSipApplicationDispatcherClassName(sipAppDispatcherClass);
    } else {
      sipService.setSipApplicationDispatcherClassName(SipApplicationDispatcherImpl.class.getName());
    }
    //
    final String baseDir = System.getProperty("jboss.server.base.dir");
    if (sipAppRouterFile != null) {
      if (!sipAppRouterFile.startsWith(FILE_PREFIX_PATH)) {
        sipAppRouterFile = FILE_PREFIX_PATH.concat(baseDir).concat("/").concat(sipAppRouterFile);
      }
      System.setProperty("javax.servlet.sip.dar", sipAppRouterFile);
    }
    //
    sipService.setSipPathName(sipPathName);
    //
    if (sipStackPropertiesFile != null) {
      if (!sipStackPropertiesFile.startsWith(FILE_PREFIX_PATH)) {
        sipStackPropertiesFile =
            FILE_PREFIX_PATH.concat(baseDir).concat("/").concat(sipStackPropertiesFile);
      }
    }
    sipService.setSipStackPropertiesFile(sipStackPropertiesFile);
    //
    if (sipConcurrencyControlMode != null) {
      sipService.setConcurrencyControlMode(sipConcurrencyControlMode);
    } else {
      sipService.setConcurrencyControlMode("None");
    }
    //
    sipService.setCongestionControlCheckingInterval(sipCongestionControlInterval);
    //
    sipService.setUsePrettyEncoding(usePrettyEncoding);
    //
    sipService.setBaseTimerInterval(baseTimerInterval);
    sipService.setT2Interval(t2Interval);
    sipService.setT4Interval(t4Interval);
    sipService.setTimerDInterval(timerDInterval);
    if (additionalParameterableHeaders != null) {
      sipService.setAdditionalParameterableHeaders(additionalParameterableHeaders);
    }
    sipService.setDialogPendingRequestChecking(dialogPendingRequestChecking);
    sipService.setDnsServerLocatorClass(dnsServerLocatorClass);
    sipService.setDnsTimeout(dnsTimeout);
    sipService.setDnsResolverClass(dnsResolverClass);
    sipService.setCanceledTimerTasksPurgePeriod(canceledTimerTasksPurgePeriod);
    sipService.setMemoryThreshold(memoryThreshold);
    sipService.setBackToNormalMemoryThreshold(backToNormalMemoryThreshold);
    sipService.setCongestionControlPolicy(congestionControlPolicy);
    sipService.setOutboundProxy(outboundProxy);
    sipService.setName(JBOSS_SIP);
    sipService.setServer(server);

    sipEngine = new SipStandardEngine();
    sipEngine.setName(JBOSS_SIP);
    sipEngine.setService(sipService);
    //        sipEngine.setDefaultHost(defaultHost);
    if (instanceId != null) {
      sipEngine.setJvmRoute(instanceId);
    }
    sipService.setContainer(sipEngine);

    try {
      server.init();
      server.start();
    } catch (Exception e) {
      throw new StartException(MESSAGES.errorStartingSip(), e);
    }
  }
Exemplo n.º 28
0
 /**
  * Get the current MBean Server.
  *
  * @return
  * @throws Exception
  */
 protected MBeanServer getMBeanServer() throws Exception {
   if (mserver_ == null) {
     mserver_ = Registry.getRegistry(null, null).getMBeanServer();
   }
   return mserver_;
 }