⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 agent.java

📁 mobile to system control
💻 JAVA
字号:
/* *   This file is part of MobiMon. * *   MobiMon is free software; you can redistribute it and/or modify *   it under the terms of the GNU General Public License as published by *   the Free Software Foundation; either version 2 of the License, or *   (at your option) any later version. * *   MobiMon is distributed in the hope that it will be useful, *   but WITHOUT ANY WARRANTY; without even the implied warranty of *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the *   GNU General Public License for more details. *   You should have received a copy of the GNU General Public License *   along with MobiMon; if not, write to the Free Software *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA *//* * Agent.java * * Created on February 14, 2003, 9:43 PM */package mobimon.agent;import java.util.*;import java.util.logging.*;import javax.management.*;import javax.management.loading.*;import javax.management.monitor.*;import com.sun.jdmk.comm.CommunicatorServer;import com.sun.jdmk.comm.RmiConnectorServer;import mobimon.mbeans.*;/** * * @author  jan */public class Agent {        private MBeanServer server;        private CommunicatorServer rmiConnector;        private MLet mlet;        private static final String AGENT_RESOURCE_FILE = "conf.Agent";        private Logger agentLogger = Logger.getLogger("mobimon.agent");        private MonCreator monCreator = null;        public Agent() {        try {            FileHandler fh = new FileHandler("log/Agent.log", 50000, 5);            fh.setFormatter(new SimpleFormatter());            agentLogger.addHandler(fh);        } catch (java.io.IOException ioe) {            ioe.printStackTrace();        }        agentLogger.setLevel(Level.ALL);        agentLogger.info("Creating base components");        // Create a MBeanServer        server = MBeanServerFactory.createMBeanServer();        agentLogger.info("MBean Server created");        rmiConnector = new RmiConnectorServer();        agentLogger.info("RMI Connector created");        monCreator = new MonCreator();        agentLogger.info("Monitor creation ready");        mlet = new MLet();        try {            String domain = server.getDefaultDomain();            server.registerMBean(mlet, new ObjectName(domain + ":type=MLetService"));            agentLogger.info("m-let Service created and registered");        } catch (Exception e) {            e.printStackTrace();        }    }        public static void main(String[] args) {        Agent agent = new Agent();        ResourceBundle agentResources = readProperties();        agent.log("Properties read");        String myURL = agent.getProperty(agentResources, "Agent.MLetURL");        if (myURL != null) {            agent.loadMBeans(myURL);            agent.log("MBeans read from m-let file");        }        agent.logAvailableBeans();        agent.initializeMonitors();        agent.initCommunication();        agent.log("Communication service ready");    }        private static void sleep(int millis) {        try {            Thread.sleep(millis);        } catch (InterruptedException e) {            return;        }    }        private void initCommunication() {        try {            ObjectInstance rmiConnectorInstance =            server.registerMBean(rmiConnector, null);        } catch(Exception e) {            e.printStackTrace();            System.exit(-1);        }                // Now we explivitly start the RMI connector server as it is not started automatically        //        rmiConnector.start();                // waiting to leave starting state...        while (rmiConnector.getState() == CommunicatorServer.STARTING) {            sleep(1000);        }    }        private void loadMBeans(String mBeanURL) {        try {            Set loadedMBeans = mlet.getMBeansFromURL(mBeanURL);            Iterator i = loadedMBeans.iterator();            while (i.hasNext()) {                Object o = i.next();                if (o instanceof Throwable) {                    agentLogger.log(Level.WARNING, "Error loading MBean", (Throwable)o);                }            }        } catch (ServiceNotFoundException snfe) {            System.out.println("Couldn't load M-LET file from "            + mBeanURL + ": " + snfe.getMessage());        }    }        private static ResourceBundle readProperties() {        ResourceBundle rb;        try {            rb = ResourceBundle.getBundle(AGENT_RESOURCE_FILE);        } catch (MissingResourceException mre) {            rb = null;        }        return rb;    }        private String getProperty(ResourceBundle rb, String key) {        if (rb == null) return null;        String retVal = null;        try {            retVal = rb.getString(key);        } catch (MissingResourceException mre) {}        return retVal;    }        private void log(String message) {        agentLogger.info(message);    }        private void logAvailableBeans() {        Set allMBeans = server.queryNames(null, null);        Iterator i = allMBeans.iterator();        while (i.hasNext()) {            ObjectName on = (ObjectName)i.next();            log(on.getCanonicalName());        }    }        private void initializeMonitors() {        try {            server.registerMBean(monCreator, null);        } catch (Exception e) {            e.printStackTrace();            System.exit(-1);        }        Set allMBeans = server.queryNames(null, null);        Iterator it = allMBeans.iterator();        while (it.hasNext()) {            ObjectName on = (ObjectName)it.next();            String beanPropertyFile =            "conf/" + on.getCanonicalName().replace(':', '_');            try {                ResourceBundle beanResources =                ResourceBundle.getBundle(beanPropertyFile);                String monitors = beanResources.getString("mbean.monitors");                StringTokenizer st = new StringTokenizer(monitors);                while (st.hasMoreTokens()) {                    String monitorKey = st.nextToken();                    try {                        String monitorType =                        beanResources.getString(monitorKey + ".type");                        if (monitorType.equalsIgnoreCase("counter")) {                            createCounterMonitor(on, monitorKey, beanResources);                        } else if (monitorType.equalsIgnoreCase("gauge")) {                            createGaugeMonitor(on, monitorKey, beanResources);                        } else if (monitorType.equalsIgnoreCase("string")) {                            createStringMonitor(on, monitorKey, beanResources);                        } else {                            log("Unknown monitor type " + monitorType +                            " for MBean " + on.getCanonicalName());                            continue;                        }                        log("Created " + monitorType + " monitor for MBean "                        + on.getCanonicalName());                    } catch (Exception e) {                        log(e.getClass().getName() + ": " + e.getMessage());                    }                }            } catch (MissingResourceException mre) { /* ignore */ }        }    }        private void createGaugeMonitor    (ObjectName mbean, String monitorKey, ResourceBundle beanResources)    throws Exception {        String toObserve = beanResources.getString(monitorKey + ".attribute");        String howOften = beanResources.getString(monitorKey + ".interval");        String highValue = beanResources.getString(monitorKey + ".high");        String lowValue = beanResources.getString(monitorKey + ".low");        String type = getAttributeType(mbean, toObserve);        String diffMode = getProperty(beanResources, monitorKey + ".diffMode");        boolean differenceMode = (diffMode != null) && diffMode.equals("true");        String notifyIf = getProperty(beanResources, monitorKey + ".events");        boolean notifyHigh = false;        boolean notifyLow = false;        if (notifyIf != null) {            StringTokenizer st = new StringTokenizer(notifyIf);            while (st.hasMoreTokens()) {                String event = st.nextToken();                if (event.equals("high")) {                    notifyHigh = true;                } else if (event.equals("low")) {                    notifyLow = true;                }            }        }        monCreator.createGaugeMonitor(mbean, toObserve,        howOften != null ? Long.parseLong(howOften) * 1000 : 0L,        convert(highValue, type), convert(lowValue, type), differenceMode,        notifyHigh, notifyLow);    }        private void createCounterMonitor    (ObjectName mbean, String monitorKey, ResourceBundle beanResources)    throws Exception {        String toObserve = beanResources.getString(monitorKey + ".attribute");        String howOften = beanResources.getString(monitorKey + ".interval");        String threshold = beanResources.getString(monitorKey + ".threshold");        String type = getAttributeType(mbean, toObserve);        String offset = getProperty(beanResources, monitorKey + ".offset");        String modulus = getProperty(beanResources, monitorKey + ".modulus");        String diffMode = getProperty(beanResources, monitorKey + ".diffMode");        boolean differenceMode = (diffMode != null) && diffMode.equals("true");        String notifyOn = getProperty(beanResources, monitorKey + ".notifyOn");        boolean notify = (notifyOn != null) && notifyOn.equals("true");        monCreator.createCounterMonitor(mbean, toObserve,        howOften != null ? Long.parseLong(howOften) * 1000 : 0L,        convert(threshold, type),        offset != null ? convert(offset, type) : convert("0", type),        modulus != null ? convert(modulus, type) : convert("0", type),        differenceMode, notify);    }        private void createStringMonitor    (ObjectName mbean, String monitorKey, ResourceBundle beanResources)    throws Exception {        String toObserve = beanResources.getString(monitorKey + ".attribute");        String toCompare = beanResources.getString(monitorKey + ".compareWith");        String howOften = getProperty(beanResources, monitorKey + ".interval");        String notifyIf = getProperty(beanResources, monitorKey + ".events");        boolean notifyMatch = false;        boolean notifyDiffer = false;        if (notifyIf != null) {            StringTokenizer st = new StringTokenizer(notifyIf);            while (st.hasMoreTokens()) {                String event = st.nextToken();                if (event.equals("match")) {                    notifyMatch = true;                } else if (event.equals("differ")) {                    notifyDiffer = true;                }            }        }        monCreator.createStringMonitor(mbean, toObserve,        howOften != null ? Long.parseLong(howOften) * 1000 : 0L,        toCompare, notifyDiffer, notifyMatch);    }        private static Number convert(String toConvert, String dataType)    throws NumberFormatException {        if (dataType.equals("int")        || dataType.equals("java.lang.Integer")) {            return new Integer(Integer.parseInt(toConvert));        } else if (dataType.equals("byte")        || dataType.equals("java.lang.Byte")) {            return new Byte(Byte.parseByte(toConvert));        } else if (dataType.equals("short")        || dataType.equals("java.lang.Short")) {            return new Short(Short.parseShort(toConvert));        } else if (dataType.equals("long")        || dataType.equals("java.lang.Long")) {            return new Long(Long.parseLong(toConvert));        } else if (dataType.equals("float")        || dataType.equals("java.lang.Float")) {            return new Float(Float.parseFloat(toConvert));        } else if (dataType.equals("double")        || dataType.equals("java.lang.Double")) {            return new Double(Double.parseDouble(toConvert));        }        return null;    }        private String getAttributeType(ObjectName mbean, String attributeName)    throws AttributeNotFoundException, InstanceNotFoundException,    IntrospectionException, ReflectionException {        MBeanInfo mbi = server.getMBeanInfo(mbean);        MBeanAttributeInfo[] mai = mbi.getAttributes();        String type = null;        for (int i = 0; i < mai.length; i++) {            if (mai[i].getName().equals(attributeName)) {                type = mai[i].getType();                break;            }        }        if (type == null) throw new AttributeNotFoundException("No attribute "        + attributeName + " in MBean " + mbean.getCanonicalName());        return type;    }    }

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -