Example usage for javax.management ObjectName ObjectName

List of usage examples for javax.management ObjectName ObjectName

Introduction

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

Prototype

public ObjectName(String name) throws MalformedObjectNameException 

Source Link

Document

Construct an object name from the given string.

Usage

From source file:org.red5.server.winstone.WinstoneLoader.java

protected void unregisterJMX() {
    MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
    try {//from   w w w . j  a  v a 2  s .c o m
        ObjectName oName = new ObjectName("org.red5.server:type=WinstoneLoader");
        mbs.unregisterMBean(oName);
    } catch (Exception e) {
        log.warn("Exception unregistering", e);
    }
}

From source file:com.webobjects.monitor.wotaskd.Application.java

/**
 * ============================================================================================
 *                  Methods Added for Enabling JMX in Wotaskd
 * ============================================================================================
 * This methods registers the MBean object in the MBeanServer
 * @param objMBean      - The MBean object to register
 * @param strDomainName - Domain name required for creating the ObjectName of the MBean
 * @param strMBeanName  - Name of the MBean
 *//*from  w  w w  . j  av  a 2s  . co  m*/
@Override
public void registerMBean(Object objMBean, String strDomainName, String strMBeanName)
        throws IllegalArgumentException {
    if (objMBean == null)
        throw new IllegalArgumentException("Error: Could not register null to PlatformMbeanServer.");
    if (strMBeanName == null)
        throw new IllegalArgumentException("Error: MBean name could not be null.");

    ObjectName objName = null;
    strDomainName = (strDomainName == null) ? getJMXDomain() : strDomainName;

    //Create the Object Name for the MBean
    try {
        objName = new ObjectName(strDomainName + ": name=" + strMBeanName);
    } catch (MalformedObjectNameException e) {
        e.printStackTrace();
    } catch (NullPointerException e) {
        e.printStackTrace();
    }

    // Register the MBean
    try {
        getMBeanServer().registerMBean(objMBean, objName);
    } catch (IllegalAccessException e) {
        NSLog.err.appendln("ERROR: security access problem registering bean: " + objMBean + " with ObjectName: "
                + objName + " " + e.toString());
    } catch (InstanceAlreadyExistsException e) {
        NSLog.err.appendln("ERROR: MBean already exists bean: " + objMBean + " with ObjectName: " + objName
                + " " + e.toString());
    } catch (MBeanRegistrationException e) {
        NSLog.err.appendln("ERROR: error registering bean: " + objMBean + " with ObjectName: " + objName + " "
                + e.toString());
    } catch (NotCompliantMBeanException e) {
        NSLog.err.appendln("ERROR: error registering bean: " + objMBean + " with ObjectName: " + objName + " "
                + e.toString());
    }
}

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   www.j  av a  2s.  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:com.spotify.reaper.cassandra.JmxProxy.java

/**
 * New way of determining if a repair is running after C* 2.2
 * /*from   ww w  .j av a2s .  c o  m*/
 * @return true if any repairs are running on the node.
 */
public boolean isRepairRunningPost22() {
    try {
        // list all mbeans in search of one with the name Repair#?? 
        // This is the replacement for AntiEntropySessions since Cassandra 2.2
        Set beanSet = mbeanServer.queryNames(new ObjectName("org.apache.cassandra.internal:*"), null);
        for (Object bean : beanSet) {
            ObjectName objName = (ObjectName) bean;
            if (objName.getCanonicalName().contains("Repair#")) {
                return true;
            }
        }
        return false;
    } catch (IOException ignored) {
        LOG.warn(FAILED_TO_CONNECT_TO_USING_JMX, host, ignored);
    } catch (MalformedObjectNameException ignored) {
        LOG.error("Internal error, malformed name", ignored);
    } catch (Exception e) {
        LOG.error(ERROR_GETTING_ATTR_JMX, e);
    }
    // If uncertain, assume it's running
    return true;
}

From source file:com.octo.captcha.j2ee.ImageCaptchaService.java

/**
 * Unregister self from the first MBean server available in the JVM, if any
 *//*from  w  ww.j a v a2s .c om*/
public void unregisterFromMBeanServer() {
    if (this.registeredName != null) {
        ArrayList mbeanServers = MBeanServerFactory.findMBeanServer(null);
        MBeanServer mbeanServer = (MBeanServer) mbeanServers.get(0);
        try {
            ObjectName name = new ObjectName(this.registeredName);
            mbeanServer.unregisterMBean(name);
        } catch (MalformedObjectNameException e) {
            // this should never happens
            log.error("Exception trying to create the object name under witch" + " the service is registered",
                    e);
        } catch (InstanceNotFoundException e) {
            // this should never happens
            log.error("Exception trying to unregister the ImageCaptchaFilter from" + " the MBean server", e);
        } catch (MBeanRegistrationException e) {
            // this remains silent for the client
            log.error("Exception trying to unregister the ImageCaptchaFilter from" + "the MBean server", e);
        }
    }
}

