Example usage for javax.management MBeanServerFactory createMBeanServer

List of usage examples for javax.management MBeanServerFactory createMBeanServer

Introduction

In this page you can find the example usage for javax.management MBeanServerFactory createMBeanServer.

Prototype

public static MBeanServer createMBeanServer(String domain) 

Source Link

Document

Return a new object implementing the MBeanServer interface with the specified default domain name.

Usage

From source file:com.app.server.Main.java

/**
 * This is the start of the all the services in web server
 * @param args/*from w ww. j a va2  s  . c o  m*/
 * @throws IOException 
 * @throws SAXException 
 */
public static void main(String[] args) throws IOException, SAXException {

    long startTime = System.currentTimeMillis();
    Hashtable urlClassLoaderMap = new Hashtable();
    Hashtable executorServicesMap = new Hashtable();
    Hashtable ataMap = new Hashtable<String, ATAConfig>();
    Hashtable messagingClassMap = new Hashtable();
    ConcurrentHashMap servletMapping = new ConcurrentHashMap();
    Vector deployerList = new Vector(), serviceList = new Vector();
    DigesterLoader serverdigesterLoader = DigesterLoader.newLoader(new FromXmlRulesModule() {
        protected void loadRules() {
            // TODO Auto-generated method stub
            try {
                loadXMLRules(new InputSource(new FileInputStream("./config/serverconfig-rules.xml")));
            } catch (FileNotFoundException e) {
                log.error("Error in loading the xml rules ./config/serverconfig-rules.xml", e);
                // TODO Auto-generated catch block
                //e.printStackTrace();
            }

        }
    });
    Digester serverdigester = serverdigesterLoader.newDigester();
    final ServerConfig serverconfig = (ServerConfig) serverdigester
            .parse(new InputSource(new FileInputStream("./config/serverconfig.xml")));

    //log.info(messagingconfig);
    ////log.info(serverconfig.getDeploydirectory());
    PropertyConfigurator.configure("log4j.properties");
    /*MemcachedClient cache=new MemcachedClient(
        new InetSocketAddress("localhost", 1000));*/

    // Store a value (async) for one hour
    //c.set("someKey", 36, new String("arun"));
    // Retrieve a value.        
    System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.apache.naming.java.javaURLContextFactory");
    System.setProperty(Context.URL_PKG_PREFIXES, "org.apache.naming");
    ExecutorService executor = java.util.concurrent.Executors.newCachedThreadPool();

    MBeanServer mbs = MBeanServerFactory.createMBeanServer("singham");
    ObjectName name = null;
    try {
        mbs.registerMBean(serverconfig, new ObjectName("com.app.server:type=serverinfo"));
    } catch (Exception e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    /*try {
       name = new ObjectName("com.app.server:type=WarDeployer");
    } catch (MalformedObjectNameException e1) {
       // TODO Auto-generated catch block
       e1.printStackTrace();
    } 
            
    WarDeployer warDeployer=new WarDeployer(serverconfig.getDeploydirectory(),serverconfig.getFarmWarDir(),serverconfig.getClustergroup(),urlClassLoaderMap,executorServicesMap,messagingClassMap,servletMapping,messagingconfig,sessionObjects);
    warDeployer.setPriority(MIN_PRIORITY);
    try {
       mbs.registerMBean(warDeployer, name);
    } catch (InstanceAlreadyExistsException | MBeanRegistrationException
    | NotCompliantMBeanException e1) {
       // TODO Auto-generated catch block
       e1.printStackTrace();
    } 
            
    //warDeployer.start();
    executor.execute(warDeployer);*/

    final byte[] shutdownBt = new byte[50];
    /*WebServerRequestProcessor webserverRequestProcessor=new WebServer().new WebServerRequestProcessor(servletMapping,urlClassLoaderMap,serverSocketChannel,serverconfig.getDeploydirectory(),Integer.parseInt(serverconfig.getShutdownport()),1);
      webserverRequestProcessor.setPriority(MIN_PRIORITY);
    try {
       name = new ObjectName("com.app.server:type=WebServerRequestProcessor");
    } catch (MalformedObjectNameException e1) {
       // TODO Auto-generated catch block
       e1.printStackTrace();
    } 
            
    try {
       mbs.registerMBean(webserverRequestProcessor, name);
    } catch (InstanceAlreadyExistsException | MBeanRegistrationException
    | NotCompliantMBeanException e1) {
       // TODO Auto-generated catch block
       e1.printStackTrace();
    }
            
    //webserverRequestProcessor.start();
      executor.execute(webserverRequestProcessor);
            
            
      for(int i=0;i<10;i++){
       WebServerRequestProcessor webserverRequestProcessor1=new WebServer().new WebServerRequestProcessor(servletMapping,urlClassLoaderMap,serverSocketChannel,serverconfig.getDeploydirectory(),Integer.parseInt(serverconfig.getShutdownport()),2);
    webserverRequestProcessor1.setPriority(MIN_PRIORITY);
       try {
    name = new ObjectName("com.app.server:type=WebServerRequestProcessor"+(i+1));
       } catch (MalformedObjectNameException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
       } 
               
       try {
    mbs.registerMBean(webserverRequestProcessor1, name);
       } catch (InstanceAlreadyExistsException | MBeanRegistrationException
       | NotCompliantMBeanException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
       }
               
         executor.execute(webserverRequestProcessor1);
      }*/

    /*ExecutorServiceThread executorService=new ExecutorServiceThread(serverSocketChannelServices,executorServicesMap,Integer.parseInt(serverconfig.getShutdownport()),ataMap,urlClassLoaderMap,serverconfig.getDeploydirectory(),serverconfig.getServicesdirectory(),serverconfig.getEarservicesdirectory(),serverconfig.getNodesport());
            
    try {
       name = new ObjectName("com.app.services:type=ExecutorServiceThread");
    } catch (MalformedObjectNameException e1) {
       // TODO Auto-generated catch block
       e1.printStackTrace();
    } 
            
    try {
       mbs.registerMBean(executorService, name);
    } catch (InstanceAlreadyExistsException | MBeanRegistrationException
    | NotCompliantMBeanException e1) {
       // TODO Auto-generated catch block
       e1.printStackTrace();
    }
            
    //executorService.start();
    executor.execute(executorService);
            
            
    for(int i=0;i<10;i++){
       ExecutorServiceThread executorService1=new ExecutorServiceThread(serverSocketChannelServices,executorServicesMap,Integer.parseInt(serverconfig.getShutdownport()),ataMap,urlClassLoaderMap,serverconfig.getDeploydirectory(),serverconfig.getServicesdirectory(),serverconfig.getEarservicesdirectory(),serverconfig.getNodesport());
               
       try {
    name = new ObjectName("com.app.services:type=ExecutorServiceThread"+(i+1));
       } catch (MalformedObjectNameException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
       } 
               
       try {
    mbs.registerMBean(executorService1, name);
       } catch (InstanceAlreadyExistsException | MBeanRegistrationException
       | NotCompliantMBeanException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
       }
               
       executor.execute(executorService1);
    }*/

    /*WebServerHttpsRequestProcessor webserverHttpsRequestProcessor=new WebServer().new WebServerHttpsRequestProcessor(servletMapping,urlClassLoaderMap,Integer.parseInt(serverconfig.getHttpsport()),serverconfig.getDeploydirectory(),Integer.parseInt(serverconfig.getShutdownport()),serverconfig.getHttpscertificatepath(),serverconfig.getHttpscertificatepasscode(),1);
    try {
       name = new ObjectName("com.app.server:type=WebServerHttpsRequestProcessor");
    } catch (MalformedObjectNameException e1) {
       // TODO Auto-generated catch block
       e1.printStackTrace();
    } 
            
    try {
       mbs.registerMBean(webserverHttpsRequestProcessor, name);
    } catch (InstanceAlreadyExistsException | MBeanRegistrationException
    | NotCompliantMBeanException e1) {
       // TODO Auto-generated catch block
       e1.printStackTrace();
    }
    webserverHttpsRequestProcessor.setPriority(MAX_PRIORITY);
    //webserverRequestProcessor.start();
      executor.execute(webserverHttpsRequestProcessor);*/

    /* for(int i=0;i<2;i++){
        webserverHttpsRequestProcessor=new WebServer().new WebServerHttpsRequestProcessor(urlClassLoaderMap,Integer.parseInt(serverconfig.getHttpsport())+(i+1),serverconfig.getDeploydirectory(),Integer.parseInt(serverconfig.getShutdownport()),serverconfig.getHttpscertificatepath(),serverconfig.getHttpscertificatepasscode(),1);
              
      try {
    name = new ObjectName("com.app.server:type=WebServerHttpsRequestProcessor"+(i+1));
      } catch (MalformedObjectNameException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
      } 
              
      try {
    mbs.registerMBean(webserverHttpsRequestProcessor, name);
      } catch (InstanceAlreadyExistsException | MBeanRegistrationException
       | NotCompliantMBeanException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
      }
              
      executor.execute(webserverHttpsRequestProcessor);
    }*/

    /*ATAServer ataServer=new ATAServer(serverconfig.getAtaaddress(),serverconfig.getAtaport(),ataMap);
            
    try {
       name = new ObjectName("com.app.services:type=ATAServer");
    } catch (MalformedObjectNameException e1) {
       // TODO Auto-generated catch block
       e1.printStackTrace();
    } 
            
    try {
       mbs.registerMBean(ataServer, name);
    } catch (InstanceAlreadyExistsException | MBeanRegistrationException
    | NotCompliantMBeanException e1) {
       // TODO Auto-generated catch block
       e1.printStackTrace();
    }
            
            
    ataServer.start();*/

    /*ATAConfigClient ataClient=new ATAConfigClient(serverconfig.getAtaaddress(),serverconfig.getAtaport(),serverconfig.getServicesport(),executorServicesMap);
            
    try {
       name = new ObjectName("com.app.services:type=ATAConfigClient");
    } catch (MalformedObjectNameException e1) {
       // TODO Auto-generated catch block
       e1.printStackTrace();
    } 
            
    try {
       mbs.registerMBean(ataClient, name);
    } catch (InstanceAlreadyExistsException | MBeanRegistrationException
    | NotCompliantMBeanException e1) {
       // TODO Auto-generated catch block
       e1.printStackTrace();
    }
    ataClient.start();*/

    /*MessagingServer messageServer=new MessagingServer(serverconfig.getMessageport(),messagingClassMap);
            
    try {
       name = new ObjectName("com.app.messaging:type=MessagingServer");
    } catch (MalformedObjectNameException e1) {
       // TODO Auto-generated catch block
       e1.printStackTrace();
    } 
            
    try {
       mbs.registerMBean(messageServer, name);
    } catch (InstanceAlreadyExistsException | MBeanRegistrationException
    | NotCompliantMBeanException e1) {
       // TODO Auto-generated catch block
       e1.printStackTrace();
    }
    //messageServer.start();
    executor.execute(messageServer);*/

    /*RandomQueueMessagePicker randomqueuemessagepicker=new RandomQueueMessagePicker(messagingClassMap);
            
    try {
       name = new ObjectName("com.app.messaging:type=RandomQueueMessagePicker");
    } catch (MalformedObjectNameException e1) {
       // TODO Auto-generated catch block
       e1.printStackTrace();
    } 
            
    try {
       mbs.registerMBean(randomqueuemessagepicker, name);
    } catch (InstanceAlreadyExistsException | MBeanRegistrationException
    | NotCompliantMBeanException e1) {
       // TODO Auto-generated catch block
       e1.printStackTrace();
    }
            
    //randomqueuemessagepicker.start();
    executor.execute(randomqueuemessagepicker);*/

    /*RoundRobinQueueMessagePicker roundrobinqueuemessagepicker=new RoundRobinQueueMessagePicker(messagingClassMap);
            
    try {
       name = new ObjectName("com.app.messaging:type=RoundRobinQueueMessagePicker");
    } catch (MalformedObjectNameException e1) {
       // TODO Auto-generated catch block
       e1.printStackTrace();
    } 
            
    try {
       mbs.registerMBean(roundrobinqueuemessagepicker, name);
    } catch (InstanceAlreadyExistsException | MBeanRegistrationException
    | NotCompliantMBeanException e1) {
       // TODO Auto-generated catch block
       e1.printStackTrace();
    }
            
    //roundrobinqueuemessagepicker.start();
    executor.execute(roundrobinqueuemessagepicker);*/

    /*TopicMessagePicker topicpicker= new TopicMessagePicker(messagingClassMap);
            
    try {
       name = new ObjectName("com.app.messaging:type=TopicMessagePicker");
    } catch (MalformedObjectNameException e1) {
       // TODO Auto-generated catch block
       e1.printStackTrace();
    } 
            
    try {
       mbs.registerMBean(topicpicker, name);
    } catch (InstanceAlreadyExistsException | MBeanRegistrationException
    | NotCompliantMBeanException e1) {
       // TODO Auto-generated catch block
       e1.printStackTrace();
    }
    //topicpicker.start();
    executor.execute(topicpicker);*/

    try {
        name = new ObjectName(SARDeployer.OBJECT_NAME);
    } catch (Exception e) {
        log.error("Error in creating the object name " + SARDeployer.OBJECT_NAME, e);
        // TODO Auto-generated catch block
        //e1.printStackTrace();
    }
    log.info(System.getProperty("user.dir"));
    try {
        mbs.createMBean("com.app.server.SARDeployer", name);
        mbs.invoke(name, "init", new Object[] { deployerList }, new String[] { Vector.class.getName() });
        mbs.invoke(name, "init", new Object[] { serviceList, serverconfig, mbs }, new String[] {
                Vector.class.getName(), ServerConfig.class.getName(), MBeanServer.class.getName() });
        mbs.invoke(name, "start", null, null);
        mbs.invoke(name, "deploy",
                new Object[] {
                        new URL("file:///" + new File("").getAbsolutePath() + "/config/mbean-service.xml") },
                new String[] { URL.class.getName() });
        /*name=new ObjectName("com.app.server:type=deployer,service=WARDeployer");
        mbs.invoke(name, "deploy", new Object[]{new URL("file:///"+serverconfig.getDeploydirectory()+"/TestDollar2.war")}, new String[]{URL.class.getName()});
        mbs.invoke(name, "deploy", new Object[]{new URL("file:///"+serverconfig.getDeploydirectory()+"/StrutsProj.war")}, new String[]{URL.class.getName()});*/
        //mbs.registerMBean("", name);
    } catch (Exception ex) {
        log.error("Error in SAR DEPLOYER ", ex);
        // TODO Auto-generated catch block
        //e1.printStackTrace();
    }

    //scanner.deployPackages(new File[]{new File(serverconfig.getDeploydirectory()+"/AppServer.war")});

    try {
        new NodeResourceReceiver(mbs).start();
    } catch (Exception ex) {
        log.error("Node Receiver start", ex);
        //e2.printStackTrace();
    }
    long endTime = System.currentTimeMillis();
    log.info("Server started in " + ((endTime - startTime) / 1000) + " seconds");
    /*try {
       mbs.invoke(name, "startDeployer", null, null);
    } catch (InstanceNotFoundException e1) {
       // TODO Auto-generated catch block
       e1.printStackTrace();
    } catch (ReflectionException e1) {
       // TODO Auto-generated catch block
       e1.printStackTrace();
    } catch (MBeanException e1) {
       // TODO Auto-generated catch block
       e1.printStackTrace();
    }
    */
    /*JarDeployer jarDeployer=new JarDeployer(registry,serverconfig.getServicesdirectory(), serverconfig.getServiceslibdirectory(),serverconfig.getCachedir(),executorServicesMap, urlClassLoaderMap);
    try {
       name = new ObjectName("com.app.server:type=JarDeployer");
    } catch (MalformedObjectNameException e1) {
       // TODO Auto-generated catch block
       e1.printStackTrace();
    } 
            
    try {
       mbs.registerMBean(jarDeployer, name);
    } catch (InstanceAlreadyExistsException | MBeanRegistrationException
    | NotCompliantMBeanException e1) {
       // TODO Auto-generated catch block
       e1.printStackTrace();
    }
            
    //jarDeployer.start();
    executor.execute(jarDeployer);*/

    /*EARDeployer earDeployer=new EARDeployer(registry,serverconfig.getEarservicesdirectory(),serverconfig.getDeploydirectory(),executorServicesMap, urlClassLoaderMap,serverconfig.getCachedir(),warDeployer);
    try {
       name = new ObjectName("com.app.server:type=EARDeployer");
    } catch (MalformedObjectNameException e1) {
       // TODO Auto-generated catch block
       e1.printStackTrace();
    } 
            
    try {
       mbs.registerMBean(earDeployer, name);
    } catch (InstanceAlreadyExistsException | MBeanRegistrationException
    | NotCompliantMBeanException e1) {
       // TODO Auto-generated catch block
       e1.printStackTrace();
    }
            
    //earDeployer.start();
    executor.execute(earDeployer);*/

    /*JVMConsole jvmConsole=new JVMConsole(Integer.parseInt(serverconfig.getJvmConsolePort()));
            
    try {
       name = new ObjectName("com.app.server:type=JVMConsole");
    } catch (MalformedObjectNameException e1) {
       // TODO Auto-generated catch block
       e1.printStackTrace();
    } 
            
    try {
       mbs.registerMBean(jvmConsole, name);
    } catch (InstanceAlreadyExistsException | MBeanRegistrationException
    | NotCompliantMBeanException e1) {
       // TODO Auto-generated catch block
       e1.printStackTrace();
    }
    executor.execute(jvmConsole);*/

    /*ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();
     XMLDeploymentScanner xmlDeploymentScanner =new XMLDeploymentScanner(serverconfig.getDeploydirectory(),serverconfig.getServiceslibdirectory());
    exec.scheduleAtFixedRate(xmlDeploymentScanner, 0, 1000, TimeUnit.MILLISECONDS);*/

    /*EmbeddedJMS embeddedJMS=null;
    try {
       embeddedJMS=new EmbeddedJMS();
       embeddedJMS.start();
    } catch (Exception ex) {
       // TODO Auto-generated catch block
       ex.printStackTrace();
    }   
             
     EJBDeployer ejbDeployer=new EJBDeployer(serverconfig.getServicesdirectory(),registry,Integer.parseInt(serverconfig.getServicesregistryport()),embeddedJMS);
    try {
       name = new ObjectName("com.app.server:type=EJBDeployer");
    } catch (MalformedObjectNameException e1) {
       // TODO Auto-generated catch block
       e1.printStackTrace();
    } 
            
    try {
       mbs.registerMBean(ejbDeployer, name);
    } catch (InstanceAlreadyExistsException | MBeanRegistrationException
    | NotCompliantMBeanException e1) {
       // TODO Auto-generated catch block
       e1.printStackTrace();
    }
            
    //jarDeployer.start();
    executor.execute(ejbDeployer);*/

    new Thread() {
        public void run() {
            try {
                ServerSocket serverSocket = new ServerSocket(Integer.parseInt(serverconfig.getShutdownport()));
                while (true) {
                    Socket sock = serverSocket.accept();
                    InputStream istream = sock.getInputStream();
                    istream.read(shutdownBt);
                    String shutdownStr = new String(shutdownBt);
                    String[] shutdownToken = shutdownStr.split("\r\n\r\n");
                    //log.info(shutdownStr);
                    if (shutdownToken[0].startsWith("shutdown WebServer")) {
                        synchronized (shutDownObject) {
                            shutDownObject.notifyAll();
                        }
                    }
                }
            } catch (Exception e) {
                log.error("Shutdown error", e);
                // TODO Auto-generated catch block
                //e.printStackTrace();
            }
        }
    }.start();

    Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
        public void run() {
            log.info("IN shutdown Hook");
            synchronized (shutDownObject) {
                shutDownObject.notifyAll();
            }
        }
    }));
    try {
        synchronized (shutDownObject) {
            shutDownObject.wait();
        }
        //executor.shutdownNow();
        //serverSocketChannelServices.close();
        //embeddedJMS.stop();

    } catch (Exception e) {
        log.error("Error in object wait ", e);
        // TODO Auto-generated catch block
        //e1.printStackTrace();
    }
    try {
        mbs.invoke(name, "stop", null, null);
        mbs.invoke(name, "destroy", null, null);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    log.info("Halting JVM");
    log.info("Exiting JVM");
    /*try{
       Thread.sleep(10000);
    }
    catch(Exception ex){
               
    }*/

    //webserverRequestProcessor.stop();
    //webserverRequestProcessor1.stop();

    /*warDeployer.stop();
    executorService.stop();
    //ataServer.stop();
    //ataClient.stop();
    messageServer.stop();
    randomqueuemessagepicker.stop();
    roundrobinqueuemessagepicker.stop();
    topicpicker.stop();*/
    /*try {
       mbs.invoke(new ObjectName("com.app.server:type=SARDeployer"), "destroyDeployer", null, null);
    } catch (InstanceNotFoundException | MalformedObjectNameException
    | ReflectionException | MBeanException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
    }*/
    //earDeployer.stop();
    System.exit(0);
}

