/**
 * PostDeregisterError.
 *
 * @author <a href="*****@*****.**">Adrian Brock</a>
 * @version $Revision: 85945 $
 */
public class PostDeregisterError extends AbstractRegistration {
  public static final ObjectName OBJECT_NAME =
      ObjectNameFactory.create("jboss.test:type=PostDeregisterError");

  public void postDeregister() {
    throw new Error("BROKEN");
  }
}
/** MBean interface. */
public interface AspectDeployerMBean extends org.jboss.deployment.SubDeployerMBean {

  // default object name
  public static final javax.management.ObjectName OBJECT_NAME =
      org.jboss.mx.util.ObjectNameFactory.create("jboss.aspect:AspectDeployer");

  /**
   * Returns true if this deployer can deploy the given DeploymentInfo.
   *
   * @return True if this deployer can deploy the given DeploymentInfo.
   */
  boolean accepts(org.jboss.deployment.DeploymentInfo di);

  /**
   * Describe <code>init</code> method here.
   *
   * @param di a <code>DeploymentInfo</code> value
   * @throws DeploymentException if an error occurs
   */
  void init(org.jboss.deployment.DeploymentInfo di) throws org.jboss.deployment.DeploymentException;

  /**
   * Describe <code>create</code> method here.
   *
   * @param di a <code>DeploymentInfo</code> value
   * @throws DeploymentException if an error occurs
   */
  void create(org.jboss.deployment.DeploymentInfo di)
      throws org.jboss.deployment.DeploymentException;

  /**
   * The <code>start</code> method starts all the mbeans in this DeploymentInfo..
   *
   * @param di a <code>DeploymentInfo</code> value
   * @throws DeploymentException if an error occurs
   */
  void start(org.jboss.deployment.DeploymentInfo di)
      throws org.jboss.deployment.DeploymentException;

  /**
   * Undeploys the package at the url string specified. This will: Undeploy packages depending on
   * this one. Stop, destroy, and unregister all the specified mbeans Unload this package and
   * packages this package deployed via the classpath tag. Keep track of packages depending on this
   * one that we undeployed so that they can be redeployed should this one be redeployed.
   *
   * @param di the <code>DeploymentInfo</code> value to stop.
   */
  void stop(org.jboss.deployment.DeploymentInfo di);

  /**
   * Describe <code>destroy</code> method here.
   *
   * @param di a <code>DeploymentInfo</code> value
   */
  void destroy(org.jboss.deployment.DeploymentInfo di);
}
/**
 * SimpleMXBeanSupportMXBean.
 *
 * @author <a href="*****@*****.**">Adrian Brock</a>
 * @version $Revision: 85945 $
 */
public interface SimpleMXBeanSupportMXBean extends SimpleInterface {
  /** The Object name */
  ObjectName REGISTERED_OBJECT_NAME = ObjectNameFactory.create("test:test=SimpleMXBeanSupport");

  void setBoolean(Boolean booleanV);

  void setByte(Byte byteV);

  void setCharacter(Character characterV);

  void setDouble(Double doubleV);

  void setFloat(Float floatV);

  void setLong(Long longV);

  void setShort(Short shortV);

  void setBigDecimal(BigDecimal bigDecimal);

  void setBigInteger(BigInteger bigInteger);

  void setDate(Date date);

  void setInteger(Integer integer);

  void setObjectName(ObjectName objectName);

  void setPrimitiveBoolean(boolean primitiveBoolean);

  void setPrimitiveByte(byte primitiveByte);

  void setPrimitiveChar(char primitiveChar);

  void setPrimitiveDouble(double primitiveDouble);

  void setPrimitiveFloat(float primitiveFloat);

  void setPrimitiveInt(int primitiveInt);

  void setPrimitiveLong(long primitiveLong);

  void setPrimitiveShort(short primitiveShort);

  void setString(String string);

  String echoReverse(String string);
}
/**
 * The interface to the MBean that manages the server-side communications services. Note that this
 * also includes the {@link ServiceContainerMetricsMBean} interface. In order to put all of our comm
 * subsystem metrics and configuration in a single service resource that our plugin can expose,
 * we'll pass through those metrics from that MBean through our interface, too.
 *
 * @author John Mazzitelli
 */