From source file:com.addthis.hydra.task.output.tree.TreeMapper.java

private void _init(TaskRunConfig runConfig) throws Exception {
    config = runConfig;/*from w  w w . j  av a  2  s.c  om*/
    mapstats = new TreeMapperStats(log);

    resolve();

    if (nodeCache != null)
        TreeCommonParameters.setDefaultCleanQueueSize(nodeCache);
    if (trashInterval != null)
        TreeCommonParameters.setDefaultTrashInterval(trashInterval);
    if (trashTimeLimit != null)
        TreeCommonParameters.setDefaultTrashTimeLimit(trashTimeLimit);
    if (storage != null) {
        if (storage.maxCacheSize != null)
            TreeCommonParameters.setDefaultMaxCacheSize(storage.maxCacheSize);
        if (storage.maxCacheMem != null)
            TreeCommonParameters.setDefaultMaxCacheMem(storage.maxCacheMem);
        if (storage.maxPageSize != null)
            TreeCommonParameters.setDefaultMaxPageSize(storage.maxCacheSize);
        if (storage.maxPageMem != null)
            TreeCommonParameters.setDefaultMaxPageMem(storage.maxPageMem);
        if (storage.memSample != null)
            TreeCommonParameters.setDefaultMemSample(storage.memSample);
    }

    if (Strings.isEmpty(localhost)) {
        localhost = InetAddress.getLocalHost().getHostAddress();
    }
    log.info("[init] java=" + System.getProperty("java.vm.version") + " query=" + enableQuery + " http="
            + enableHttp + " jmx=" + enableJmx + " live=" + live);
    log.info("[init] host=" + localhost + " port=" + port + " target=" + root + " job=" + config.jobId);

    Path treePath = Paths.get(runConfig.dir, "data");
    tree = new ConcurrentTree(Files.initDirectory(treePath.toFile()));
    bench = new Bench(EnumSet.allOf(BENCH.class), 1000);

    if (enableHttp) {
        jetty = new Server(port > 0 ? port++ : 0);
        jetty.start();
        int httpPort = jetty.getConnectors()[0].getLocalPort();
        log.info("[init.http] http://" + localhost + ":" + httpPort + "/");
        Files.write(new File("job.port"), Bytes.toBytes(Integer.toString(httpPort)), false);
    }

    if (enableJmx) {
        int queryPort = 0;
        jmxname = new ObjectName("com.addthis.hydra:type=Hydra,node=" + queryPort);
        ManagementFactory.getPlatformMBeanServer().registerMBean(mapstats, jmxname);
        ServerSocket ss = new ServerSocket();
        ss.setReuseAddress(true);
        ss.bind(port > 0 ? new InetSocketAddress(port++) : null);
        int jmxport = ss.getLocalPort();
        ss.close();
        if (jmxport == -1) {
            log.warn("[init.jmx] failed to get a port");
        } else {
            try {
                jmxremote = new MBeanRemotingSupport(jmxport);
                jmxremote.start();
                log.info("[init.jmx] port=" + jmxport);
            } catch (Exception e) {
                log.warn("[init.jmx] err=" + e);
            }
        }
    }

    if (config.jobId != null && live && livePort > -1) {
        QueryEngine liveQueryEngine = new QueryEngine(tree);
        connectToMesh(treePath.toFile(), runConfig.jobId, liveQueryEngine);
    }

    startTime = System.currentTimeMillis();

    if (pre != null) {
        log.warn("pre-chain: " + pre);
        processBundle(new KVBundle(), pre);
    }
}

From source file:com.sun.grizzly.http.jk.common.ChannelNioSocket.java

/**
 * jmx:managed-operation//from   www.ja v  a2s  .  com
 */
