snmpsession.java

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

JAVA
1,043
字号
//// 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://// 2003 Mar 20: Added code to allow the joeSNMP library to answer SNMP requests//              to be used in creating SNMP agents.//// 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//// SnmpSession.java,v 1.1.1.1 2001/11/11 17:27:22 ben Exp//////// History:////	3/29/00 Weave//		Made some minor changes here and there, but the biggest change//		is from ArrayList to LinkedList for the outstanding request. I //		realized that the session was mostly adding/deleting request//		and linked list was faster. When the ArrayList was being used//		the search was O(N), just like a linked list (actually N/2 on average).//		So the performance gains from the faster add/remove should help//		until a better structure for searching, adding, and deleteing //		can be used.//// 5/25/00 Sowmya//		Added the SnmpPortal member to abstract the communication related//		data out of this class. Added SnmpSessionPacketHandler to//		handle callbacks from the SnmpPortal //package org.opennms.protocols.snmp;import java.net.DatagramPacket;import java.net.InetAddress;import java.net.SocketException;import java.util.LinkedList;import java.util.ListIterator;import org.opennms.protocols.snmp.asn1.ASN1;import org.opennms.protocols.snmp.asn1.AsnEncoder;import org.opennms.protocols.snmp.asn1.AsnEncodingException;/** * <P> * The SnmpSession is the main connection between the SNMP manager and the SNMP * Agent. All the request flow through this class. To use the SnmpSession class * a SnmpHandler class must be defined to process any errors or responses * through the library. * </P> *  * <P> * Once the session is created the creator must call <EM>close()</EM> to * ensure an orderly release of threads and resources. * </P> *  * @author <A HREF="mailto:weave@oculan.com">Brian Weaver </A> * @author <A HREF="http://www.opennms.org/">OpenNMS </A> *  * @version 1.1.1.1 2001/11/11 17:27:22 *  * @see SnmpHandler * @see SnmpPacketHandler * @see SnmpPortal */public class SnmpSession extends Object {    /**     * This is the command passed to the SnmpHandler if a timeout occurs. All     * errors are less than zero.     *      * @see SnmpHandler     */    public static final int ERROR_TIMEOUT = -1;    /**     * This is the command passed to the SnmpHandler if an IOException occurs     * while attempting to transmit the request     *      * @see SnmpHandler     */    public static final int ERROR_IOEXCEPTION = -2;    /**     * This is the command passed to the SnmpHandler if an encoding exception is     * generated when attempting to send an SnmpPduRequest message     *      * @see SnmpHandler     */    public static final int ERROR_ENCODING = -3;    /**     * Used to contain a list of outstanding request for the session. The list     * should only contain SnmpRequest objects!     */    private LinkedList m_requests;    /**     * The SNMP peer to whom this session will communicate with. The peer     * contains the parameters also.     *      * @see SnmpParameters     */    private SnmpPeer m_peer;    /**     * The timer object used to schedule the SnmpRequest timeouts. It is also     * used to schedule the cleanup of the m_requests list.     *      * @see org.opennms.protocols.snmp.SnmpSession.CleanupRequest     * @see SnmpRequest     */    private SnmpTimer m_timer;    /**     * The default SNMP callback handler. If this is not set and it is needed     * then an SnmpHandlerNotDefinedException is thrown.     */    private SnmpHandler m_defHandler;    /**     * ASN encoder     */    AsnEncoder m_encoder;    //    // thread related stuff    //    /**     * Provides a synchronization point     */    private Object m_sync;    /**     * If the boolean variable is set then the destroy() method must have been     * called     */    private boolean m_stopRun;    /**     * the receiver thread     */    private SnmpPortal m_portal;    /**     * If this boolean value is set then the receiver thread is terminated due     * to an exception that was generated in either a handler or a socket error.     * This is considered a fatal exception.     */    private boolean m_threadException;    /**     * This is the saved fatal excetion that can be rethrown by the application     */    private Throwable m_why;    /**     * Inner class SessionHandler implements the interface SnmpPacketHandler to     * handle callbacks from the SnmpPortal     */    private class SessionHandler implements SnmpPacketHandler {        public void processSnmpMessage(InetAddress agent, int port, SnmpInt32 version, SnmpOctetString community, int pduType, SnmpPduPacket pdu) throws SnmpPduEncodingException {            //            // now find the request and            // inform            //            boolean isExpired = false;            SnmpRequest req = null;            synchronized (m_requests) {                //                // ensures that we get the proper                // state information                //                req = findRequest(pdu);                if (req != null)                    isExpired = req.m_expired;            }            if (isExpired == false) {                int cmd = -1;                if (req != null && req.m_pdu instanceof SnmpPduPacket)                    cmd = ((SnmpPduPacket) req.m_pdu).getCommand();                else {                    cmd = pdu.getCommand();                    pdu.setPeer(new SnmpPeer(agent, port));                }                switch (cmd) {                case SnmpPduPacket.SET: {                    String tst = new String(community.getString());                    String wr = m_peer.getParameters().getWriteCommunity();                    if (!tst.equals(wr)) {                        throw new SnmpPduEncodingException("Invalid community string");                    }                }                    break;                case SnmpPduPacket.GET:                case SnmpPduPacket.GETNEXT:                case SnmpPduPacket.RESPONSE:                case SnmpPduPacket.INFORM:                case SnmpPduPacket.GETBULK:                case SnmpPduPacket.REPORT: {                    String tst = new String(community.getString());                    String rd = m_peer.getParameters().getReadCommunity();                    if (!tst.equals(rd)) {                        throw new SnmpPduEncodingException("Invalid community string");                    }                }                    break;                default:                    throw new SnmpPduEncodingException("Invalid PDU Type for session received");                }                if (req != null) {                    req.m_expired = true; // mark it as expired                    req.m_handler.snmpReceivedPdu(req.m_session, ((SnmpPduRequest) pdu).getCommand(), (SnmpPduRequest) pdu);                } else {                    if (m_defHandler != null)                        m_defHandler.snmpReceivedPdu(null, cmd, pdu);                }            }        }        public void processSnmpTrap(InetAddress agent, int port, SnmpOctetString community, SnmpPduTrap pdu) throws SnmpPduEncodingException {            throw new SnmpPduEncodingException("Invalid PDU Type for session");        }        public void processBadDatagram(DatagramPacket p) {            // do nothing - discard?        }        public void processException(Exception e) {            // do nothing - discard?        }    }    /**     * This class is used to periodically cleanup the outstanding request that     * have expired. The cleanup interval is nominally once every 5 to 10     * seconds. It's used like the garbage collector for the m_requests list.     * This is used in hopes of minimizing the contention for the request array     *      */    private class CleanupRequest implements Runnable {        /**         * Preforms the actual removal of the expired SnmpRequest elements.         *          * @see SnmpRequest         *          */        public void run() {            synchronized (m_requests) {                if (m_requests.size() > 0) {                    ListIterator iter = m_requests.listIterator(0);                    while (iter.hasNext()) {                        SnmpRequest req = (SnmpRequest) iter.next();                        if (req.m_expired)                            iter.remove();                    }                }            }            //            // reschedule            //            if (!m_stopRun && !m_threadException)                m_timer.schedule(this, 1000);        }    }    /**     * <P>     * Encapsulates a byte array and the number of bytes of valid data in the     * array. The length passed to the constructor is normally less then the     * length of the encapsulated array.     * </P>     *      */    private static class ByteArrayInfo {        /**         * The buffer         */        private byte[] m_buf;        /**         * The valid length of the buffer         */        private int m_length;        /**         * Builds an encapuslated array with the passed buffer and its <EM>         * valid</EM> length set to <EM>length</EM>.         *          * @param buf         *            The buffer.         * @param length         *            The valid length of the buffer.         */        public ByteArrayInfo(byte[] buf, int length) {            m_buf = buf;            m_length = length;        }        /**         * returns the encapsulated array         */        public byte[] array() {            return m_buf;        }        /**         * Returns the valid length of the encapsulate array         */        public int size() {            return m_length;        }    }

⌨️ 快捷键说明

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