1   package com.mccrory.scott.spumoni;
2   
3   ////////////////////////////////////////////////////////////////////////////////
4   // SnmpTrapAgent is an adaptation of JoeSNMP's SnmpAgent test class, which
5   // is a part of the OpenNMS project (http://www.opennms.org).  Thanks go out
6   // to Brian Weaver and the rest of the OpenNMS crew for their excellent work.
7   //
8   // This library is free software; you can redistribute it and/or
9   // modify it under the terms of the GNU Lesser General Public
10  // License as published by the Free Software Foundation; either
11  // version 2.1 of the License, or (at your option) any later version.
12  //
13  // (Also available online at http://www.fsf.org/copyleft/lesser.html)
14  //
15  // This library is distributed in the hope that it will be useful,
16  // but WITHOUT ANY WARRANTY; without even the implied warranty of
17  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18  // Lesser General Public License for more details.
19  //
20  // You should have received a copy of the GNU Lesser General Public
21  // License along with this library; if not, write to the Free Software
22  // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
23  ////////////////////////////////////////////////////////////////////////////////
24  
25  // Imports from Java API
26  import java.io.IOException;
27  import java.io.ObjectInputStream;
28  import java.io.ObjectOutputStream;
29  import java.net.InetAddress;
30  
31  import org.opennms.protocols.snmp.SnmpHandler;
32  import org.opennms.protocols.snmp.SnmpIPAddress;
33  import org.opennms.protocols.snmp.SnmpObjectId;
34  import org.opennms.protocols.snmp.SnmpOctetString;
35  import org.opennms.protocols.snmp.SnmpParameters;
36  import org.opennms.protocols.snmp.SnmpPduPacket;
37  import org.opennms.protocols.snmp.SnmpPduRequest;
38  import org.opennms.protocols.snmp.SnmpPduTrap;
39  import org.opennms.protocols.snmp.SnmpPeer;
40  import org.opennms.protocols.snmp.SnmpSMI;
41  import org.opennms.protocols.snmp.SnmpSession;
42  import org.opennms.protocols.snmp.SnmpSyntax;
43  import org.opennms.protocols.snmp.SnmpVarBind;
44  
45  /**
46   * <P><code>SnmpTrapAgent</code> is a class that sends SNMP V1 or V2 traps to
47   * one (and only one) SNMP manager defined by its IP address and port number.
48   * SnmpTrapAgent is an adaptation of JoeSNMP's SnmpAgent test class, which
49   * is a part of the <A HREF="http://www.opennms.org">OpenNMS</a> project.
50   * Thanks go out to Brian Weaver and the rest of the OpenNMS crew for their
51   * excellent work.</P>
52   *
53   * @author  <A HREF="mailto:weave@opennms.org">Brian Weaver</A>
54   * @author  <A HREF="http://www.opennms.org/">OpenNMS</A>
55   * @author <a href="mailto:smccrory@users.sourceforge.net">Scott McCrory</a>.
56   * @version CVS $Id: SnmpTrapAgent.java,v 1.8 2002/08/04 22:04:53 smccrory Exp $
57   */
58  public class SnmpTrapAgent implements SnmpHandler {
59  
60      /** The name of this class to log context without introspection **/
61      private static final String CLASS_NAME = "SnmpTrapAgent";
62  
63      /** The version of this class (filled in by CVS) **/
64      private static final String VERSION = "CVS $Revision: 1.8 $";
65  
66      /** SNMP parameter for community */
67      private static final String PARAM_COMMUNITY = "public";
68  
69      /** SNMP parameter for number of retries */
70      private static final int PARAM_RETRIES = 10;
71  
72      /** SNMP parameter for timeout */
73      private static final int PARAM_TIMEOUT = 5000;
74  
75      /** SNMP parameter for generic type (V1 only) */
76      private static final int PARAM_GENERIC_TYPE = 0;
77  
78      /** SNMP parameter for specific type (V1 only) */
79      private static final int PARAM_SPECIFIC_TYPE = 0;
80  
81      /** SNMP OID of the sent trap */
82      private String m_trapOid;
83  
84      /** Holds the reference to the SNMP session */
85      private SnmpSession m_session;
86  
87      /**
88       * Builds an snmpagent object for sending SNMP V1 or V2 traps. <P>
89       *
90       * Remark : The SNMP trap type (V1 or V2) will be set every time a trap is 
91       *          sent in the respectie send method.
92       *
93       * @param managerAddress the IP address where the traps are sent
94       * @param managerPort the port number where the traps are sent (e.g. 162)
95       * @param trapOid the complete OID for the trap (e.g. "1.3.6.1.2.1.1232.1.1")
96       * @throws Exception if an error occurs during the initialization
97       *            of the object
98       */
99      public SnmpTrapAgent(String managerAddress, int managerPort, String trapOid)
100         throws Exception {
101 
102         // Memorize attributes
103         m_trapOid = trapOid;
104 
105         // Build the SNMP session
106         try {
107             // Create the peer object
108             SnmpPeer peer = new SnmpPeer(InetAddress.getByName(managerAddress));
109             peer.setPort(managerPort);
110             peer.setRetries(PARAM_RETRIES);
111             peer.setTimeout(PARAM_TIMEOUT);
112             SnmpParameters parameters = peer.getParameters();
113             parameters.setReadCommunity(PARAM_COMMUNITY);
114 
115             // Create the session object
116             m_session = new SnmpSession(peer);
117             m_session.setDefaultHandler(this);
118         }
119         catch (Exception e) {
120             System.out.println("SNMP agent creation error");
121         }
122     }
123 
124     /**
125      * We override the <code>clone</code> method here to prevent cloning of our class.
126      *
127      * @return Nothing ever really returned since we throw a CloneNotSupportedException
128      * @throws CloneNotSupportedException To indicate cloning is not allowed
129      **/
130     public final Object clone() throws CloneNotSupportedException {
131 
132         throw new CloneNotSupportedException();
133 
134     }
135 
136     /**
137      * Closes the SNMP session.
138      */
139     public void close() {
140         m_session.close();
141     }
142 
143     /**
144      * For unit testing.
145      *
146      * @param args an array of command-line arguments
147      */
148     public static void main(String[] args) {
149 
150         try {
151 
152             System.out.println("Starting...");
153             SnmpTrapAgent sa = new SnmpTrapAgent("localhost", 161, "1.3.6.1.2.1.1232.1.1");
154 
155             sa.sendV1Trap("V1 Link Up");
156             sa.sendV2Trap("V1 Link Down");
157 
158             sa.close();
159             System.out.println("Done...");
160 
161         }
162         catch (Exception e) {
163             e.printStackTrace();
164             System.exit(0);
165         }
166 
167     }
168 
169     /**
170      * We override the <code>readObject</code> method here to prevent
171      * deserialization of our class for security reasons.
172      *
173      * @param in java.io.ObjectInputStream
174      * @throws IOException thrown if a problem occurs
175      **/
176     private final void readObject(ObjectInputStream in) throws IOException {
177 
178         throw new IOException("Object cannot be deserialized");
179 
180     }
181 
182     /**
183      * Sends a formatted message as SNMP V1 trap.
184      *
185      * @param message the formatted text to send
186      * @throws Exception if an error occurs during the sending of the trap
187      */
188     public void sendV1Trap(String message) throws Exception {
189 
190         try {
191             // Set SNMP version as V1
192             SnmpPeer peer = m_session.getPeer();
193             SnmpParameters parameters = peer.getParameters();
194             parameters.setVersion(SnmpSMI.SNMPV1);
195 
196             // Create trap
197             SnmpPduTrap trapPdu = new SnmpPduTrap();
198             trapPdu.setAgentAddress(
199                 new SnmpIPAddress(InetAddress.getLocalHost().getAddress()));
200             trapPdu.setGeneric(PARAM_GENERIC_TYPE);
201             trapPdu.setSpecific(PARAM_SPECIFIC_TYPE);
202             trapPdu.addVarBind(
203                 new SnmpVarBind(
204                     new SnmpObjectId(m_trapOid),
205                     new SnmpOctetString(message.getBytes())));
206 
207             // Send trap
208             m_session.send(trapPdu);
209 
210         }
211         catch (Exception e) {
212             System.out.println("SNMP send error");
213         }
214 
215     }
216 
217     /**
218      * Sends a formatted message as SNMP V2 trap.
219      *
220      * @param message the formatted text to send
221      * @throws Exception if an error occurs during the sending of the trap
222      */
223     public void sendV2Trap(String message) throws Exception {
224 
225         try {
226             // Set SNMP version as V2
227             SnmpPeer peer = m_session.getPeer();
228             SnmpParameters parameters = peer.getParameters();
229             parameters.setVersion(SnmpSMI.SNMPV2);
230 
231             // Create trap
232             SnmpPduRequest trapPdu = new SnmpPduRequest(SnmpPduPacket.V2TRAP);
233             trapPdu.addVarBind(
234                 new SnmpVarBind(
235                     new SnmpObjectId(m_trapOid),
236                     new SnmpOctetString(message.getBytes())));
237 
238             // Send trap
239             m_session.send(trapPdu);
240 
241         }
242         catch (Exception e) {
243             System.out.println("SNMP send error");
244         }
245 
246     }
247 
248     /**
249      * Stubbed out since we are only sending
250      *
251      * @param session The SnmpSession we're communicating with
252      * @param err     The error number
253      * @param pdu     The SNMP Packet Data Unit
254      */
255     public void snmpInternalError(SnmpSession session, int err, SnmpSyntax pdu) {
256         System.out.println("SNMP internal error, code: " + err);
257     }
258 
259     /**
260      * Stubbed out since we are only sending
261      *
262      * @param session The SnmpSession we're communicating with
263      * @param cmd     The SNMP command
264      * @param pdu     The SNMP Packet Data Unit
265      */
266     public void snmpReceivedPdu(SnmpSession session, int cmd, SnmpPduPacket pdu) {
267 
268         // Just print any incoming SNMP messages
269         System.out.println("SnmpSession=" + session);
270         System.out.println("cmd=" + cmd);
271         System.out.println("SnmpPduPacket=" + pdu);
272 
273     }
274 
275     /**
276      * Stubbed out since we are only sending
277      *
278      * @param session The SnmpSession we're communicating with
279      * @param pdu     The SNMP Packet Data Unit
280      */
281     public void snmpTimeoutError(SnmpSession session, SnmpSyntax pdu) {
282         System.out.println("SNMP timeout");
283     }
284 
285     /**
286      * We override the <code>writeObject</code> method here to prevent
287      * serialization of our class for security reasons.
288      *
289      * @param out java.io.ObjectOutputStream
290      * @throws IOException thrown if a problem occurs
291      **/
292     private final void writeObject(ObjectOutputStream out) throws IOException {
293 
294         throw new IOException("Object cannot be serialized");
295 
296     }
297 }