@Override
public void init() throws IOException {
    // Find a port.
    if (startPort == 0) {
        port = 0;
        LoggerUtils.getLogger().info("JK: ajp13 disabling channelNioSocket");
        running = true;
        return;
    }
    if (maxPort < startPort) {
        maxPort = startPort;
    }
    ServerSocketChannel ssc = ServerSocketChannel.open();
    ssc.configureBlocking(false);
    for (int i = startPort; i <= maxPort; i++) {
        try {
            InetSocketAddress iddr = null;
            if (inet == null) {
                iddr = new InetSocketAddress(i);
            } else {
                iddr = new InetSocketAddress(inet, i);
            }
            sSocket = ssc.socket();
            sSocket.bind(iddr);
            port = i;
            break;
        } catch (IOException ex) {

            LoggerUtils.getLogger().info("Port busy " + i + " " + ex.toString());
            sSocket = null;
        }
    }

    if (sSocket == null) {
        LoggerUtils.getLogger().log(Level.SEVERE, "Can't find free port " + startPort + " " + maxPort);
        return;
    }

    LoggerUtils.getLogger().info("JK: ajp13 listening on " + getAddress() + ":" + port);

    selector = Utils.openSelector();
    ssc.register(selector, SelectionKey.OP_ACCEPT);
    // If this is not the base port and we are the 'main' channleSocket and
    // SHM didn't already set the localId - we'll set the instance id
    if ("channelNioSocket".equals(name) && port != startPort && (wEnv.getLocalId() == 0)) {
        wEnv.setLocalId(port - startPort);
    }

    // XXX Reverse it -> this is a notification generator !!
    if (next == null && wEnv != null) {
        if (nextName != null) {
            setNext(wEnv.getHandler(nextName));
        }
        if (next == null) {
            next = wEnv.getHandler("dispatch");
        }
        if (next == null) {
            next = wEnv.getHandler("request");
        }
    }
    JMXRequestNote = wEnv.getNoteId(WorkerEnv.ENDPOINT_NOTE, "requestNote");
    running = true;

    // Run a thread that will accept connections.
    // XXX Try to find a thread first - not sure how...
    if (this.domain != null) {
        try {
            tpOName = new ObjectName(domain + ":type=ThreadPool,name=" + getChannelName());

            Registry.getRegistry(null, null).registerComponent(tp, tpOName, null);

            rgOName = new ObjectName(domain + ":type=GlobalRequestProcessor,name=" + getChannelName());
            Registry.getRegistry(null, null).registerComponent(global, rgOName, null);
        } catch (Exception e) {
            LoggerUtils.getLogger().log(Level.SEVERE, "Can't register threadpool");
        }
    }

    tp.start();
    Poller pollAjp = new Poller();
    tp.runIt(pollAjp);
}

From source file:catalina.mbeans.MBeanFactory.java

/**
 * Create a new HttpConnector//from   www .j a v  a  2  s.  com
 *
 * @param parent MBean Name of the associated parent component
 * @param address The IP address on which to bind
 * @param port TCP port number to listen on
 *
 * @exception Exception if an MBean cannot be created or registered
 */
public String createHttpConnector(String parent, String address, int port) throws Exception {

    Object retobj = null;

    try {

        // Create a new CoyoteConnector instance
        // use reflection to avoid j-t-c compile-time circular dependencies
        Class cls = Class.forName("org.apache.coyote.tomcat4.CoyoteConnector");
        Constructor ct = cls.getConstructor(null);
        retobj = ct.newInstance(null);
        Class partypes1[] = new Class[1];
        // Set address
        String str = new String();
        partypes1[0] = str.getClass();
        Method meth1 = cls.getMethod("setAddress", partypes1);
        Object arglist1[] = new Object[1];
        arglist1[0] = address;
        meth1.invoke(retobj, arglist1);
        // Set port number
        Class partypes2[] = new Class[1];
        partypes2[0] = Integer.TYPE;
        Method meth2 = cls.getMethod("setPort", partypes2);
        Object arglist2[] = new Object[1];
        arglist2[0] = new Integer(port);
        meth2.invoke(retobj, arglist2);
    } catch (Exception e) {
        throw new MBeanException(e);
    }

    // Add the new instance to its parent component
    ObjectName pname = new ObjectName(parent);
    Server server = ServerFactory.getServer();
    Service service = server.findService(pname.getKeyProperty("name"));
    service.addConnector((Connector) retobj);

    // Return the corresponding MBean name
    ManagedBean managed = registry.findManagedBean("CoyoteConnector");
    ObjectName oname = MBeanUtils.createObjectName(managed.getDomain(), (Connector) retobj);
    return (oname.toString());

}

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

/**
 * This method extracts the SAR archive and configures for the SAR and starts the services
 * @param file/* w w w  .  j  a  va  2 s  .  c  o  m*/
 * @param warDirectoryPath
 * @throws IOException
 */