public interface ServerCommunicationsServiceMBean extends ServiceContainerMetricsMBean {
  /** The object name that the MBean service will be registered under. */
  ObjectName OBJECT_NAME = ObjectNameFactory.create("rhq:service=ServerCommunications");

  /**
   * Returns the location of the configuration file where all preferences are defined for the
   * server-side services. The file location can be either a URL, a local file system path or a path
   * within this service's classloader.
   *
   * @return configuration file location
   */
  String getConfigurationFile();

  /**
   * Defines the location of the configuration file where all preferences are defined for the
   * server-side services. The file location can be either a URL, a local file system path or a path
   * within this service's classloader.
   *
   * @param location
   */
  void setConfigurationFile(String location);

  /**
   * Returns the preferences node name used to identify the configuration set to use. See the Java
   * Preferences API for the definition of a preference node name.
   *
   * @return the name of the Java Preferences node where the server's configuration lives
   */
  String getPreferencesNodeName();

  /**
   * Defines the preferences node name used to identify the configuration set to use. See the Java
   * Preferences API for the definition of a preference node name.
   *
   * <p>If this isn't specified, a suitable default will be used.
   *
   * @param node the name of the Java Preferences node where the server's configuration will or
   *     already lives
   */
  void setPreferencesNodeName(String node);

  /**
   * This allows you to explicitly override configuration preferences found in the configuration
   * file. If this isn't set, then the settings specified by the configuration preferences file take
   * effect as-is. If this is set, this file is a properties file whose values will override the
   * config file prefs.
   *
   * @param overrides configuration settings file that override the configuration preferences (may
   *     be<code>null</code>)
   */
  void setConfigurationOverridesFile(String overridesFile);

  String getConfigurationOverridesFile();

  /**
   * This will clear any and all current configuration preferences and then reload the {@link
   * #getConfigurationFile() configuration file}.
   *
   * @return the new server configuration
   * @throws Exception if failed to clear and reload the configuration
   */
  ServerConfiguration reloadConfiguration() throws Exception;

  /**
   * Returns the configuration of the server-side communication components. If the configuration has
   * not yet been loaded, this will return <code>null</code>.
   *
   * @return the server configuration
   */
  ServerConfiguration getConfiguration();

  /**
   * Starts the communications services used by the server to send and receive messages to/from
   * agents.
   *
   * @throws Exception if failed to start the server-side services successfully
   */
  void startCommunicationServices() throws Exception;

  /**
   * Stops the service which will stop all server-side services. Incoming messages will no longer be
   * able to be received after this method is called.
   *
   * @throws Exception if failed to stop the server-side services
   */
  void stop() throws Exception;

  /**
   * @return true if communication services have been started. False if not initialized or stopped.
   */
  boolean isStarted();

  /**
   * Returns the service container that houses all the server-side communications services. Will
   * create a service container for the comm services if one has not yet been created. This is
   * typically only called to add or remove listeners prior to comm service startup. Use isStarted()
   * as necessary.
   *
   * @return service container object
   */
  ServiceContainer safeGetServiceContainer();

  /**
   * Returns the service container that houses all the server-side communications services. Will
   * return <code>
   * null</code> if the serviceContainer has not been initialized. It is possible for this to be
   * non-null prior to server-side comm services initialization. Use isStarted() as necessary.
   *
   * @return service container object
   */
  ServiceContainer getServiceContainer();

  /**
   * If the server is currently listening for requests, this will return the endpoint the agents
   * should use to connect to it. If the server's underlying communications services are not
   * deployed and running, this returns <code>
   * null</code>.
   *
   * @return the server's remote endpoint that agents use to connect to the server
   */
  String getStartedServerEndpoint();

  /**
   * Given an agent domain object, this will see if that agent is known by looking up its host and
   * port from the list of all {@link #getAllKnownAgents() known agents} and returns a client to
   * that agent. An agent can become known if it has been auto discovered.
   *
   * @param agent the agent whose client is to be returned
   * @return the agent client; will be <code>null</code> if that agent is not known
   */
  AgentClient getKnownAgentClient(Agent agent);

  /**
   * This will stop the client, remove it from the cache and clean up any resources used by the
   * client. This is normally called when an agent has been completely removed from inventory.
   *
   * @param agent the agent whose client is to be destroyed
   */
  void destroyKnownAgentClient(Agent agent);

