KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > SNMPAgentTest


1 /*
2  * SNMP Agent Test
3  *
4  * Copyright (C) 2004, Jonathan Sevy <jsevy@mcs.drexel.edu>
5  *
6  * This is free software. Redistribution and use in source and binary forms, with
7  * or without modification, are permitted provided that the following conditions
8  * are met:
9  *
10  * 1. Redistributions of source code must retain the above copyright notice, this
11  * list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright notice,
13  * this list of conditions and the following disclaimer in the documentation
14  * and/or other materials provided with the distribution.
15  * 3. The name of the author may not be used to endorse or promote products
16  * derived from this software without specific prior written permission.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
19  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
20  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
21  * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
22  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
23  * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
24  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
25  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27  *
28  */

29
30
31
32 import java.util.*;
33 import java.awt.*;
34 import javax.swing.*;
35 import javax.swing.border.*;
36 import javax.swing.plaf.*;
37 import java.awt.event.*;
38 import java.io.*;
39 import snmp.*;
40
41
42
43
44 public class SNMPAgentTest extends JFrame
45                     implements ActionListener, SNMPRequestListener, Runnable JavaDoc
46 {
47     
48     JButton clearButton;
49     JTextArea messagesArea;
50     JScrollPane messagesScroll;
51     JLabel authorLabel;
52     
53     MenuBar theMenubar;
54     Menu fileMenu;
55     MenuItem aboutItem, quitItem, setReportFileItem;
56     
57     SNMPv1AgentInterface agentInterface;
58     String JavaDoc communityName = "public";
59     
60     SNMPOctetString storedSNMPValue;
61     
62     PipedReader errorReader;
63     PipedWriter errorWriter;
64     Thread JavaDoc readerThread;
65     
66     boolean haveReportFile = false;
67     FileWriter reportFileWriter;
68     
69     
70     
71     
72     private class WindowCloseAdapter extends WindowAdapter
73     {
74         public void windowClosing(WindowEvent e)
75         {
76             readerThread.interrupt();
77             System.exit(0);
78         }
79     }
80     
81             
82     
83     public SNMPAgentTest()
84     {
85         setUpDisplay();
86         
87         storedSNMPValue = new SNMPOctetString("Original value");
88         
89         try
90         {
91             errorReader = new PipedReader();
92             errorWriter = new PipedWriter(errorReader);
93             
94             readerThread = new Thread JavaDoc(this);
95             readerThread.start();
96             
97             int version = 0; // SNMPv1
98

99             agentInterface = new SNMPv1AgentInterface(version, new PrintWriter(errorWriter));
100             agentInterface.addRequestListener(this);
101             agentInterface.setReceiveBufferSize(5120);
102             agentInterface.startReceiving();
103             
104         }
105         catch(Exception JavaDoc e)
106         {
107             messagesArea.append("Problem starting Agent Test: " + e.toString() + "\n");
108         }
109     }
110     
111     
112     
113     private void setUpDisplay()
114     {
115         
116         this.setTitle("SNMP Agent Test");
117         
118         this.getRootPane().setBorder(new BevelBorder(BevelBorder.RAISED));
119         
120         // set fonts to smaller-than-normal size, for compaction!
121
/*
122         FontUIResource appFont = new FontUIResource("SansSerif", Font.PLAIN, 10);
123         UIDefaults defaults = UIManager.getLookAndFeelDefaults();
124         Enumeration keys = defaults.keys();
125         
126         while (keys.hasMoreElements())
127         {
128             String nextKey = (String)(keys.nextElement());
129             if ((nextKey.indexOf("font") > -1) || (nextKey.indexOf("Font") > -1))
130             {
131                 UIManager.put(nextKey, appFont);
132             }
133         }
134         */

135         
136         // add WindowCloseAdapter to catch window close-box closings
137
addWindowListener(new WindowCloseAdapter());
138
139         
140         theMenubar = new MenuBar();
141         this.setMenuBar(theMenubar);
142         fileMenu = new Menu("File");
143         
144         aboutItem = new MenuItem("About...");
145         aboutItem.setActionCommand("about");
146         aboutItem.addActionListener(this);
147         fileMenu.add(aboutItem);
148         
149         setReportFileItem = new MenuItem("Set report file...");
150         setReportFileItem.setActionCommand("set report file");
151         setReportFileItem.addActionListener(this);
152         fileMenu.add(setReportFileItem);
153         
154         fileMenu.addSeparator();
155         
156         quitItem = new MenuItem("Quit");
157         quitItem.setActionCommand("quit");
158         quitItem.addActionListener(this);
159         fileMenu.add(quitItem);
160         
161         theMenubar.add(fileMenu);
162         
163         clearButton = new JButton("Clear messages");
164         clearButton.setActionCommand("clear messages");
165         clearButton.addActionListener(this);
166         
167         
168         authorLabel = new JLabel(" Version 1.0 J. Sevy, August 2003 ");
169         authorLabel.setFont(new Font("SansSerif", Font.ITALIC, 8));
170             
171         
172         messagesArea = new JTextArea(10,60);
173         messagesScroll = new JScrollPane(messagesArea);
174         
175         
176         // now set up display
177

178         
179         // set params for layout manager
180
GridBagLayout theLayout = new GridBagLayout();
181         GridBagConstraints c = new GridBagConstraints();
182         
183         c.gridwidth = 1;
184         c.gridheight = 1;
185         c.fill = GridBagConstraints.NONE;
186         c.ipadx = 0;
187         c.ipady = 0;
188         c.insets = new Insets(2,2,2,2);
189         c.anchor = GridBagConstraints.CENTER;
190         c.weightx = 0;
191         c.weighty = 0;
192         
193         
194         JPanel messagesPanel = new JPanel();
195         messagesPanel.setLayout(theLayout);
196         
197         c.gridx = 1;
198         c.gridy = 1;
199         c.anchor = GridBagConstraints.WEST;
200         JLabel messagesLabel = new JLabel("Received requests:");
201         theLayout.setConstraints(messagesLabel, c);
202         messagesPanel.add(messagesLabel);
203         
204         c.gridx = 2;
205         c.gridy = 1;
206         c.anchor = GridBagConstraints.EAST;
207         theLayout.setConstraints(clearButton, c);
208         messagesPanel.add(clearButton);
209         
210         c.fill = GridBagConstraints.BOTH;
211         c.gridx = 1;
212         c.gridy = 2;
213         c.gridwidth = 2;
214         c.weightx = .5;
215         c.weighty = .5;
216         c.anchor = GridBagConstraints.CENTER;
217         theLayout.setConstraints(messagesScroll, c);
218         messagesPanel.add(messagesScroll);
219         
220         
221         c.gridwidth = 1;
222         c.weightx = 0;
223         c.weighty = 0;
224         
225         
226         this.getContentPane().setLayout(theLayout);
227         
228         
229         c.fill = GridBagConstraints.BOTH;
230         c.gridx = 1;
231         c.gridy = 1;
232         c.weightx = .5;
233         c.weighty = .5;
234         theLayout.setConstraints(messagesPanel, c);
235         this.getContentPane().add(messagesPanel);
236         
237         c.fill = GridBagConstraints.NONE;
238         c.gridx = 1;
239         c.gridy = 2;
240         c.weightx = 0;
241         c.weighty = 0;
242         theLayout.setConstraints(authorLabel, c);
243         this.getContentPane().add(authorLabel);
244         
245         
246     }
247     
248     
249     
250     
251     
252     public void actionPerformed(ActionEvent theEvent)
253     // respond to button pushes, menu selections
254
{
255         String JavaDoc command = theEvent.getActionCommand();
256         
257     
258         if (command == "quit")
259         {
260             readerThread.interrupt();
261             System.exit(0);
262         }
263         
264         
265         if (command == "clear messages")
266         {
267             messagesArea.setText("");
268         }
269         
270         
271         if (command == "about")
272         {
273             //AboutDialog aboutDialog = new AboutDialog(this);
274
}
275         
276         
277         if (command == "set report file")
278         {
279             try
280             {
281                 FileDialog fd = new FileDialog(this, "Select report file...", FileDialog.LOAD);
282                 fd.show();
283                 
284                 if (fd.getFile() != null)
285                 {
286                     File newFile = new File(fd.getDirectory(), fd.getFile());
287                     
288                     reportFileWriter = new FileWriter(newFile);
289                     
290                     try
291                     {
292                         reportFileWriter.write("SNMP Agent Report File\n");
293                         reportFileWriter.write("Date: " + (new Date()).toString() + "\n\n");
294                         reportFileWriter.flush();
295                     }
296                     catch (IOException e)
297                     {
298                         messagesArea.append("Unable to write message to report file\n\n");
299                     }
300                     
301                     haveReportFile = true;
302                 }
303                 
304             }
305             catch (Exception JavaDoc e)
306             {
307                 messagesArea.append("Error opening report file: " + e.getMessage() + "\n");
308             }
309         }
310         
311     }
312     
313     
314     // Tried making it synchronized so error and "normal" messages won't be interleaved,
315
// but this led to hangs during testing; so guess I'll live with possible message interleaving.
316
private void writeMessage(String JavaDoc message)
317     {
318         messagesArea.append(message);
319         
320         // also write to report file, if any
321
if (haveReportFile)
322         {
323             try
324             {
325                 reportFileWriter.write(message);
326                 reportFileWriter.flush();
327             }
328             catch (IOException e)
329             {
330                 messagesArea.append("Unable to write message to report file\n\n");
331             }
332         }
333     }
334             
335     
336     
337     public SNMPSequence processRequest(SNMPPDU pdu, String JavaDoc communityName)
338         throws SNMPGetException, SNMPSetException
339     {
340         writeMessage("Got pdu:\n");
341         
342         writeMessage(" community name: " + communityName + "\n");
343         writeMessage(" request ID: " + pdu.getRequestID() + "\n");
344         writeMessage(" pdu type: ");
345         byte pduType = pdu.getPDUType();
346         switch (pduType)
347         {
348             case SNMPBERCodec.SNMPGETREQUEST:
349             {
350                 writeMessage("SNMPGETREQUEST\n");
351                 break;
352             }
353             
354             case SNMPBERCodec.SNMPGETNEXTREQUEST:
355             {
356                 writeMessage("SNMPGETNEXTREQUEST\n");
357                 break;
358             }
359             
360             case SNMPBERCodec.SNMPSETREQUEST:
361             {
362                 writeMessage("SNMPSETREQUEST\n");
363                 break;
364             }
365             
366             case SNMPBERCodec.SNMPGETRESPONSE:
367             {
368                 writeMessage("SNMPGETRESPONSE\n");
369                 break;
370             }
371             
372             case SNMPBERCodec.SNMPTRAP:
373             {
374                 writeMessage("SNMPTRAP\n");
375                 break;
376             }
377             
378             default:
379             {
380                 writeMessage("unknown\n");
381                 break;
382             }
383             
384             
385         }
386         
387         
388         
389         SNMPSequence varBindList = pdu.getVarBindList();
390         SNMPSequence responseList = new SNMPSequence();
391         
392         for (int i = 0; i < varBindList.size(); i++)
393         {
394             SNMPSequence variablePair = (SNMPSequence)varBindList.getSNMPObjectAt(i);
395             SNMPObjectIdentifier snmpOID = (SNMPObjectIdentifier)variablePair.getSNMPObjectAt(0);
396             SNMPObject snmpValue = (SNMPObject)variablePair.getSNMPObjectAt(1);
397             
398             writeMessage(" OID: " + snmpOID + "\n");
399             writeMessage(" value: " + snmpValue + "\n");
400             
401             
402             // check to see if supplied community name is ours; if not, we'll just silently
403
// ignore the request by not returning anything
404
if (!communityName.equals(this.communityName))
405             {
406                 continue;
407             }
408             
409             // we'll only respond to requests for OIDs 1.3.6.1.2.1.99.0 and 1.3.6.1.2.1.100.0
410

411             // OID 1.3.6.1.2.1.99.0: it's read-only
412
if (snmpOID.toString().equals("1.3.6.1.2.1.99.0"))
413             {
414                 if (pduType == SNMPBERCodec.SNMPSETREQUEST)
415                 {
416                     // got a set-request for our variable; throw an exception to indicate the
417
// value is read-only - the SNMPv1AgentInterface will create the appropriate
418
// error message using our supplied error index and status
419
// note that error index starts at 1, not 0, so it's i+1
420
int errorIndex = i+1;
421                     int errorStatus = SNMPRequestException.VALUE_READ_ONLY;
422                     throw new SNMPSetException("Trying to set a read-only variable!", errorIndex, errorStatus);
423                 }
424                 else if (pduType == SNMPBERCodec.SNMPGETREQUEST)
425                 {
426                     // got a get-request for our variable; send back a value - just a string
427
try
428                     {
429                         SNMPVariablePair newPair = new SNMPVariablePair(new SNMPObjectIdentifier(snmpOID.toString()), new SNMPOctetString("Boo"));
430                         //SNMPVariablePair newPair = new SNMPVariablePair(snmpOID, new SNMPOctetString("Boo"));
431
responseList.addSNMPObject(newPair);
432                     }
433                     catch (SNMPBadValueException e)
434                     {
435                         // won't happen...
436
}
437                 }
438                 
439             }
440             
441             if (snmpOID.toString().equals("1.3.6.1.2.1.100.0"))
442             {
443                 if (pduType == SNMPBERCodec.SNMPSETREQUEST)
444                 {
445                     // got a set-request for our variable; supplied value must be a string
446
if (snmpValue instanceof SNMPOctetString)
447                     {
448                         // assign new value
449
storedSNMPValue = (SNMPOctetString)snmpValue;
450                         
451                         // return SNMPVariablePair to indicate we've handled this OID
452
try
453                         {
454                             SNMPVariablePair newPair = new SNMPVariablePair(snmpOID, storedSNMPValue);
455                             responseList.addSNMPObject(newPair);
456                         }
457                         catch (SNMPBadValueException e)
458                         {
459                             // won't happen...
460
}
461                     
462                     }
463                     else
464                     {
465                         int errorIndex = i+1;
466                         int errorStatus = SNMPRequestException.BAD_VALUE;
467                         throw new SNMPSetException("Supplied value must be SNMPOctetString", errorIndex, errorStatus);
468                     }
469                     
470                 }
471                 else if (pduType == SNMPBERCodec.SNMPGETREQUEST)
472                 {
473                     // got a get-request for our variable; send back a value - just a string
474
try
475                     {
476                         SNMPVariablePair newPair = new SNMPVariablePair(snmpOID, storedSNMPValue);
477                         responseList.addSNMPObject(newPair);
478                     }
479                     catch (SNMPBadValueException e)
480                     {
481                         // won't happen...
482
}
483                 }
484                 
485             }
486             
487         }
488         
489         writeMessage("\n");
490         
491         
492         // return the created list of variable pairs
493
return responseList;
494         
495     }
496     
497     
498     
499     
500     public SNMPSequence processGetNextRequest(SNMPPDU pdu, String JavaDoc communityName)
501         throws SNMPGetException
502     {
503         writeMessage("Got pdu:\n");
504         
505         writeMessage(" community name: " + communityName + "\n");
506         writeMessage(" request ID: " + pdu.getRequestID() + "\n");
507         writeMessage(" pdu type: ");
508         byte pduType = pdu.getPDUType();
509         
510         switch (pduType)
511         {
512             case SNMPBERCodec.SNMPGETREQUEST:
513             {
514                 writeMessage("SNMPGETREQUEST\n");
515                 break;
516             }
517             
518             case SNMPBERCodec.SNMPGETNEXTREQUEST:
519             {
520                 writeMessage("SNMPGETNEXTREQUEST\n");
521                 break;
522             }
523             
524             case SNMPBERCodec.SNMPSETREQUEST:
525             {
526                 writeMessage("SNMPSETREQUEST\n");
527                 break;
528             }
529             
530             case SNMPBERCodec.SNMPGETRESPONSE:
531             {
532                 writeMessage("SNMPGETRESPONSE\n");
533                 break;
534             }
535             
536             case SNMPBERCodec.SNMPTRAP:
537             {
538                 writeMessage("SNMPTRAP\n");
539                 break;
540             }
541             
542             default:
543             {
544                 writeMessage("unknown\n");
545                 break;
546             }
547             
548             
549         }
550         
551         
552         
553         SNMPSequence varBindList = pdu.getVarBindList();
554         SNMPSequence responseList = new SNMPSequence();
555         
556         for (int i = 0; i < varBindList.size(); i++)
557         {
558             SNMPSequence variablePair = (SNMPSequence)varBindList.getSNMPObjectAt(i);
559             SNMPObjectIdentifier suppliedOID = (SNMPObjectIdentifier)variablePair.getSNMPObjectAt(0);
560             SNMPObject suppliedObject = (SNMPObject)variablePair.getSNMPObjectAt(1);
561             
562             writeMessage(" OID: " + suppliedOID + "\n");
563             writeMessage(" value: " + suppliedObject + "\n");
564             
565             
566             // check to see if supplied community name is ours; if not, we'll just silently
567
// ignore the request by not returning anything
568
if (!communityName.equals(this.communityName))
569             {
570                 continue;
571             }
572             
573             // we'll only respond to requests for OID 1.3.6.1.2.1.99.0, and it's read-only;
574
// for get-next request, we'll return the value for 1.3.6.1.2.1.100.0
575
if (suppliedOID.toString().equals("1.3.6.1.2.1.99.0"))
576             {
577                 if (pduType == SNMPBERCodec.SNMPGETNEXTREQUEST)
578                 {
579                     // got a get-next-request for our variable; send back a value for OID 1.3.6.1.2.1.100.0
580
try
581                     {
582                         // create SNMPVariablePair for the next OID and its value
583
SNMPObjectIdentifier nextOID = new SNMPObjectIdentifier("1.3.6.1.2.1.100.0");
584                         SNMPVariablePair innerPair = new SNMPVariablePair(nextOID, storedSNMPValue);
585                         
586                         // now create a pair containing the supplied OID and the variable pair containing the following
587
// OID and its value; this allows the ANMPv1AgentInterface to know which of the supplied OIDs
588
// the new OID corresponds to (follows).
589
SNMPVariablePair outerPair = new SNMPVariablePair(suppliedOID, innerPair);
590                         
591                         // add the "compound" SNMPVariablePair to the response list
592
responseList.addSNMPObject(outerPair);
593                     }
594                     catch (SNMPBadValueException e)
595                     {
596                         // won't happen...
597
}
598                 }
599                 
600             }
601             
602         }
603         
604         writeMessage("\n");
605         
606         
607         // return the created list of variable pairs
608
return responseList;
609         
610     }
611     
612     
613     
614     
615     public void run()
616     {
617         int numChars;
618         char[] charArray = new char[256];
619         
620         try
621         {
622             while (!readerThread.isInterrupted() && ((numChars = errorReader.read(charArray, 0, charArray.length)) != -1))
623             {
624                 StringBuffer JavaDoc errorMessage = new StringBuffer JavaDoc();
625                 errorMessage.append("Problem receiving request:\n");
626                 errorMessage.append(new String JavaDoc(charArray, 0, numChars));
627                 errorMessage.append("\n");
628                 writeMessage(errorMessage.toString());
629             }
630         }
631         catch(IOException e)
632         {
633             messagesArea.append("Problem receiving errors; error reporter exiting!");
634         }
635     }
636     
637     
638     
639     
640     public static void main(String JavaDoc args[])
641     {
642         try
643         {
644             SNMPAgentTest theApp = new SNMPAgentTest();
645             theApp.pack();
646             theApp.setSize(700,500);
647             theApp.setVisible(true);
648         }
649         catch (Exception JavaDoc e)
650         {}
651     }
652     
653
654 }
Popular Tags