public void extractSarDeploy(ClassLoader cL, Object... args) throws IOException {
    CopyOnWriteArrayList classPath = null;
    File file = null;
    String fileName = "";
    String fileWithPath = "";
    if (args[0] instanceof File) {
        classPath = new CopyOnWriteArrayList();
        file = (File) args[0];
        fileWithPath = file.getAbsolutePath();
        ZipFile zip = new ZipFile(file);
        ZipEntry ze = null;
        fileName = file.getName();
        fileName = fileName.substring(0, fileName.indexOf('.'));
        fileName += "sar";
        String fileDirectory;
        Enumeration<? extends ZipEntry> entries = zip.entries();
        int numBytes;
        while (entries.hasMoreElements()) {
            ze = entries.nextElement();
            // //log.info("Unzipping " + ze.getName());
            String filePath = serverConfig.getDeploydirectory() + "/" + fileName + "/" + ze.getName();
            if (!ze.isDirectory()) {
                fileDirectory = filePath.substring(0, filePath.lastIndexOf('/'));
            } else {
                fileDirectory = filePath;
            }
            // //log.info(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();
    } else if (args[0] instanceof FileObject) {
        FileObject fileObj = (FileObject) args[0];
        fileName = fileObj.getName().getBaseName();
        try {
            fileWithPath = fileObj.getURL().toURI().toString();
        } catch (URISyntaxException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        fileName = fileName.substring(0, fileName.indexOf('.'));
        fileName += "sar";
        classPath = unpack(fileObj, new File(serverConfig.getDeploydirectory() + "/" + fileName + "/"),
                (StandardFileSystemManager) args[1]);
    }
    URLClassLoader loader = (URLClassLoader) ClassLoader.getSystemClassLoader();
    URL[] urls = loader.getURLs();
    WebClassLoader sarClassLoader;
    if (cL != null) {
        sarClassLoader = new WebClassLoader(urls, cL);
    } else {
        sarClassLoader = new WebClassLoader(urls);
    }
    for (int index = 0; index < classPath.size(); index++) {
        // log.info("file:"+classPath.get(index));
        sarClassLoader.addURL(new URL("file:" + classPath.get(index)));
    }
    sarClassLoader.addURL(new URL("file:" + serverConfig.getDeploydirectory() + "/" + fileName + "/"));
    //log.info(sarClassLoader.geturlS());
    sarsMap.put(fileWithPath, sarClassLoader);
    try {
        Sar sar = (Sar) sardigester.parse(new InputSource(new FileInputStream(
                serverConfig.getDeploydirectory() + "/" + fileName + "/META-INF/" + "mbean-service.xml")));
        CopyOnWriteArrayList mbeans = sar.getMbean();
        //log.info(mbeanServer);
        ObjectName objName, classLoaderObjectName = new ObjectName("com.app.server:classLoader=" + fileName);
        if (!mbeanServer.isRegistered(classLoaderObjectName)) {
            mbeanServer.registerMBean(sarClassLoader, classLoaderObjectName);
        } else {
            mbeanServer.unregisterMBean(classLoaderObjectName);
            mbeanServer.registerMBean(sarClassLoader, classLoaderObjectName);
            ;
        }
        for (int index = 0; index < mbeans.size(); index++) {
            Mbean mbean = (Mbean) mbeans.get(index);
            //log.info(mbean.getObjectname());
            //log.info(mbean.getCls());
            objName = new ObjectName(mbean.getObjectname());
            Class service = sarClassLoader.loadClass(mbean.getCls());
            if (mbeanServer.isRegistered(objName)) {
                //mbs.invoke(objName, "stopService", null, null);
                //mbs.invoke(objName, "destroy", null, null);
                mbeanServer.unregisterMBean(objName);
            }
            mbeanServer.createMBean(service.getName(), objName, classLoaderObjectName);
            //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());
                    mbeanServer.setAttribute(objName, mbeanattribute);
                }
            }
            Attribute mbeanattribute = new Attribute("ObjectName", objName);
            mbeanServer.setAttribute(objName, mbeanattribute);
            if (((String) mbeanServer.getAttribute(objName, "Deployer")).equals("true")) {
                mbeanServer.invoke(objName, "init", new Object[] { deployerList },
                        new String[] { Vector.class.getName() });

            }
            mbeanServer.invoke(objName, "init", new Object[] { serviceList, serverConfig, mbeanServer },
                    new String[] { Vector.class.getName(), ServerConfig.class.getName(),
                            MBeanServer.class.getName() });
            mbeanServer.invoke(objName, "start", null, null);
            serviceListObjName.put(fileWithPath, objName);
        }
    } catch (Exception e) {
        log.error("Could not able to deploy sar archive " + fileWithPath, e);
        // TODO Auto-generated catch block
        //e.printStackTrace();
    }
}

From source file:io.fabric8.jolokia.assertions.JolokiaAssert.java

protected Object operationResult(String mbean, String operation, Object... arguments)
        throws MalformedObjectNameException, J4pException {
    ObjectName objectName = new ObjectName(mbean);
    J4pResponse<J4pExecRequest> results = client.execute(new J4pExecRequest(objectName, operation, arguments));
    return results.getValue();
}