Ejemplo n.º 1
0
  public static String getServerPort(String protocol, String scheme) {
    MBeanServer mBeanServer = null;
    if (MBeanServerFactory.findMBeanServer(null).size() > 0) {
      mBeanServer = (MBeanServer) MBeanServerFactory.findMBeanServer(null).get(0);
    }
    if (mBeanServer == null) {
      return null;
    }

    Set names = null;
    try {
      names =
          mBeanServer.queryNames(
              new ObjectName("Catalina:type=Connector,*"), null); // TODO support tomcat
    } catch (Exception e) {
      return null;
    }

    try {
      Iterator it = names.iterator();
      ObjectName oname = null;
      while (it.hasNext()) {
        oname = (ObjectName) it.next();
        String pvalue = (String) mBeanServer.getAttribute(oname, "protocol");
        String svalue = (String) mBeanServer.getAttribute(oname, "scheme");
        if (protocol.equalsIgnoreCase(pvalue) && scheme.equalsIgnoreCase(svalue)) {
          return ((Integer) mBeanServer.getAttribute(oname, "port")).toString();
        }
      }
    } catch (Exception e) {
      throw new IllegalStateException(e.getMessage(), e);
    }
    return null;
  }
Ejemplo n.º 2
0
 /**
  * Resets MBeanServerFactory and ManagementFactory to a known consistent state. This involves
  * releasing all currently registered MBeanServers and resetting the platformMBeanServer to null.
  */
 public static void resetMBeanServers() throws Exception {
   for (MBeanServer server : MBeanServerFactory.findMBeanServer(null)) {
     MBeanServerFactory.releaseMBeanServer(server);
   }
   Field field = ManagementFactory.class.getDeclaredField("platformMBeanServer");
   field.setAccessible(true);
   field.set(null, null);
 }
 public static MBeanServer getMBeanServer() throws Exception {
   if (mbeanServer == null) {
     if (MBeanServerFactory.findMBeanServer(null).size() > 0) {
       mbeanServer = MBeanServerFactory.findMBeanServer(null).get(0);
     } else {
       mbeanServer = MBeanServerFactory.createMBeanServer();
     }
   }
   return mbeanServer;
 }
Ejemplo n.º 4
0
 public static MBeanServer getMBeanServer() {
   if (mbserver == null) {
     final ArrayList<MBeanServer> mbservers = MBeanServerFactory.findMBeanServer(null);
     if (mbservers.size() > 0) {
       mbserver = mbservers.get(0);
     }
     if (mbserver == null) {
       mbserver = MBeanServerFactory.createMBeanServer();
     }
   }
   return mbserver;
 }
Ejemplo n.º 5
0
  @Override
  @After
  public void tearDown() throws Exception {
    try {
      for (JMSContext jmsContext : contextSet) {
        jmsContext.close();
      }
    } catch (RuntimeException ignored) {
      // no-op
    } finally {
      contextSet.clear();
    }
    try {
      if (conn != null) conn.close();
    } catch (Exception e) {
      // no-op
    }

    namingContext.close();
    jmsServer.stop();
    server = null;
    cf = null;
    jmsServer = null;

    namingContext = null;

    MBeanServerFactory.releaseMBeanServer(mbeanServer);

    mbeanServer = null;

    ServiceUtils.setTransactionManager(null);

    super.tearDown();
  }