  /**
   * This returns a list of all known agents that the server is in communications with.
   *
   * @return the list of agents (which may or may not be empty)
   */
  List<InvokerLocator> getAllKnownAgents();

  /**
   * Given an {@link Agent agent} (which includes its remote endpoint and name), this will see if it
   * is not yet a known agent and if so, will add it. This should be called only when you know an
   * agent has started.
   *
   * @param agent the agent (which has the endpoint of the agent that has started and its name)
   */
  void addStartedAgent(Agent agent);

  /**
   * Given an {@link Agent#getRemoteEndpoint() agent remote endpoint}, this will see if it is a
   * known agent and if so, will remove it. This should be called only when you know an agent has
   * gone down.
   *
   * @param endpoint the endpoint of the agent that has gone down
   */
  void removeDownedAgent(String endpoint);

  /**
   * This will perform an ad-hoc, low-level ping to the given endpoint. This is usually reserved for
   * those callers that need to confirm that an endpoint exists and can be communicated with, before
   * being added as an official agent endpoint.
   *
   * @param endpoint the endpoint to ping
   * @param timeoutMillis the timeout, in milliseconds, to wait for the ping to return
   * @return <code>true</code> if connectivity to the given endpoint was verified; <code>false
   *     </code> if for some reason the endpoint could not be pinged
   */
  boolean pingEndpoint(String endpoint, long timeoutMillis);

  /**
   * Gets the global concurrency limit. This is the amount of messages that the server will allow to
   * be processed concurrently - the type of message doesn't matter, this is the global maximum of
   * any and all messages that are allowed to be concurrently accepted.
   *
   * @return number of concurrent calls allowed
   */
  Integer getGlobalConcurrencyLimit();

  /**
   * Sets the global concurrency limit. This is the amount of messages that the server will allow to
   * be processed concurrently - the type of message doesn't matter, this is the global maximum of
   * any and all messages that are allowed to be concurrently accepted.
   *
   * @param maxConcurrency
   */
  void setGlobalConcurrencyLimit(Integer maxConcurrency);

  /**
   * Gets the concurrency limit for inventory reports. This is the amount of inventory reports that
   * the server will allow to be processed concurrently.
   *
   * @return number of concurrent calls allowed
   */
  Integer getInventoryReportConcurrencyLimit();

  /**
   * Sets the new concurrency limit for inventory reports. This new number is the amount of
   * inventory reports that the server will allow to be processed concurrently.
   *
   * @param maxConcurrency
   */
  void setInventoryReportConcurrencyLimit(Integer maxConcurrency);

  /**
   * Gets the concurrency limit for availability reports. This is the amount of availability reports
   * that the server will allow to be processed concurrently.
   *
   * @return number of concurrent calls allowed
   */
  Integer getAvailabilityReportConcurrencyLimit();

  /**
   * Sets the new concurrency limit for availability reports. This new number is the amount of
   * availability reports that the server will allow to be processed concurrently.
   *
   * @param maxConcurrency
   */
  void setAvailabilityReportConcurrencyLimit(Integer maxConcurrency);

  /**
   * Gets the concurrency limit for inventory sync requests. This is the amount of inventory sync
   * requests that the server will allow to be processed concurrently.
   *
   * @return number of concurrent calls allowed
   */
  Integer getInventorySyncConcurrencyLimit();

  /**
   * Sets the new concurrency limit for inventory sync requests. This new number is the amount of
   * inventory sync requests that the server will allow to be processed concurrently.
   *
   * @param maxConcurrency
   */
  void setInventorySyncConcurrencyLimit(Integer maxConcurrency);

  /**
   * Gets the concurrency limit for content reports. This is the amount of content reports that the
   * server will allow to be processed concurrently.
   *
   * @return number of concurrent calls allowed
   */
  Integer getContentReportConcurrencyLimit();

  /**
   * Sets the new concurrency limit for content reports. This new number is the amount of content
   * reports that the server will allow to be processed concurrently.
   *
   * @param maxConcurrency
   */
  void setContentReportConcurrencyLimit(Integer maxConcurrency);