From source file:chronos.web.listener.ChronosServletListener.java

/**
 * @return MBeanServer//  w w  w. jav a 2s.  c om
 */
private MBeanServer findOrCreateChronosMBeanServer() {
    final ArrayList<MBeanServer> servers = MBeanServerFactory.findMBeanServer(null);
    logger.debug("Got " + servers.size() + " MBean servers");
    if (servers.size() == 0) {
        logger.debug("Creating new MBeanServer for \"chronos\"...");
        return MBeanServerFactory.createMBeanServer(CHRONOS);
    }

    final MBeanServer server = servers.get(0);
    logger.debug("Returning MBeanServer domain: " + server.getDefaultDomain());
    return server;
}

From source file:net.sf.ehcache.management.ManagementServiceTest.java

private MBeanServer create14MBeanServer() {
    return MBeanServerFactory.createMBeanServer("SimpleAgent");
}

From source file:net.sbbi.upnp.jmx.JMXManager.java

private MBeanServer initMBeanServer(MBeanServerConfig conf) throws Exception {
    mx4j.log.Log.redirectTo(new CommonsLogger());
    //  make sure that MX4j Server builder is used
    String oldSysProp = System.getProperty("javax.management.builder.initial");
    System.setProperty("javax.management.builder.initial", "mx4j.server.MX4JMBeanServerBuilder");
    MBeanServer server = MBeanServerFactory.createMBeanServer("UPNPLib");
    if (oldSysProp != null) {
        System.setProperty("javax.management.builder.initial", oldSysProp);
    }//from   ww  w. jav  a 2  s . com
    ObjectName serverName = new ObjectName("Http:name=HttpAdaptor");
    server.createMBean("mx4j.tools.adaptor.http.HttpAdaptor", serverName, null);
    // set attributes
    server.setAttribute(serverName, new Attribute("Port", new Integer(conf.adapterAdapterPort)));

    Boolean allowWanBool = new Boolean(conf.allowWan);
    if (allowWanBool.booleanValue()) {
        server.setAttribute(serverName, new Attribute("Host", "0.0.0.0"));
    } else {
        server.setAttribute(serverName, new Attribute("Host", "localhost"));
    }

    ObjectName processorName = new ObjectName("Http:name=XSLTProcessor");
    server.createMBean("mx4j.tools.adaptor.http.XSLTProcessor", processorName, null);
    server.setAttribute(processorName, new Attribute("LocaleString", conf.locale));

    server.setAttribute(processorName, new Attribute("UseCache", Boolean.FALSE));

    server.setAttribute(processorName, new Attribute("PathInJar", "net/sbbi/jmx/xsl"));

    server.setAttribute(serverName, new Attribute("ProcessorName", processorName));
    // add user names
    server.invoke(serverName, "addAuthorization", new Object[] { conf.adapterUserName, conf.adapterPassword },
            new String[] { "java.lang.String", "java.lang.String" });
    // use basic authentication
    server.setAttribute(serverName, new Attribute("AuthenticationMethod", "basic"));
    // starts the server
    server.invoke(serverName, "start", null, null);

    return server;
}

From source file:net.sf.ehcache.AbstractCacheTest.java

/**
 * Obtains an MBeanServer, which varies with Java version
 * @return/* ww w  . jav a  2 s .  c  o  m*/
 */
public MBeanServer createMBeanServer() {
    try {
        Class managementFactoryClass = Class.forName("java.lang.management.ManagementFactory");
        Method method = managementFactoryClass.getMethod("getPlatformMBeanServer", null);
        return (MBeanServer) method.invoke(null, null);
    } catch (Exception e) {
        LOG.info("JDK1.5 ManagementFactory not found. Falling back to JMX1.2.1", e);
        return MBeanServerFactory.createMBeanServer("SimpleAgent");
    }
}

From source file:org.apache.camel.management.DefaultManagementAgent.java

protected MBeanServer findOrCreateMBeanServer() {

    // return platform mbean server if the option is specified.
    if (usePlatformMBeanServer) {
        return ManagementFactory.getPlatformMBeanServer();
    }//from w ww.ja  v a  2  s .c o  m

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

    for (MBeanServer server : servers) {
        if (LOG.isDebugEnabled()) {
            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);
}

From source file:org.apache.geode.admin.jmx.internal.MBeanUtil.java

/**
 * Create and configure (if necessary) and return the <code>MBeanServer</code> with which we will
 * be registering our <code>ModelMBean</code> implementations.
 *
 * @see javax.management.MBeanServer/*  w  ww  . j av a  2  s  . com*/
 */
static synchronized MBeanServer createMBeanServer() {
    if (mbeanServer == null) {
        mbeanServer = MBeanServerFactory.createMBeanServer(DEFAULT_DOMAIN);
    }
    return mbeanServer;
}

From source file:org.jpos.q2.Q2.java

public void run() {
    started = true;//from  w  ww  .  j  ava 2 s  .  co  m
    Thread.currentThread().setName("Q2-" + getInstanceId().toString());
    try {
        /*
        * The following code determines whether a MBeanServer exists 
        * already. If so then the first one in the list is used. 
        * I have not yet find a way to interrogate the server for 
        * information other than MBeans so to pick a specific one 
        * would be difficult.
        */
        ArrayList mbeanServerList = MBeanServerFactory.findMBeanServer(null);
        if (mbeanServerList.isEmpty()) {
            server = MBeanServerFactory.createMBeanServer(JMX_NAME);
        } else {
            server = (MBeanServer) mbeanServerList.get(0);
        }
        final ObjectName loaderName = new ObjectName(Q2_CLASS_LOADER);
        try {
            loader = (QClassLoader) java.security.AccessController
                    .doPrivileged(new java.security.PrivilegedAction() {
                        public Object run() {
                            return new QClassLoader(server, libDir, loaderName, mainClassLoader);
                        }
                    });
            server.registerMBean(loader, loaderName);
            loader = loader.scan(false);
        } catch (Throwable t) {
            if (log != null)
                log.error("initial-scan", t);
            else
                t.printStackTrace();
        }
        factory = new QFactory(loaderName, this);
        initSystemLogger();
        if (bundleContext == null)
            addShutdownHook();
        q2Thread = Thread.currentThread();
        q2Thread.setContextClassLoader(loader);
        if (cli != null)
            cli.start();
        initConfigDecorator();
        if (startOSGI)
            startOSGIFramework();
        for (int i = 1; !shutdown; i++) {
            try {
                boolean forceNewClassLoader = scan();
                QClassLoader oldClassLoader = loader;
                loader = loader.scan(forceNewClassLoader);
                if (loader != oldClassLoader) {
                    oldClassLoader = null; // We want this to be null so it gets GCed.
                    System.gc(); // force a GC
                    log.info("new classloader [" + Integer.toString(loader.hashCode(), 16)
                            + "] has been created");
                }
                deploy();
                checkModified();
                relax(SCAN_INTERVAL);
                if (i % (3600000 / SCAN_INTERVAL) == 0)
                    logVersion();
            } catch (Throwable t) {
                log.error("start", t);
                relax();
            }
        }
        undeploy();
        try {
            server.unregisterMBean(loaderName);
        } catch (InstanceNotFoundException e) {
            log.error(e);
        }
        if (decorator != null) {
            decorator.uninitialize();
        }
        if (exit && !shuttingDown)
            System.exit(0);
    } catch (Exception e) {
        if (log != null)
            log.error(e);
        else
            e.printStackTrace();
        System.exit(1);
    }
}

From source file:org.opennms.netmgt.vmmgr.InvokerTest.java

@Before
public void setUp() throws Throwable {
    m_server = MBeanServerFactory.createMBeanServer("OpenNMS");
    m_services = InvokerService.createServiceList(getServiceList());

    Invoker invoker = new Invoker();
    invoker.setServer(m_server);/* w w w . jav  a2 s.  c  om*/
    invoker.setAtType(InvokeAtType.START);
    invoker.setServices(m_services);
    invoker.instantiateClasses();

    invokeMethods(invoker);

    Thread.sleep(1000);
}

From source file:org.springframework.jmx.support.MBeanServerFactoryBean.java

/**
 * Create a new {@code MBeanServer} instance and register it with the
 * {@code MBeanServerFactory}, if desired.
 * @param defaultDomain the default domain, or {@code null} if none
 * @param registerWithFactory whether to register the {@code MBeanServer}
 * with the {@code MBeanServerFactory}/*ww w .ja  va 2s .co m*/
 * @see javax.management.MBeanServerFactory#createMBeanServer
 * @see javax.management.MBeanServerFactory#newMBeanServer
 */
protected MBeanServer createMBeanServer(@Nullable String defaultDomain, boolean registerWithFactory) {
    if (registerWithFactory) {
        return MBeanServerFactory.createMBeanServer(defaultDomain);
    } else {
        return MBeanServerFactory.newMBeanServer(defaultDomain);
    }
}