Ejemplo n.º 6
0
  /**
   * Returns the platform {@link javax.management.MBeanServer MBeanServer}. On the first call to
   * this method, it first creates the platform <tt>MBeanServer</tt> by calling the {@link
   * javax.management.MBeanServerFactory#createMBeanServer MBeanServerFactory.createMBeanServer}
   * method and registers the platform MXBeans in this platform <tt>MBeanServer</tt> using the <a
   * href="#MXBeanNames">MXBean names</a> defined in the class description. This method, in
   * subsequent calls, will simply return the initially created platform <tt>MBeanServer</tt>.
   *
   * <p>MXBeans that get created and destroyed dynamically, for example, memory {@link
   * MemoryPoolMXBean pools} and {@link MemoryManagerMXBean managers}, will automatically be
   * registered and deregistered into the platform <tt>MBeanServer</tt>.
   *
   * <p>If the system property <tt>javax.management.builder.initial</tt> is set, the platform
   * <tt>MBeanServer</tt> creation will be done by the specified {@link
   * javax.management.MBeanServerBuilder}.
   *
   * <p>It is recommended that this platform MBeanServer also be used to register other application
   * managed beans besides the platform MXBeans. This will allow all MBeans to be published through
   * the same <tt>MBeanServer</tt> and hence allow for easier network publishing and discovery. Name
   * conflicts with the platform MXBeans should be avoided.
   *
   * @return the platform <tt>MBeanServer</tt>; the platform MXBeans are registered into the
   *     platform <tt>MBeanServer</tt> at the first time this method is called.
   * @exception SecurityException if there is a security manager and the caller does not have the
   *     permission required by {@link javax.management.MBeanServerFactory#createMBeanServer}.
   * @see javax.management.MBeanServerFactory
   * @see javax.management.MBeanServerFactory#createMBeanServer
   */
  public static synchronized MBeanServer getPlatformMBeanServer() {
    SecurityManager sm = System.getSecurityManager();
    if (sm != null) {
      Permission perm = new MBeanServerPermission("createMBeanServer");
      sm.checkPermission(perm);
    }

    if (platformMBeanServer == null) {
      platformMBeanServer = MBeanServerFactory.createMBeanServer();
      for (PlatformComponent pc : PlatformComponent.values()) {
        List<? extends PlatformManagedObject> list = pc.getMXBeans(pc.getMXBeanInterface());
        for (PlatformManagedObject o : list) {
          // Each PlatformComponent represents one management
          // interface. Some MXBean may extend another one.
          // The MXBean instances for one platform component
          // (returned by pc.getMXBeans()) might be also
          // the MXBean instances for another platform component.
          // e.g. com.sun.management.GarbageCollectorMXBean
          //
          // So need to check if an MXBean instance is registered
          // before registering into the platform MBeanServer
          if (!platformMBeanServer.isRegistered(o.getObjectName())) {
            addMXBean(platformMBeanServer, o);
          }
        }
      }
    }
    return platformMBeanServer;
  }