  /**
   * Gets the concurrency limit for content downloads. This is the amount of downloads that the
   * server will allow to be processed concurrently.
   *
   * @return number of concurrent calls allowed
   */
  Integer getContentDownloadConcurrencyLimit();

  /**
   * Sets the new concurrency limit for content downloads. This new number is the amount of
   * downloads that the server will allow to be processed concurrently.
   *
   * @param maxConcurrency
   */
  void setContentDownloadConcurrencyLimit(Integer maxConcurrency);

  /**
   * Gets the concurrency limit for measurement reports. This is the amount of measurement reports
   * that the server will allow to be processed concurrently.
   *
   * @return number of concurrent calls allowed
   */
  Integer getMeasurementReportConcurrencyLimit();

  /**
   * Sets the new concurrency limit for measurement reports. This new number is the amount of
   * measurement reports that the server will allow to be processed concurrently.
   *
   * @param maxConcurrency
   */
  void setMeasurementReportConcurrencyLimit(Integer maxConcurrency);

  /**
   * Gets the concurrency limit for measurement reports. This is the amount of measurement reports
   * that the server will allow to be processed concurrently.
   *
   * @return number of concurrent calls allowed
   */
  Integer getMeasurementScheduleRequestConcurrencyLimit();

  /**
   * Sets the new concurrency limit for measurement schedule requests. This new number is the amount
   * of measurement schedule requests that the server will allow to be processed concurrently.
   *
   * @param maxConcurrency
   */
  void setMeasurementScheduleRequestConcurrencyLimit(Integer maxConcurrency);

  /**
   * Returns <code>true</code> if the server should always start up in maintenance mode. If <code>
   * false</code>, the server will startup in the same state it was in when it was shutdown.
   *
   * @return <code>true</code> if the server should always start up in MM
   */
  Boolean getMaintenanceModeAtStartup();

  /**
   * Same as {@link #getMaintenanceModeAtStartup()}.
   *
   * @return <code>true</code> if server starts up in MM
   */
  Boolean isMaintenanceModeAtStartup();

  /**
   * Sets the flag to indicate if the server should always start up in maintenance mode. See {@link
   * #getMaintenanceModeAtStartup()} for more.
   *
   * @param flag
   */
  void setMaintenanceModeAtStartup(Boolean flag);
}
/**
 * Test JBAS-3861 (DeploymentFileRepository service)
 *
 * @author <a href="mailto:[email protected]">Dimitris Andreadis</a>
 * @version $Revision: 85945 $
 */
public class JBAS3861UnitTestCase extends JBossTestCase {
  ObjectName target = ObjectNameFactory.create("jboss.admin:service=DeploymentFileRepository");

  public JBAS3861UnitTestCase(String name) {
    super(name);
  }

  /** Check if BaseDir can be set outside the server home directory */
  public void testSetBaseDirOutsideServerHomeDir() throws Exception {
    // remember original BaseDir
    String basedir = (String) getServer().getAttribute(target, "BaseDir");
    try {
      // Should throw an IllegalArgumentException
      getServer().setAttribute(target, new Attribute("BaseDir", ".."));
      // Should throw an IllegalArgumentException
      getServer().setAttribute(target, new Attribute("BaseDir", "/"));

      // Restore the original dir and fail the test
      getServer().setAttribute(target, new Attribute("BaseDir", basedir));
      fail("Managed to set BaseDir outside ServerHomeDir for service: " + target);
    } catch (RuntimeMBeanException e) {
      // expected
    }
  }

