snmppeerfactory.java

来自「opennms得相关源码 请大家看看」· Java 代码 · 共 805 行 · 第 1/3 页

JAVA
805
字号
//// This file is part of the OpenNMS(R) Application.//// OpenNMS(R) is Copyright (C) 2002-2003 The OpenNMS Group, Inc.  All rights reserved.// OpenNMS(R) is a derivative work, containing both original code, included code and modified// code that was published under the GNU General Public License. Copyrights for modified // and included code are below.//// OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.//// Modifications://// 2005 Mar 08: Added saveCurrent, optimize, and define methods.// 2003 Jan 31: Cleaned up some unused imports.//// Original code base Copyright (C) 1999-2001 Oculan Corp.  All rights reserved.//// This program 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.//// This program 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 this program; if not, write to the Free Software// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.//       // For more information contact: //      OpenNMS Licensing       <license@opennms.org>//      http://www.opennms.org///      http://www.opennms.com///// Tab Size = 8//package org.opennms.netmgt.config;import java.io.File;import java.io.FileInputStream;import java.io.FileWriter;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.StringWriter;import java.net.InetAddress;import java.net.UnknownHostException;import java.util.ArrayList;import java.util.Enumeration;import java.util.Iterator;import java.util.TreeMap;import org.apache.log4j.Category;import org.exolab.castor.xml.MarshalException;import org.exolab.castor.xml.Marshaller;import org.exolab.castor.xml.Unmarshaller;import org.exolab.castor.xml.ValidationException;import org.opennms.core.utils.ThreadCategory;import org.opennms.netmgt.ConfigFileConstants;import org.opennms.netmgt.config.capsd.Definition;import org.opennms.netmgt.config.capsd.Range;import org.opennms.netmgt.config.capsd.SnmpConfig;import org.opennms.protocols.ip.IPv4Address;import org.opennms.protocols.snmp.SnmpParameters;import org.opennms.protocols.snmp.SnmpPeer;import org.opennms.protocols.snmp.SnmpSMI;/** * This class is the main respository for SNMP configuration information used by * the capabilities daemon. When this class is loaded it reads the snmp * configuration into memory, and uses the configuration to find the * {@link org.opennms.protocols.snmp.SnmpPeer SnmpPeer}objects for specific * addresses. If an address cannot be located in the configuration then a * default peer instance is returned to the caller. *  * <strong>Note: </strong>Users of this class should make sure the * <em>init()</em> is called before calling any other method to ensure the * config is loaded before accessing other convenience methods. *  * @author <a href="mailto:weave@oculan.com">Weave </a> * @author <a href="mailto:gturner@newedgenetworks.com">Gerald Turner </a> * @author <a href="http://www.opennms.org/">OpenNMS </a> *  */public final class SnmpPeerFactory {    /**     * The singleton instance of this factory     */    private static SnmpPeerFactory m_singleton = null;    /**     * The config class loaded from the config file     */    private static SnmpConfig m_config;    /**     * This member is set to true if the configuration file has been loaded.     */    private static boolean m_loaded = false;    /**     * Private constructor     *      * @exception java.io.IOException     *                Thrown if the specified config file cannot be read     * @exception org.exolab.castor.xml.MarshalException     *                Thrown if the file does not conform to the schema.     * @exception org.exolab.castor.xml.ValidationException     *                Thrown if the contents do not match the required schema.     */    private SnmpPeerFactory(String configFile) throws IOException, MarshalException, ValidationException {        InputStream cfgIn = new FileInputStream(configFile);        m_config = (SnmpConfig) Unmarshaller.unmarshal(SnmpConfig.class, new InputStreamReader(cfgIn));        cfgIn.close();    }    /**     * Load the config from the default config file and create the singleton     * instance of this factory.     *      * @exception java.io.IOException     *                Thrown if the specified config file cannot be read     * @exception org.exolab.castor.xml.MarshalException     *                Thrown if the file does not conform to the schema.     * @exception org.exolab.castor.xml.ValidationException     *                Thrown if the contents do not match the required schema.     */    public static synchronized void init() throws IOException, MarshalException, ValidationException {        if (m_loaded) {            // init already called - return            // to reload, reload() will need to be called            return;        }        File cfgFile = ConfigFileConstants.getFile(ConfigFileConstants.SNMP_CONF_FILE_NAME);        ThreadCategory.getInstance(SnmpPeerFactory.class).debug("init: config file path: " + cfgFile.getPath());        m_singleton = new SnmpPeerFactory(cfgFile.getPath());        m_loaded = true;    }    /**     * Reload the config from the default config file     *      * @exception java.io.IOException     *                Thrown if the specified config file cannot be read/loaded     * @exception org.exolab.castor.xml.MarshalException     *                Thrown if the file does not conform to the schema.     * @exception org.exolab.castor.xml.ValidationException     *                Thrown if the contents do not match the required schema.     */    public static synchronized void reload() throws IOException, MarshalException, ValidationException {        m_singleton = null;        m_loaded = false;        init();    }    /**     * Saves the current settings to disk     */    public static synchronized void saveCurrent() throws Exception {        optimize();        // Marshall to a string first, then write the string to the file. This        // way the original config        // isn't lost if the XML from the marshall is hosed.        StringWriter stringWriter = new StringWriter();        Marshaller.marshal(m_config, stringWriter);        if (stringWriter.toString() != null) {            FileWriter fileWriter = new FileWriter(ConfigFileConstants.getFile(ConfigFileConstants.SNMP_CONF_FILE_NAME));            fileWriter.write(stringWriter.toString());            fileWriter.flush();            fileWriter.close();        }        reload();    }    /**     * Combine specific and range elements so that SnmpPeerFactory has to spend     * less time iterating all these elements.     */    private static void optimize() throws UnknownHostException {        Category log = ThreadCategory.getInstance(SnmpPeerFactory.class);        // First pass: Remove empty definition elements        for (Iterator definitionsIterator =                 m_config.getDefinitionCollection().iterator();             definitionsIterator.hasNext();) {            Definition definition =                (Definition) definitionsIterator.next();            if (definition.getSpecificCount() == 0                && definition.getRangeCount() == 0) {                if (log.isDebugEnabled())                    log.debug("optimize: Removing empty definition element");                definitionsIterator.remove();            }        }        // Second pass: Replace single IP range elements with specific elements        for (Iterator definitionsIterator =                 m_config.getDefinitionCollection().iterator();             definitionsIterator.hasNext();) {            Definition definition =                (Definition) definitionsIterator.next();            for (Iterator rangesIterator =                     definition.getRangeCollection().iterator();                 rangesIterator.hasNext();) {                Range range = (Range) rangesIterator.next();                if (range.getBegin().equals(range.getEnd())) {                    definition.addSpecific(range.getBegin());                    rangesIterator.remove();                }            }        }        // Third pass: Sort specific and range elements for improved XML        // readability and then combine them into fewer elements where possible        for (Iterator definitionsIterator =                 m_config.getDefinitionCollection().iterator();             definitionsIterator.hasNext();) {            Definition definition =                (Definition) definitionsIterator.next();            // Sort specifics            TreeMap specificsMap = new TreeMap();            for (Iterator specificsIterator =                     definition.getSpecificCollection().iterator();                 specificsIterator.hasNext();) {                String specific = (String) specificsIterator.next();                specificsMap.put(new Integer(new IPv4Address(specific).getAddress()),                                 specific);            }            // Sort ranges            TreeMap rangesMap = new TreeMap();            for (Iterator rangesIterator =                     definition.getRangeCollection().iterator();                 rangesIterator.hasNext();) {                Range range = (Range) rangesIterator.next();                rangesMap.put(new Integer(new IPv4Address(range.getBegin()).getAddress()),                              range);            }            // Combine consecutive specifics into ranges            Integer priorSpecific = null;            Range addedRange = null;            for (Iterator specificsIterator =                     new ArrayList(specificsMap.keySet()).iterator();                 specificsIterator.hasNext();) {                Integer specific = (Integer) specificsIterator.next();                if (priorSpecific == null) {                    priorSpecific = specific;                    continue;                }                int specificInt = specific.intValue();                int priorSpecificInt = priorSpecific.intValue();                if (specificInt == priorSpecificInt + 1) {

⌨️ 快捷键说明

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