Ejemplo n.º 7
0
  public static void main(String[] args) throws Exception {
    // Instantiate the MBean server
    //
    System.out.println("Create the MBean server");
    MBeanServer mbs = MBeanServerFactory.createMBeanServer();

    // Get the JMX implementation version from the MBeanServerDelegateMBean
    //
    System.out.println("Get the JMX implementation version");
    ObjectName mbsdName = new ObjectName("JMImplementation:type=MBeanServerDelegate");
    String mbsdAttribute = "ImplementationVersion";
    String mbsdVersion = (String) mbs.getAttribute(mbsdName, mbsdAttribute);

    // Display JMX implementation version and JVM implementation version
    //
    System.out.println("JMX implementation version          = " + mbsdVersion);
    System.out.println("Java Runtime implementation version = " + args[0]);

    // Check JMX implementation version vs. JVM implementation version
    //
    if (!mbsdVersion.equals(args[0]))
      throw new IllegalArgumentException(
          "JMX and Java Runtime implementation versions do not match!");
    // Test OK!
    //
    System.out.println("JMX and Java Runtime implementation " + "versions match!");
    System.out.println("Bye! Bye!");
  }
  public void export() {
    try {
      // 创建一个MBeanServer
      MBeanServer mbs = MBeanServerFactory.createMBeanServer(DOMAIN);
      // MBeanServer mbs = MBeanServerFactory.createMBeanServer();//不能在jconsole中使用
      // MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();//可在jconsole中使用
      // 用MBeanServer注册LoginStatsMBean
      // MBeanServer.registerMBean(Object,ObjectName)方法使用的参数有两个:一个是MBean实现的一个实例;另一个是类型ObjectName的一个对象-它用于唯一地标识该MBean
      mbs.registerMBean(new Status(), new ObjectName(MBeanName));

      // 存取该JMX服务的URL:
      JMXServiceURL url =
          new JMXServiceURL("rmi", HOST, JMX_PORT, "/jndi/rmi://" + HOST + ":" + 1099 + "/app");
      // start()和stop()来启动和停止 JMXConnectorServer
      JMXConnectorServer jmxServer =
          JMXConnectorServerFactory.newJMXConnectorServer(url, null, mbs);
      serviceUrl = url.toString();
      // 在RMI上注册
      LocateRegistry.createRegistry(JMX_PORT);
      jmxServer.start();

      // 创建适配器,用于能够通过浏览器访问MBean
      //            HtmlAdaptorServer adapter = new HtmlAdaptorServer();
      //            adapter.setPort(9797);
      //            mbs.registerMBean(adapter, new ObjectName(
      //                    "MyappMBean:name=htmladapter,port=9797"));
      //            adapter.start();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  private int getHttpsPort() {
    try {
      MBeanServer mBeanServer = MBeanServerFactory.findMBeanServer(null).get(0);
      QueryExp query = Query.eq(Query.attr("Scheme"), Query.value("https"));
      Set<ObjectName> objectNames = mBeanServer.queryNames(null, query);

      if (objectNames != null && objectNames.size() > 0) {
        for (ObjectName objectName : objectNames) {
          String name = objectName.toString();
          if (name.indexOf("port=") > -1) {
            String[] parts = name.split("port=");
            String port = parts[1];
            try {
              int portNum = Integer.parseInt(port);
              return portNum;
            } catch (NumberFormatException e) {
              logger.error("Error parsing https port:" + port);
              return -1;
            }
          }
        }
      }
    } catch (Throwable t) {
      logger.error("Error getting https port:", t);
    }

    return -1;
  }
  @Override
  public void init() throws ServletException {

    LOG.info("enter--init");

    super.init();
    ArrayList<MBeanServer> serverList = MBeanServerFactory.findMBeanServer(null);
    MBeanServer serverHelloWorld = (MBeanServer) serverList.get(0);
    final HelloWorldService helloWorldMBean = new HelloWorldService();
    ObjectName helloWorld = null;
    try {
      helloWorld = new ObjectName("jboss.jmx:name=HelloJMX");
      serverHelloWorld.registerMBean(helloWorldMBean, helloWorld);
    } catch (MalformedObjectNameException e) {
      e.printStackTrace();
    } catch (NullPointerException e) {
      e.printStackTrace();
    } catch (InstanceAlreadyExistsException e) {
      e.printStackTrace();
    } catch (MBeanRegistrationException e) {
      e.printStackTrace();
    } catch (NotCompliantMBeanException e) {
      e.printStackTrace();
    }

    LOG.info("exit--init");
  }
 @Test
 public void checkNotRegistered() throws MalformedObjectNameException {
   MBeanServer jolokiaServer = JolokiaMBeanServerUtil.getJolokiaMBeanServer();
   Assert.assertNotEquals(ManagementFactory.getPlatformMBeanServer(), jolokiaServer);
   for (MBeanServer server : MBeanServerFactory.findMBeanServer(null)) {
     Assert.assertNotEquals(server, jolokiaServer);
   }
 }
Ejemplo n.º 12
0
  /**
   * Returns an MBeanServer that simulates the JBossAS MBeanServer.
   *
   * @return MBeanServer instance
   */
  public MBeanServer getJBossMBeanServer() {
    if (dummyJBossMBeanServer == null) {
      dummyJBossMBeanServer = MBeanServerFactory.createMBeanServer("jboss");
      MBeanServerLocator.setJBoss(dummyJBossMBeanServer);
    }

    return dummyJBossMBeanServer;
  }
Ejemplo n.º 13
0
/**
 * Start a server, connect a client, add/remove listeners, close client, stop server. Check that VM
 * exits in less than 5 secs.
 */
public class RMIExitTest {
  private static final MBeanServer mbs = MBeanServerFactory.createMBeanServer();
  public static long exitStartTime = 0;

  public static void main(String[] args) {
    System.out.println("Start test");
    Runtime.getRuntime().addShutdownHook(new TimeChecker());
    test();
    exitStartTime = System.currentTimeMillis();
    System.out.println("End test");
  }

  private static void test() {
    try {
      JMXServiceURL u = new JMXServiceURL("rmi", null, 0);
      JMXConnectorServer server;
      JMXServiceURL addr;
      JMXConnector client;
      MBeanServerConnection mserver;

      final ObjectName delegateName = new ObjectName("JMImplementation:type=MBeanServerDelegate");
      final NotificationListener dummyListener =
          new NotificationListener() {
            public void handleNotification(Notification n, Object o) {
              // do nothing
              return;
            }
          };

      server = JMXConnectorServerFactory.newJMXConnectorServer(u, null, mbs);
      server.start();

      addr = server.getAddress();
      client = JMXConnectorFactory.newJMXConnector(addr, null);
      client.connect(null);

      mserver = client.getMBeanServerConnection();
      String s1 = "1";
      String s2 = "2";
      String s3 = "3";

      mserver.addNotificationListener(delegateName, dummyListener, null, s1);
      mserver.addNotificationListener(delegateName, dummyListener, null, s2);
      mserver.addNotificationListener(delegateName, dummyListener, null, s3);

      mserver.removeNotificationListener(delegateName, dummyListener, null, s3);
      mserver.removeNotificationListener(delegateName, dummyListener, null, s2);
      mserver.removeNotificationListener(delegateName, dummyListener, null, s1);
      client.close();

      server.stop();
    } catch (Exception e) {
      System.out.println(e);
      e.printStackTrace();
      System.exit(1);
    }
  }
}
 /**
  * Returns a string array containing the default JMX domains of all available MBeanServers in this
  * JVM.
  *
  * @return a string array of JMX default domains
  */
 public static String[] getMBeanServerDomains() {
   Set<String> domains = new HashSet<String>();
   for (MBeanServer mbs : MBeanServerFactory.findMBeanServer(null)) {
     String domain = mbs.getDefaultDomain();
     if (domain == null) domain = "DefaultDomain";
     domains.add(domain);
   }
   return domains.toArray(new String[domains.size()]);
 }
  private MBeanServer findOrCreateMBeanServer() {
    MBeanServer mbeanServer = null;

    ArrayList<MBeanServer> serverArr = MBeanServerFactory.findMBeanServer(null);
    if (serverArr.size() > 1) log.warn("Multiple MBeanServer instances: " + serverArr);

    if (serverArr.size() > 0) {
      mbeanServer = serverArr.get(0);
      log.debug("Found MBeanServer: " + mbeanServer.getDefaultDomain());
    }

    if (mbeanServer == null) {
      log.debug("No MBeanServer, create one ...");
      mbeanServer = MBeanServerFactory.createMBeanServer();
    }

    return mbeanServer;
  }
Ejemplo n.º 16
0
  public static void main(String[] args) throws Exception {
    System.out.println(
        ">>> Test how for the MBeanServerInvocationHandler to "
            + "unwrap a user specific exception.");

    final MBeanServer mbs = MBeanServerFactory.newMBeanServer();
    final ObjectName name = new ObjectName("a:b=c");
    mbs.registerMBean(new Test(), name);
    TestMBean proxy =
        (TestMBean)
            MBeanServerInvocationHandler.newProxyInstance(mbs, name, TestMBean.class, false);

    // test the method "getter"
    System.out.println(">>> Test the method getter to get an IOException.");
    try {
      proxy.getIOException();
    } catch (IOException e) {
      System.out.println(">>> Test passed: got expected exception:");
      // e.printStackTrace(System.out);
    } catch (Throwable t) {
      System.out.println(">>> Test failed: got wrong exception:");
      t.printStackTrace(System.out);

      throw new RuntimeException("Did not get an expected IOException.");
    }

    // test the method "setter"
    System.out.println(">>> Test the method setter to get a RuntimeException.");
    try {
      proxy.setRuntimeException("coucou");
    } catch (UnsupportedOperationException ue) {
      System.out.println(">>> Test passed: got expected exception:");
      // ue.printStackTrace(System.out);
    } catch (Throwable t) {
      System.out.println(">>> Test failed: got wrong exception:");
      t.printStackTrace(System.out);

      throw new RuntimeException("Did not get an expected Runtimeexception.");
    }

    // test the method "invoke"
    System.out.println(">>> Test the method invoke to get an Error.");
    try {
      proxy.invokeError();
    } catch (AssertionError ae) {
      System.out.println(">>> Test passed: got expected exception:");
      // ue.printStackTrace(System.out);
    } catch (Throwable t) {
      System.out.println(">>> Test failed: got wrong exception:");
      t.printStackTrace(System.out);

      throw new RuntimeException("Did not get an expected Error.");
    }
  }
Ejemplo n.º 17
0
 /*
  * (non-Javadoc)
  *
  * @see org.mule.umo.lifecycle.Initialisable#initialise()
  */
 public void initialise() throws InitialisationException {
   try {
     mBeanServer = (MBeanServer) MBeanServerFactory.findMBeanServer(null).get(0);
     final ObjectName objectName = jmxSupport.getObjectName(JMX_OBJECT_NAME);
     // unregister existing Log4j MBean first if required
     unregisterMBeansIfNecessary();
     mBeanServer.registerMBean(new HierarchyDynamicMBean(), objectName);
   } catch (Exception e) {
     throw new InitialisationException(CoreMessages.failedToStart("JMX Agent"), e, this);
   }
 }
  public void clearCache(String username) {
    try {

      ObjectName jaasMgr = new ObjectName("jboss.as:subsystem=security,security-domain=cosmDomain");
      Object[] params = {username};
      String[] signature = {"java.lang.String"};
      MBeanServer server = (MBeanServer) MBeanServerFactory.findMBeanServer(null).get(0);
      server.invoke(jaasMgr, "flushCache", params, signature);
    } catch (Exception ex) {
      LOG.warning(ex.getMessage());
    }
  }
Ejemplo n.º 19
0
  protected MBeanServer findOrCreateMBeanServer() {

    // return platform mbean server if the option is specified.
    if (usePlatformMBeanServer) {
      return ManagementFactory.getPlatformMBeanServer();
    }

    // look for the first mbean server that has match default domain name
    List<MBeanServer> servers = MBeanServerFactory.findMBeanServer(null);

    for (MBeanServer server : servers) {
      LOG.debug("Found MBeanServer with default domain {}", server.getDefaultDomain());

      if (mBeanServerDefaultDomain.equals(server.getDefaultDomain())) {
        return server;
      }
    }

    // create a mbean server with the given default domain name
    return MBeanServerFactory.createMBeanServer(mBeanServerDefaultDomain);
  }
  @Override
  public MBeanServer getMBeanServer(String domain) {
    if (mbs == null) {
      mbs = MBeanServerFactory.createMBeanServer(domain);
      Properties props = getProperties();

      if (props.containsKey("com.sun.management.jmxremote")) {
        startRmiConnector(mbs);
      }
    }
    return mbs;
  }
  /**
   * Create DataSource, there are two ways, if the application has a security policy then it will
   * create from that policy properties, otherwise it will use <code>connection.datasource</code>
   * property defined in <code>hibernate.cfg.xml</code> file.
   *
   * @param props
   * @return DataSource
   * @throws Exception
   */
  @SuppressWarnings("unchecked")
  private DataSource createDataSource(Properties props) throws Exception {
    try {
      Properties dsProperties = null;
      InitialContext ic = new InitialContext();
      Subject subject = (Subject) ic.lookup(SECURITY_SUBJECT);
      ObjectName oname = findObjectName(ic, props);
      MBeanServer server = null;
      List servers = MBeanServerFactory.findMBeanServer(null);
      if (servers.size() > 0) {
        if (servers.size() > 1) {
          //	Iterates over servers list untill AonMainDeployerMBean is found.
          //	TODO Isolate application server.
          Iterator it = servers.iterator();
          while (it.hasNext()) {
            server = (MBeanServer) it.next();
            try {
              ObjectName jbossname = new ObjectName("jboss.admin:service=AonMainDeployer");
              server.getObjectInstance(jbossname);
              break;
            } catch (Exception e) {
            }
          }
        } else {
          server = (MBeanServer) servers.get(0);
        }
      }
      if (subject == null) throw new NamingException("");

      Principal principal = subject.getPrincipals().iterator().next();
      dsProperties =
          (Properties)
              server.invoke(
                  oname,
                  DSMD_METHOD_NAME,
                  new Object[] {principal},
                  new String[] {Principal.class.getName()});
      return BasicDataSourceFactory.createDataSource(dsProperties);
    } catch (NamingException ne) {
      String jndiName = props.getProperty(Environment.DATASOURCE);
      DataSource ds;
      try {
        ds = (DataSource) NamingHelper.getInitialContext(props).lookup(jndiName);
      } catch (NamingException e) {
        throw new HibernateException("Could not find datasource", e);
      }
      if (ds == null) {
        throw new HibernateException("Could not find datasource: " + jndiName);
      }
      return ds;
    }
  }
  /** @throws Exception */
  private void setupServer1() throws Exception {
    Configuration configuration = createConfigServer(1, 2);

    JMSConfigurationImpl jmsconfig = new JMSConfigurationImpl();

    mBeanServer1 = MBeanServerFactory.createMBeanServer();
    server1 =
        addServer(
            ActiveMQServers.newActiveMQServer(configuration, mBeanServer1, enablePersistence()));
    jmsServer1 = new JMSServerManagerImpl(server1, jmsconfig);
    context1 = new InVMNamingContext();
    jmsServer1.setRegistry(new JndiBindingRegistry(context1));
  }
Ejemplo n.º 23
0
  public static void main(String[] args) throws Exception {
    Class thisClass = MethodResultTest.class;
    Class exoticClass = Exotic.class;
    String exoticClassName = Exotic.class.getName();
    ClassLoader testClassLoader = thisClass.getClassLoader();
    if (!(testClassLoader instanceof URLClassLoader)) {
      System.out.println("TEST INVALID: Not loaded by a " + "URLClassLoader: " + testClassLoader);
      System.exit(1);
    }

    URLClassLoader tcl = (URLClassLoader) testClassLoader;
    URL[] urls = tcl.getURLs();
    ClassLoader shadowLoader =
        new ShadowLoader(
            urls,
            testClassLoader,
            new String[] {
              exoticClassName, ExoticMBeanInfo.class.getName(), ExoticException.class.getName()
            });
    Class cl = shadowLoader.loadClass(exoticClassName);
    if (cl == exoticClass) {
      System.out.println(
          "TEST INVALID: Shadow class loader loaded " + "same class as test class loader");
      System.exit(1);
    }
    Thread.currentThread().setContextClassLoader(shadowLoader);

    ObjectName on = new ObjectName("a:b=c");
    MBeanServer mbs = MBeanServerFactory.newMBeanServer();
    mbs.createMBean(Thing.class.getName(), on);

    final String[] protos = {"rmi", "iiop", "jmxmp"};

    boolean ok = true;
    for (int i = 0; i < protos.length; i++) {
      try {
        ok &= test(protos[i], mbs, on);
        System.out.println();
      } catch (Exception e) {
        System.out.println("TEST FAILED WITH EXCEPTION:");
        e.printStackTrace(System.out);
        ok = false;
      }
    }

    if (ok) System.out.println("Test passed");
    else {
      System.out.println("TEST FAILED");
      System.exit(1);
    }
  }
Ejemplo n.º 24
0
  /** Test notifying job state to a NotificationListener. */
  public void testNotifyState() throws Exception {
    /** Fixture Stateful */
    class MyStateful extends MockStateful {
      StateListener jsl;

      public void addStateListener(StateListener listener) {
        jsl = listener;
        listener.jobStateChange(new StateEvent(this, JobState.READY, null));
      }

      public void removeStateListener(StateListener listener) {}

      public void foo() {
        jsl.jobStateChange(new StateEvent(this, JobState.COMPLETE, null));
      }
    };
    MyStateful myJob = new MyStateful();

    MyNotLis myNotLis = new MyNotLis();

    ServerContext serverContext = new ServerContextImpl(myJob, sm, new OurHierarchicalRegistry());

    // create and register MBean.
    OddjobMBean ojmb =
        new OddjobMBean(
            myJob, OddjobMBeanFactory.objectName(0), new OurServerSession(), serverContext);

    ObjectName on = OddjobMBeanFactory.objectName(0);

    MBeanServer mbs = MBeanServerFactory.createMBeanServer();
    mbs.registerMBean(ojmb, on);

    // add notification listener.
    mbs.addNotificationListener(on, myNotLis, null, null);

    // check null state to begin with
    assertEquals("number", 0, myNotLis.getNum());

    // change state.
    myJob.foo();

    // check state
    assertEquals("number", 1, myNotLis.getNum());
    assertEquals("source", on, myNotLis.getNotification(0).getSource());
    assertEquals(
        "type",
        StatefulHandlerFactory.STATE_CHANGE_NOTIF_TYPE,
        myNotLis.getNotification(0).getType());

    mbs.unregisterMBean(on);
  }
  @SuppressWarnings("deprecation")
  @Override
  protected void setUp() throws Exception {
    super.setUp();
    // load it up with example1.ldif
    String fileName = targetDir + "ldap" + fs + "example1.ldif";
    boolean op = util.addLDIF(serverHost, port, adminDN, adminPW, new File(fileName).toURL());
    assertTrue(op);

    // Setup a configuration
    Configuration.setConfiguration(
        new Configuration() {
          @SuppressWarnings("unchecked")
          @Override
          public AppConfigurationEntry[] getAppConfigurationEntry(String cname) {
            String name = LdapLoginModule.class.getName();
            HashMap options = new HashMap();

            options.put("java.naming.factory.initial", ldapCtxFactory);
            options.put("java.naming.provider.url", "ldap://localhost:10389/");
            options.put("java.naming.security.authentication", "simple");
            options.put("principalDNPrefix", "uid=");
            options.put("uidAttributeID", "userid");
            options.put("roleAttributeID", "roleName");
            options.put("principalDNSuffix", ",ou=People,dc=jboss,dc=org");
            options.put("rolesCtxDN", "cn=JBossSX Tests,ou=Roles,dc=jboss,dc=org");
            options.put(Context.SECURITY_CREDENTIALS, "somecrazyencryptedstring");
            options.put("jaasSecurityDomain", oname);

            AppConfigurationEntry ace =
                new AppConfigurationEntry(
                    name, AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, options);
            AppConfigurationEntry[] entry = {ace};
            return entry;
          }

          @Override
          public void refresh() {}
        });

    // Setup MBeanServer
    MBeanServer jbossMBeanServer = MBeanServerFactory.createMBeanServer("jboss");
    MBeanServerLocator.setJBoss(jbossMBeanServer);
    try {
      Test test = new Test();
      jbossMBeanServer.registerMBean(test, new ObjectName(oname));
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Ejemplo n.º 26
0
  private static Class<?> load(ClassLoader without, String className)
      throws ClassNotFoundException {
    final List<MBeanServer> mbsList = MBeanServerFactory.findMBeanServer(null);

    for (MBeanServer mbs : mbsList) {
      ClassLoaderRepository clr = mbs.getClassLoaderRepository();
      try {
        return clr.loadClassWithout(without, className);
      } catch (ClassNotFoundException e) {
        // OK : Try with next one...
      }
    }
    throw new ClassNotFoundException(className);
  }
Ejemplo n.º 27
0
  public static void main(String[] args) {
    try {
      // Instantiate the MBean server
      //
      System.out.println("\nCreate the MBean server");
      MBeanServer mbs = MBeanServerFactory.createMBeanServer();

      // Environment map
      //
      System.out.println("\nInitialize the environment map");
      HashMap env = new HashMap();

      // Provide SSL-based RMI socket factories.
      //
      SslRMIClientSocketFactory csf = new SslRMIClientSocketFactory();
      SslRMIServerSocketFactory ssf = new SslRMIServerSocketFactory();
      env.put(RMIConnectorServer.RMI_CLIENT_SOCKET_FACTORY_ATTRIBUTE, csf);
      env.put(RMIConnectorServer.RMI_SERVER_SOCKET_FACTORY_ATTRIBUTE, ssf);

      // Provide the password file used by the connector server to
      // perform user authentication. The password file is a properties
      // based text file specifying username/password pairs. This
      // properties based password authenticator has been implemented
      // using the JMXAuthenticator interface and is passed to the
      // connector through the "jmx.remote.authenticator" property
      // in the map.
      //
      // This property is implementation-dependent and might not be
      // supported by all implementations of the JMX Remote API.
      //
      env.put("jmx.remote.x.password.file", "config" + File.separator + "password.properties");

      // Create an RMI connector server
      //
      System.out.println("\nCreate an RMI connector server");
      JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:9999/server");
      JMXConnectorServer cs = JMXConnectorServerFactory.newJMXConnectorServer(url, env, mbs);

      // Start the RMI connector server
      //
      System.out.println("\nStart the RMI connector server");
      cs.start();
      System.out.println("\nRMI connector server successfully started");
      System.out.println("\nWaiting for incoming connections...");
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  private void checkNoTwoShardsUseTheSameIndexDir() throws Exception {
    Map<String, Set<String>> indexDirToShardNamesMap = new HashMap<String, Set<String>>();

    List<MBeanServer> servers = new LinkedList<MBeanServer>();
    servers.add(ManagementFactory.getPlatformMBeanServer());
    servers.addAll(MBeanServerFactory.findMBeanServer(null));
    for (final MBeanServer server : servers) {
      Set<ObjectName> mbeans = new HashSet<ObjectName>();
      mbeans.addAll(server.queryNames(null, null));
      for (final ObjectName mbean : mbeans) {
        Object value;
        Object indexDir;
        Object name;

        try {
          if (((value = server.getAttribute(mbean, "category")) != null
                  && value.toString().equals(Category.CORE.toString()))
              && ((indexDir = server.getAttribute(mbean, "coreName")) != null)
              && ((indexDir = server.getAttribute(mbean, "indexDir")) != null)
              && ((name = server.getAttribute(mbean, "name")) != null)) {
            if (!indexDirToShardNamesMap.containsKey(indexDir.toString())) {
              indexDirToShardNamesMap.put(indexDir.toString(), new HashSet<String>());
            }
            indexDirToShardNamesMap.get(indexDir.toString()).add(name.toString());
          }
        } catch (Exception e) {
          // ignore, just continue - probably a "category" or "source" attribute
          // not found
        }
      }
    }

    assertTrue(
        "Something is broken in the assert for no shards using the same indexDir - probably something was changed in the attributes published in the MBean of "
            + SolrCore.class.getSimpleName()
            + " : "
            + indexDirToShardNamesMap,
        indexDirToShardNamesMap.size() > 0);
    for (Entry<String, Set<String>> entry : indexDirToShardNamesMap.entrySet()) {
      if (entry.getValue().size() > 1) {
        fail(
            "We have shards using the same indexDir. E.g. shards "
                + entry.getValue().toString()
                + " all use indexDir "
                + entry.getKey());
      }
    }
  }
Ejemplo n.º 29
0
  public static final int getServerPort() {
    try {
      MBeanServer mBeanServer = MBeanServerFactory.findMBeanServer(null).get(0);
      ObjectName name = new ObjectName("Catalina", "type", "Server");
      Object server = mBeanServer.getAttribute(name, "managedResource");

      Object service = Array.get(server.getClass().getMethod("findServices").invoke(server), 0);
      Object connector =
          Array.get(service.getClass().getMethod("findConnectors").invoke(service), 0);

      int port = (Integer) connector.getClass().getMethod("getPort").invoke(connector);
      return port;
    } catch (Exception ex) {
      log.error("could not determine server port, using 8080");
      return 8080;
    }
  }
Ejemplo n.º 30
0
  public static void main(String[] args) throws Exception {
    System.out.println(
        "Test that target MBean class loader is used " + "before JMX Remote API class loader");

    ClassLoader jmxRemoteClassLoader = JMXServiceURL.class.getClassLoader();
    if (jmxRemoteClassLoader == null) {
      System.out.println(
          "JMX Remote API loaded by bootstrap " + "class loader, this test is irrelevant");
      return;
    }
    if (!(jmxRemoteClassLoader instanceof URLClassLoader)) {
      System.out.println("TEST INVALID: JMX Remote API not loaded by " + "URLClassLoader");
      System.exit(1);
    }

    URLClassLoader jrcl = (URLClassLoader) jmxRemoteClassLoader;
    URL[] urls = jrcl.getURLs();
    PrivateMLet mlet = new PrivateMLet(urls, null, false);
    Class shadowClass = mlet.loadClass(JMXServiceURL.class.getName());
    if (shadowClass == JMXServiceURL.class) {
      System.out.println("TEST INVALID: MLet got original " + "JMXServiceURL not shadow");
      System.exit(1);
    }

    MBeanServer mbs = MBeanServerFactory.newMBeanServer();
    mbs.registerMBean(mlet, mletName);

    final String[] protos = {"rmi", "iiop", "jmxmp"};
    boolean ok = true;
    for (int i = 0; i < protos.length; i++) {
      try {
        ok &= test(protos[i], mbs);
      } catch (Exception e) {
        System.out.println("TEST FAILED WITH EXCEPTION:");
        e.printStackTrace(System.out);
        ok = false;
      }
    }

    if (ok) System.out.println("Test passed");
    else {
      System.out.println("TEST FAILED");
      System.exit(1);
    }
  }