  /** Check if we can write a file outside the server home directory */
  public void testStoreFileOutsideServerHomeDir() throws Exception {
    try {
      // Should throw an exception
      getServer()
          .invoke(
              target,
              "store",
              new Object[] {"..", "jbas3861", ".tmp", "file content", Boolean.TRUE},
              new String[] {
                "java.lang.String",
                "java.lang.String",
                "java.lang.String",
                "java.lang.String",
                Boolean.TYPE.toString()
              });

      // Should throw an exception
      getServer()
          .invoke(
              target,
              "store",
              new Object[] {".", "../jbas3861", ".tmp", "file content", Boolean.TRUE},
              new String[] {
                "java.lang.String",
                "java.lang.String",
                "java.lang.String",
                "java.lang.String",
                Boolean.TYPE.toString()
              });

      // Remove the stored file and fail the test - normally it should throw an exception, too
      getServer()
          .invoke(
              target,
              "remove",
              new Object[] {".", "../jbas3861", ".tmp"},
              new String[] {"java.lang.String", "java.lang.String", "java.lang.String"});

      fail("Managed to create/remove a file outside ServerHomeDir for service: " + target);
    } catch (RuntimeMBeanException e) {
      // expected
    }
  }
}
Example #6
0
  public static void main(final String[] args) throws Exception {
    if (args.length == 0) {
      displayUsage();
      System.exit(0);
    }

    String sopts = "-:hD:s:n:a:u:p:Se:H:";
    LongOpt[] lopts = {
      new LongOpt("help", LongOpt.NO_ARGUMENT, null, 'h'),
      new LongOpt("server", LongOpt.REQUIRED_ARGUMENT, null, 's'),
      new LongOpt("adapter", LongOpt.REQUIRED_ARGUMENT, null, 'a'),
      new LongOpt("serverName", LongOpt.REQUIRED_ARGUMENT, null, 'n'),
      new LongOpt("shutdown", LongOpt.NO_ARGUMENT, null, 'S'),
      new LongOpt("exit", LongOpt.REQUIRED_ARGUMENT, null, 'e'),
      new LongOpt("halt", LongOpt.REQUIRED_ARGUMENT, null, 'H'),
      new LongOpt("user", LongOpt.REQUIRED_ARGUMENT, null, 'u'),
      new LongOpt("password", LongOpt.REQUIRED_ARGUMENT, null, 'p'),
    };

    Getopt getopt = new Getopt(PROGRAM_NAME, args, sopts, lopts);
    int code;
    String arg;

    String serverURL = null;
    String adapterName = "jmx/rmi/RMIAdaptor";
    String username = null;
    String password = null;
    ObjectName serverJMXName = ObjectNameFactory.create("jboss.system:type=JVMShutdown");
    boolean exit = false;
    boolean halt = false;
    int exitcode = -1;

    while ((code = getopt.getopt()) != -1) {
      switch (code) {
        case ':':
        case '?':
          // for now both of these should exit with error status
          System.exit(1);
          break;

        case 1:
          // this will catch non-option arguments
          // (which we don't currently care about)
          System.err.println(PROGRAM_NAME + ": unused non-option argument: " + getopt.getOptarg());
          break;
        case 'h':
          displayUsage();
          System.exit(0);
          break;
        case 'D':
          {
            // set a system property
            arg = getopt.getOptarg();
            String name, value;
            int i = arg.indexOf("=");
            if (i == -1) {
              name = arg;
              value = "true";
            } else {
              name = arg.substring(0, i);
              value = arg.substring(i + 1, arg.length());
            }
            System.setProperty(name, value);
            break;
          }
        case 's':
          serverURL = getopt.getOptarg();
          break;
        case 'n':
          serverJMXName = new ObjectName(getopt.getOptarg());
          break;
        case 'S':
          // nothing...
          break;
        case 'a':
          adapterName = getopt.getOptarg();
          break;
        case 'u':
          username = getopt.getOptarg();
          SecurityAssociation.setPrincipal(new SimplePrincipal(username));
          break;
        case 'p':
          password = getopt.getOptarg();
          SecurityAssociation.setCredential(password);
          break;
        case 'e':
          exitcode = Integer.parseInt(getopt.getOptarg());
          exit = true;
          break;
        case 'H':
          exitcode = Integer.parseInt(getopt.getOptarg());
          halt = true;
          break;
      }
    }

    InitialContext ctx;

    // If there was a username specified, but no password prompt for it
    if (username != null && password == null) {
      System.out.print("Enter password for " + username + ": ");
      BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
      password = br.readLine();
      SecurityAssociation.setCredential(password);
    }

    if (serverURL == null) {
      ctx = new InitialContext();
    } else {
      Hashtable env = new Hashtable();
      env.put(Context.PROVIDER_URL, serverURL);
      env.put(NamingContext.JNP_DISABLE_DISCOVERY, "true");
      // This is a hack
      if (serverURL.startsWith("http:") || serverURL.startsWith("https:"))
        env.put(Context.INITIAL_CONTEXT_FACTORY, HttpNamingContextFactory.class.getName());
      ctx = new InitialContext(env);
    }

    Object obj = ctx.lookup(adapterName);
    if (!(obj instanceof MBeanServerConnection)) {
      throw new RuntimeException(
          "Object not of type: MBeanServerConnection, but: "
              + (obj == null ? "not found" : obj.getClass().getName()));
    }

    MBeanServerConnection adaptor = (MBeanServerConnection) obj;
    ServerProxyHandler handler = new ServerProxyHandler(adaptor, serverJMXName);
    Class<?>[] ifaces = {JVMShutdownMBean.class};
    ClassLoader tcl = Thread.currentThread().getContextClassLoader();
    JVMShutdownMBean server = (JVMShutdownMBean) Proxy.newProxyInstance(tcl, ifaces, handler);

    if (exit) {
      server.exit(exitcode);
    } else if (halt) {
      server.halt(exitcode);
    } else {
      server.shutdown();
    }
    System.out.println("Shutdown message has been posted to the server.");
    System.out.println("Server shutdown may take a while - check logfiles for completion");
  }
