Example usage for javax.management MBeanServer invoke

List of usage examples for javax.management MBeanServer invoke

Introduction

In this page you can find the example usage for javax.management MBeanServer invoke.

Prototype

public Object invoke(ObjectName name, String operationName, Object params[], String signature[])
            throws InstanceNotFoundException, MBeanException, ReflectionException;

Source Link

Usage

From source file:com.web.server.SARDeployer.java

/**
 * This method undeployed the SAR//from www. ja  v  a  2s.com
 * @param dir
 * @return
 */
public boolean deleteDir(File dir) {
    String fileName = dir.getName();
    System.out.println("Dirname to be deleted" + fileName);
    Sar sar = null;
    try {
        sar = (Sar) sardigester.parse(new InputSource(
                new FileInputStream(deployDirectory + "/" + fileName + "/META-INF/" + "mbean-service.xml")));
    } catch (IOException | SAXException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    URLClassLoader sarClassLoader = (URLClassLoader) sarsMap.get(fileName);
    if (sarClassLoader != null) {
        ClassLoaderUtil.closeClassLoader(sarClassLoader);
        CopyOnWriteArrayList mbeans = sar.getMbean();
        MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
        System.out.println(mbs);
        ObjectName objName;
        try {
            for (int index = 0; index < mbeans.size(); index++) {
                Mbean mbean = (Mbean) mbeans.get(index);
                System.out.println(mbean.getObjectname());
                System.out.println(mbean.getCls());
                objName = new ObjectName(mbean.getObjectname());
                if (mbs.isRegistered(objName)) {
                    mbs.invoke(objName, "stopService", null, null);
                    //mbs.invoke(objName, "destroy", null, null);
                    mbs.unregisterMBean(objName);
                }
            }
            sarsMap.remove(fileName);
        } catch (MalformedObjectNameException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (MBeanRegistrationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InstanceNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ReflectionException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (MBeanException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    return recursiveDelete(dir);

}

From source file:com.web.server.SARDeployer.java

/**
 * This method extracts the SAR archive and configures for the SAR and starts the services
 * @param file/*from w w  w . j  a v  a2 s  . c  o  m*/
 * @param warDirectoryPath
 * @throws IOException
 */
public void extractSar(File file, String warDirectoryPath) throws IOException {
    ZipFile zip = new ZipFile(file);
    ZipEntry ze = null;
    String fileName = file.getName();
    fileName = fileName.substring(0, fileName.indexOf('.'));
    fileName += "sar";
    String fileDirectory;
    CopyOnWriteArrayList classPath = new CopyOnWriteArrayList();
    Enumeration<? extends ZipEntry> entries = zip.entries();
    int numBytes;
    while (entries.hasMoreElements()) {
        ze = entries.nextElement();
        // //System.out.println("Unzipping " + ze.getName());
        String filePath = deployDirectory + "/" + fileName + "/" + ze.getName();
        if (!ze.isDirectory()) {
            fileDirectory = filePath.substring(0, filePath.lastIndexOf('/'));
        } else {
            fileDirectory = filePath;
        }
        // //System.out.println(fileDirectory);
        createDirectory(fileDirectory);
        if (!ze.isDirectory()) {
            FileOutputStream fout = new FileOutputStream(filePath);
            byte[] inputbyt = new byte[8192];
            InputStream istream = zip.getInputStream(ze);
            while ((numBytes = istream.read(inputbyt, 0, inputbyt.length)) >= 0) {
                fout.write(inputbyt, 0, numBytes);
            }
            fout.close();
            istream.close();
            if (ze.getName().endsWith(".jar")) {
                classPath.add(filePath);
            }
        }
    }
    zip.close();
    URLClassLoader loader = (URLClassLoader) ClassLoader.getSystemClassLoader();
    URL[] urls = loader.getURLs();
    WebClassLoader sarClassLoader = new WebClassLoader(urls);
    for (int index = 0; index < classPath.size(); index++) {
        System.out.println("file:" + classPath.get(index));
        new WebServer().addURL(new URL("file:" + classPath.get(index)), sarClassLoader);
    }
    new WebServer().addURL(new URL("file:" + deployDirectory + "/" + fileName + "/"), sarClassLoader);
    sarsMap.put(fileName, sarClassLoader);
    System.out.println(sarClassLoader.geturlS());
    try {
        Sar sar = (Sar) sardigester.parse(new InputSource(
                new FileInputStream(deployDirectory + "/" + fileName + "/META-INF/" + "mbean-service.xml")));
        CopyOnWriteArrayList mbeans = sar.getMbean();
        MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
        System.out.println(mbs);
        ObjectName objName;
        for (int index = 0; index < mbeans.size(); index++) {
            Mbean mbean = (Mbean) mbeans.get(index);
            System.out.println(mbean.getObjectname());
            System.out.println(mbean.getCls());
            objName = new ObjectName(mbean.getObjectname());
            Class helloWorldService = sarClassLoader.loadClass(mbean.getCls());
            Object obj = helloWorldService.newInstance();
            if (mbs.isRegistered(objName)) {
                mbs.invoke(objName, "stopService", null, null);
                //mbs.invoke(objName, "destroy", null, null);
                mbs.unregisterMBean(objName);
            }
            mbs.registerMBean(obj, objName);
            CopyOnWriteArrayList attrlist = mbean.getMbeanAttribute();
            if (attrlist != null) {
                for (int count = 0; count < attrlist.size(); count++) {
                    MBeanAttribute attr = (MBeanAttribute) attrlist.get(count);
                    Attribute mbeanattribute = new Attribute(attr.getName(), attr.getValue());
                    mbs.setAttribute(objName, mbeanattribute);
                }
            }
            mbs.invoke(objName, "startService", null, null);
        }
    } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InstantiationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SAXException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (MalformedObjectNameException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InstanceAlreadyExistsException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (MBeanRegistrationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (NotCompliantMBeanException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InstanceNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ReflectionException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (MBeanException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InvalidAttributeValueException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (AttributeNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

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   w  ww  . j  a  va  2s  .c o  m*/
    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:org.camelcookbook.monitoring.managed.ManagedSpringTest.java

@Test
public void testManagedResource() throws Exception {
    final ManagementAgent managementAgent = context.getManagementStrategy().getManagementAgent();
    assertNotNull(managementAgent);//from   ww  w  . j av  a2 s .c om

    final MBeanServer mBeanServer = managementAgent.getMBeanServer();
    assertNotNull(mBeanServer);

    final String mBeanServerDefaultDomain = managementAgent.getMBeanServerDefaultDomain();
    assertEquals("org.apache.camel", mBeanServerDefaultDomain);

    final String managementName = context.getManagementName();
    assertNotNull("CamelContext should have a management name if JMX is enabled", managementName);
    LOG.info("managementName = {}", managementName);

    // Get the Camel Context MBean
    ObjectName onContext = ObjectName.getInstance(mBeanServerDefaultDomain + ":context=localhost/"
            + managementName + ",type=context,name=\"" + context.getName() + "\"");

    assertTrue("Should be registered", mBeanServer.isRegistered(onContext));

    // Get myManagedBean
    ObjectName onManagedBean = ObjectName.getInstance(mBeanServerDefaultDomain + ":context=localhost/"
            + managementName + ",type=processors,name=\"myManagedBean\"");
    LOG.info("Canonical Name = {}", onManagedBean.getCanonicalName());
    assertTrue("Should be registered", mBeanServer.isRegistered(onManagedBean));

    // Send a couple of messages to get some route statistics
    template.sendBody("direct:start", "Hello Camel");
    template.sendBody("direct:start", "Camel Rocks!");

    // Get MBean attribute
    int camelsSeenCount = (Integer) mBeanServer.getAttribute(onManagedBean, "CamelsSeenCount");
    assertEquals(2, camelsSeenCount);

    // Stop the route via JMX
    mBeanServer.invoke(onManagedBean, "resetCamelsSeenCount", null, null);

    camelsSeenCount = (Integer) mBeanServer.getAttribute(onManagedBean, "CamelsSeenCount");
    assertEquals(0, camelsSeenCount);
}

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

/**
 * This is the start of the all the services in web server
 * @param args//from www  .jav a  2s.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:com.evolveum.midpoint.gui.api.page.PageBase.java

protected void clearLessJsCache(AjaxRequestTarget target) {
    try {//from   ww  w  . j  a v a  2s  .  com
        ArrayList<MBeanServer> servers = MBeanServerFactory.findMBeanServer(null);
        if (servers.size() > 1) {
            LOGGER.info("Too many mbean servers, cache won't be cleared.");
            for (MBeanServer server : servers) {
                LOGGER.info(server.getDefaultDomain());
            }
            return;
        }
        MBeanServer server = servers.get(0);
        ObjectName objectName = ObjectName.getInstance(Wro4jConfig.WRO_MBEAN_NAME + ":type=WroConfiguration");
        server.invoke(objectName, "reloadCache", new Object[] {}, new String[] {});
        if (target != null) {
            target.add(PageBase.this);
        }
    } catch (Exception ex) {
        LoggingUtils.logUnexpectedException(LOGGER, "Couldn't clear less/js cache", ex);
        error("Error occurred, reason: " + ex.getMessage());
        if (target != null) {
            target.add(getFeedbackPanel());
        }
    }
}

From source file:org.camelcookbook.monitoring.naming.JmxNamingContextSpringTest.java

@Test
public void testNamingContextSpring() throws Exception {
    final ManagementAgent managementAgent = context.getManagementStrategy().getManagementAgent();
    assertNotNull(managementAgent);//  w  w  w .jav a2s .  co m

    final MBeanServer mBeanServer = managementAgent.getMBeanServer();
    assertNotNull(mBeanServer);

    final String mBeanServerDefaultDomain = managementAgent.getMBeanServerDefaultDomain();
    assertEquals("org.apache.camel", mBeanServerDefaultDomain);

    final String managementName = context.getManagementName();
    assertNotNull("CamelContext should have a management name if JMX is enabled", managementName);
    LOG.info("managementName = {}", managementName);

    // Get the Camel Context MBean
    ObjectName onContext = ObjectName.getInstance(mBeanServerDefaultDomain + ":context=localhost/"
            + managementName + ",type=context,name=\"" + context.getName() + "\"");
    assertTrue("Should be registered", mBeanServer.isRegistered(onContext));

    // Get the first Route MBean by id
    ObjectName onRoute1 = ObjectName.getInstance(mBeanServerDefaultDomain + ":context=localhost/"
            + managementName + ",type=routes,name=\"first-route\"");
    LOG.info("Canonical Name = {}", onRoute1.getCanonicalName());
    assertTrue("Should be registered", mBeanServer.isRegistered(onRoute1));

    // Send a couple of messages to get some route statistics
    template.sendBody("direct:start", "Hello Camel");
    template.sendBody("direct:start", "Camel Rocks!");

    // Get an MBean attribute for the number of messages processed
    assertEquals(2L, mBeanServer.getAttribute(onRoute1, "ExchangesCompleted"));

    // Get the other Route MBean by id
    ObjectName onRoute2 = ObjectName.getInstance(mBeanServerDefaultDomain + ":context=localhost/"
            + managementName + ",type=routes,name=\"other-route\"");
    assertTrue("Should be registered", mBeanServer.isRegistered(onRoute2));

    // Get an MBean attribute for the number of messages processed
    assertEquals(0L, mBeanServer.getAttribute(onRoute2, "ExchangesCompleted"));

    // Send some messages to the other route
    template.sendBody("direct:startOther", "Hello Other Camel");
    template.sendBody("direct:startOther", "Other Camel Rocks!");

    // Verify that the MBean statistics updated correctly
    assertEquals(2L, mBeanServer.getAttribute(onRoute2, "ExchangesCompleted"));

    // Check this routes running state
    assertEquals("Started", mBeanServer.getAttribute(onRoute2, "State"));

    // Stop the route via JMX
    mBeanServer.invoke(onRoute2, "stop", null, null);

    // verify the route now shows its state as stopped
    assertEquals("Stopped", mBeanServer.getAttribute(onRoute2, "State"));
}

From source file:org.camelcookbook.monitoring.naming.JmxNamingPatternSpringTest.java

@Test
public void testNamingPatternSpring() throws Exception {
    final ManagementAgent managementAgent = context.getManagementStrategy().getManagementAgent();
    assertNotNull(managementAgent);/* www .  j a  va  2s. co m*/

    final MBeanServer mBeanServer = managementAgent.getMBeanServer();
    assertNotNull(mBeanServer);

    final String mBeanServerDefaultDomain = managementAgent.getMBeanServerDefaultDomain();
    assertEquals("org.apache.camel", mBeanServerDefaultDomain);

    final String managementName = context.getManagementName();
    assertNotNull("CamelContext should have a management name if JMX is enabled", managementName);
    LOG.info("managementName = {}; name = {}", managementName, context.getName());
    assertTrue(managementName.startsWith("CustomName"));

    // Get the Camel Context MBean
    ObjectName onContext = ObjectName.getInstance(mBeanServerDefaultDomain + ":context=localhost/"
            + managementName + ",type=context,name=\"" + context.getName() + "\"");
    assertTrue("Should be registered", mBeanServer.isRegistered(onContext));

    // Get the first Route MBean by id
    ObjectName onRoute1 = ObjectName.getInstance(mBeanServerDefaultDomain + ":context=localhost/"
            + managementName + ",type=routes,name=\"first-route\"");
    LOG.info("Canonical Name = {}", onRoute1.getCanonicalName());
    assertTrue("Should be registered", mBeanServer.isRegistered(onRoute1));

    // Send a couple of messages to get some route statistics
    template.sendBody("direct:start", "Hello Camel");
    template.sendBody("direct:start", "Camel Rocks!");

    // Get an MBean attribute for the number of messages processed
    assertEquals(2L, mBeanServer.getAttribute(onRoute1, "ExchangesCompleted"));

    // Get the other Route MBean by id
    ObjectName onRoute2 = ObjectName.getInstance(mBeanServerDefaultDomain + ":context=localhost/"
            + managementName + ",type=routes,name=\"other-route\"");
    assertTrue("Should be registered", mBeanServer.isRegistered(onRoute2));

    // Get an MBean attribute for the number of messages processed
    assertEquals(0L, mBeanServer.getAttribute(onRoute2, "ExchangesCompleted"));

    // Send some messages to the other route
    template.sendBody("direct:startOther", "Hello Other Camel");
    template.sendBody("direct:startOther", "Other Camel Rocks!");

    // Verify that the MBean statistics updated correctly
    assertEquals(2L, mBeanServer.getAttribute(onRoute2, "ExchangesCompleted"));

    // Check this routes running state
    assertEquals("Started", mBeanServer.getAttribute(onRoute2, "State"));

    // Stop the route via JMX
    mBeanServer.invoke(onRoute2, "stop", null, null);

    // verify the route now shows its state as stopped
    assertEquals("Stopped", mBeanServer.getAttribute(onRoute2, "State"));
}

From source file:net.testdriven.psiprobe.beans.JBossResourceResolverBean.java

public boolean resetResource(Context context, String resourceName) throws NamingException {
    try {/*  w  w w  .  j a va 2s  .co  m*/
        ObjectName poolOName = new ObjectName("jboss.jca:service=ManagedConnectionPool,name=" + resourceName);
        MBeanServer server = getMBeanServer();
        if (server != null) {
            try {
                server.invoke(poolOName, "stop", null, null);
                server.invoke(poolOName, "start", null, null);
                return true;
            } catch (Exception e) {
                logger.error("Could not reset resource \"" + resourceName + "\"", e);
            }
        }
        return false;
    } catch (MalformedObjectNameException e) {
        throw new NamingException("Resource name: \"" + resourceName + "\" makes a malformed ObjectName");
    }
}

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

private void createRMIRegistry() throws Exception {
    if (!this.agentConfig.isRmiRegistryEnabled()) {
        return;//from  ww  w.jav  a 2s .  c o  m
    }
    MBeanServer mbs = getMBeanServer();
    String host = this.agentConfig.getRmiBindAddress();
    int port = this.agentConfig.getRmiPort();

    /*
     * Register and start the rmi-registry naming MBean, which is needed by JSR 160
     * RMIConnectorServer
     */
    ObjectName registryName = getRMIRegistryNamingName();
    try {
        RMIRegistryService registryNamingService = null;
        if (host != null && !("".equals(host.trim()))) {
            registryNamingService = new RMIRegistryService(host, port);
        } else {
            registryNamingService = new RMIRegistryService(port);
        }
        mbs.registerMBean(registryNamingService, registryName);
    } catch (javax.management.InstanceAlreadyExistsException e) {
        logger.info(LocalizedMessage.create(LocalizedStrings.AgentImpl_0__IS_ALREADY_REGISTERED, registryName));
    }
    mbs.invoke(registryName, "start", null, null);
}