/**
 * DependencyListValueTest.
 *
 * @author <a href="*****@*****.**">Adrian Brock</a>
 * @version $Revision: 85945 $
 */
public abstract class DependencyListValueTest extends AbstractControllerTest {
  static ObjectName DEPENDS1 = ObjectNameFactory.create("jboss.test:type=depends1");
  static ObjectName[] DEPENDSLIST1 = new ObjectName[] {DEPENDS1};
  static ObjectName DEPENDS2 = ObjectNameFactory.create("jboss.test:type=depends2");
  static ObjectName[] DEPENDSLIST2 = new ObjectName[] {DEPENDS1, DEPENDS2};

  public DependencyListValueTest(String name) {
    super(name);
  }

  protected void assertEquals(ObjectName[] expected, Collection<ObjectName> actual) {
    List<ObjectName> expectedList = Arrays.asList(expected);
    assertEquals(expectedList, actual);
  }

  public void testNone() throws Exception {
    ObjectName name = SimpleMBean.OBJECT_NAME;
    assertInstall(name);
    try {
      Simple simple = getSimple();
      assertEquals(new ObjectName[0], simple.getObjectNames());
    } finally {
      assertUninstall(name);
    }
  }

  public void testOne() throws Exception {
    ObjectName name = SimpleMBean.OBJECT_NAME;
    assertInstall(name);
    try {
      Simple simple = getSimple();
      assertEquals(DEPENDSLIST1, simple.getObjectNames());
    } finally {
      assertUninstall(name);
    }
  }

  public void testTwo() throws Exception {
    ObjectName name = SimpleMBean.OBJECT_NAME;
    assertInstall(name);
    try {
      Simple simple = getSimple();
      assertEquals(DEPENDSLIST2, simple.getObjectNames());
    } finally {
      assertUninstall(name);
    }
  }

  public void testNested() throws Exception {
    ObjectName name = SimpleMBean.OBJECT_NAME;
    assertInstall(name);
    try {
      Simple simple = getSimple();
      assertEquals(DEPENDSLIST1, simple.getObjectNames());
    } finally {
      assertUninstall(name);
    }
  }

  public void testNoValue() throws Exception {
    assertDeployFailure(SimpleMBean.OBJECT_NAME, MalformedObjectNameException.class);
  }

  public void testEmptyValue() throws Exception {
    assertDeployFailure(SimpleMBean.OBJECT_NAME, MalformedObjectNameException.class);
  }

  public void testInvalidValue() throws Exception {
    assertDeployFailure(SimpleMBean.OBJECT_NAME, MalformedObjectNameException.class);
  }

  public void testUnknownElement() throws Exception {
    assertDeployFailure(SimpleMBean.OBJECT_NAME, MalformedObjectNameException.class);
  }

  public void testPatternValue() throws Exception {
    assertDeployFailure(SimpleMBean.OBJECT_NAME, MalformedObjectNameException.class);
  }

  public void testBrokenSetAttribute() throws Exception {
    assertDeployFailure(SimpleMBean.OBJECT_NAME, Error.class);
  }
}