KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > ist > coach > coachEmfServicesComponents > SnmpAdapterProviderComposition > SnmpAdapterProviderImpl


1 /*====================================================================
2
3 This file was produced by the OpenCCM CIF_JIMPL generator.
4
5 OpenCCM: The Open CORBA Component Model Platform
6 Copyright (C) 2000-2003 INRIA - USTL - LIFL - GOAL
7 Contact: openccm@objectweb.org
8
9 This library is free software; you can redistribute it and/or
10 modify it under the terms of the GNU Lesser General Public
11 License as published by the Free Software Foundation; either
12 version 2.1 of the License, or any later version.
13
14 This library is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 Lesser General Public License for more details.
18
19 You should have received a copy of the GNU Lesser General Public
20 License along with this library; if not, write to the Free Software
21 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
22 USA
23
24 Initial developer(s): Christophe Demarey.
25 Contributor(s): ______________________________________.
26
27 ====================================================================*/

28
29 package ist.coach.coachEmfServicesComponents.SnmpAdapterProviderComposition JavaDoc;
30
31 import org.opennms.protocols.snmp.*;
32
33 import ist.coach.coachEmfCommon.Utils;
34 import ist.coach.coachEmfCommon.ExceptionMessages;
35 import ist.coach.coachEmfServices.SnmpAdapter.SnmpApplicationError JavaDoc;
36 import ist.coach.coachEmfCommon.DataTypeImpl;
37 import ist.coach.coachEmfServices.SnmpAdapter.DataType JavaDoc;
38 import ist.coach.coachEmfServicesComponents.SnmpAdapterProviderPackage.trap_targetConnection JavaDoc;
39 //import ist.coach.coachEmfServicesComponents.SnmpObjectData;
40
//import ist.coach.coachEmfServicesComponents.Configuration;
41

42 import org.omg.CORBA.Any JavaDoc;
43
44 import java.util.LinkedList JavaDoc;
45 import java.util.ListIterator JavaDoc;
46
47 import org.omg.CosNaming.NameComponent JavaDoc;
48
49 /**
50  * This is the CIDL-based implementation of the
51  * OMG IDL3 IDL:coach.ist/coachEmfServicesComponents/SnmpAdapterProvider:1.0 component type.
52  *
53  * @author OpenCCM CIF_Jimpl Compiler.
54  */

55 public class SnmpAdapterProviderImpl
56      extends ist.coach.coachEmfServicesComponents.SnmpAdapterProviderComposition.SnmpAdapterProvider_impl JavaDoc
57      implements Runnable JavaDoc,
58                 SnmpTrapHandler
59      {
60     // ==================================================================
61
//
62
// Internal states.
63
//
64
// ==================================================================
65
protected static LinkedList JavaDoc linkedList;
66     protected static Configuration config;
67     trap_targetConnection[] trap_target_facades = null;
68     /**
69      ** Private ORB reference (used to create Anys)
70      **/

71     private static org.omg.CORBA.ORB JavaDoc orb = org.objectweb.ccm.CORBA.TheORB.getORB();
72     /**
73     /**
74      ** Declaration of the identifier used to identify SNMP trap types
75      **/

76     private static final SnmpObjectId SNMPv2_MIB_snmpTrapOid =
77     new SnmpObjectId(".1.3.6.1.6.3.1.1.4.1.0");
78
79     public static final int SNMP_TRAP_PORT = 2010;
80     /**
81      ** SnmpTrapDaemon Listener Thread
82      **/

83     private Thread JavaDoc listenerThread;
84     /**
85      ** Declaration of Unknown Trap
86      **/

87     private static final int UNKNOWN_TRAP_TYPE = 0;
88     // ==================================================================
89
//
90
// Constructors.
91
//
92
// ==================================================================
93

94     public SnmpAdapterProviderImpl()
95     {
96       this.linkedList = new LinkedList JavaDoc();
97     }
98     // ==================================================================
99
//
100
// Methods for the OMG IDL Components::EnterpriseComponent local interface.
101
//
102
// ==================================================================
103
//
104
// IDL:omg.org/Components/EnterpriseComponent/configuration_complete:1.0
105
//
106
/**
107      ** Completes the component configuration.
108      **
109      ** @throws org.omg.Components.InvalidConfiguration
110      ** Thrown if the configuration is invalid.
111      **/

112     public void
113     configuration_complete()
114     throws org.omg.Components.InvalidConfiguration
115     {
116         //
117
// DONE : implement !!!
118
//
119

120         config = Configuration.getInstance();
121
122         if (config == null) {
123             System.err.println("Could not create a valid configuration. Exiting...");
124             throw new org.omg.Components.InvalidConfiguration();
125         }
126
127         listener_init();
128
129         if ((trap_target_facades = get_context().get_connections_trap_target()) == null) {
130             System.err.println("SnmpAdapter is not configured with Facades to serve....");
131         }
132
133         System.err.println("SnmpAdapterProvider configuration completed...");
134      }
135     // added by FSET
136
public void ccm_remove()
137     throws org.omg.Components.CCMException {
138         listener_stop();
139         super.ccm_remove();
140         System.err.println("SnmpAdapter has been destroyed");
141     }
142     // ==================================================================
143
//
144
// Private Methods.
145
//
146
// ==================================================================
147

148     protected static Any JavaDoc convertSnmpSyntaxToAny(SnmpSyntax data) {
149
150         Any JavaDoc value =orb.create_any();
151
152
153         switch (data.typeId()) {
154             case SnmpSMI.SMI_OBJECTID:
155                 value.insert_string( new String JavaDoc(((SnmpObjectId)data).toString()));
156                 break;
157             case SnmpSMI.SMI_COUNTER32:
158                 value.insert_longlong( ((SnmpCounter32)data).getValue());
159                 break;
160             case SnmpSMI.SMI_COUNTER64: //Same as SnmpSMI.SMI_UNSIGNED32
161
value.insert_longlong( ((SnmpCounter64)data).getValue().longValue());
162                 break;
163             case SnmpSMI.SMI_GAUGE32:
164                 value.insert_longlong( ((SnmpGauge32)data).getValue());
165                 break;
166             case SnmpSMI.SMI_INTEGER:
167                 value.insert_long( ((SnmpInt32)data).getValue());
168                 break;
169             case SnmpSMI.SMI_TIMETICKS:
170                 value.insert_longlong( ((SnmpTimeTicks)data).getValue());
171                 break;
172             case SnmpSMI.SMI_IPADDRESS:
173                 value.insert_string( new String JavaDoc(((SnmpIPAddress)data).toString()));
174                 break;
175             case SnmpSMI.SMI_STRING:
176                 //fset HACK
177
// It seems that orbacus has problems handling anys as strings if these contain
178
// non printable characters. NOT RESOLVED BUT BYPASSED....
179
//System.err.println("SnmpSMI.SMI_STRING length= " + ((SnmpOctetString)data).getLength());
180
//System.err.print("As string = " + ((SnmpOctetString)data).toString() +
181
// " as bytes = " + new String(((SnmpOctetString)data).getString()));
182
/*********
183                 if (octetData.toString().indexOf("RAW") < 0) {
184                   //System.err.println(" Type is HEX");
185                   value.insert_string("Hello");
186                  }
187                  else {
188                   //System.err.println(" Type is RAW");
189                   value.insert_string( new String(((SnmpOctetString)data).getString()));
190                 }
191                 ******/

192                 SnmpOctetString octetData = (SnmpOctetString) data;
193                 byte[] octetDataBytes = octetData.getString();
194                 org.omg.CORBA.OctetSeqHelper.insert(value, octetDataBytes);
195
196                 //initially by digi
197
//value.insert_string( new String(((SnmpOctetString)data).getString()));
198
break;
199             case SnmpSMI.SMI_OPAQUE:
200                 value.insert_string( new String JavaDoc(((SnmpOpaque)data).getString()));
201                 break;
202             case SnmpSMI.SMI_NOSUCHOBJECT:
203                 //value = null;
204
// Is this good...???
205
value.insert_string("No Such Object");
206                 break;
207             case SnmpSMI.SMI_NOSUCHINSTANCE:
208                 //value = null;
209
// Is this good...???
210
value.insert_string( "No Such Instance");
211                 break;
212             default:
213                 System.err.println("Unknown Variable Binding.");
214                 value = null;
215                 break;
216
217         }
218
219         return value;
220
221     }
222
223     protected static SnmpSyntax convertAnyToSnmpSyntax(Any JavaDoc data, byte code) {
224
225         SnmpSyntax value = null;
226
227         switch (code) {
228
229             case SnmpSMI.SMI_COUNTER32:
230                 value = ((SnmpSyntax)new SnmpCounter32(data.extract_longlong()));
231                 break;
232             case SnmpSMI.SMI_COUNTER64:
233                 value = ((SnmpSyntax)new SnmpCounter64(data.extract_longlong()));
234                 break;
235             case SnmpSMI.SMI_UNSIGNED32: // same as SnmpSMI.SMI_GAUGE32
236
value = ((SnmpSyntax)new SnmpGauge32(data.extract_longlong()));
237                 break;
238             case SnmpSMI.SMI_INTEGER:
239                 value = ((SnmpSyntax)new SnmpInt32(data.extract_long()));
240                 break;
241             case SnmpSMI.SMI_IPADDRESS:
242                 value = ((SnmpSyntax)new SnmpIPAddress(data.extract_string().getBytes()));
243                 break;
244             case SnmpSMI.SMI_OBJECTID:
245                 value = ((SnmpSyntax)new SnmpObjectId(data.extract_string()));
246                 break;
247             case SnmpSMI.SMI_OPAQUE:
248                 value = ((SnmpSyntax)new SnmpOpaque(data.extract_string().getBytes()));
249                 break;
250             case SnmpSMI.SMI_STRING:
251                 value = (SnmpSyntax)new SnmpOctetString(org.omg.CORBA.OctetSeqHelper.extract(data));
252                 //initially by digi
253
//value = ((SnmpSyntax)new SnmpOctetString(data.extract_string().getBytes()));
254
break;
255             case SnmpSMI.SMI_TIMETICKS:
256                 value = ((SnmpSyntax)new SnmpTimeTicks(data.extract_longlong()));
257                 break;
258             default:
259                 System.err.println("SnmpAdapter:convertAnyToSnmpSyntax> " +
260                     " Unknown (or un-supported) SMI Type");
261                 break;
262         }
263
264         return value;
265     }
266
267     private void processTrapData(
268         java.net.InetAddress JavaDoc agent,
269         SnmpOctetString community,
270         SnmpPduPacket pdu)
271     throws SnmpApplicationError{
272
273         int snmpTrapType = 0;
274         String JavaDoc trapObjectIdentifier = null;
275         int k = pdu.getLength();
276         DataTypeImpl[] dataSetType = new DataTypeImpl[k];
277
278         for (int i = 0; i < k ; i++ ) {
279
280             SnmpVarBind vb = pdu.getVarBindAt(i);
281
282             String JavaDoc oid = vb.getName().toString();
283             Any JavaDoc value = orb.create_any();
284
285             switch (vb.getValue().typeId()) {
286                 case SnmpSMI.SMI_OBJECTID:
287                     value.insert_string( ((SnmpObjectId)vb.getValue()).toString());
288                     break;
289                 case SnmpSMI.SMI_COUNTER32:
290                     value.insert_longlong( ((SnmpCounter32)vb.getValue()).getValue());
291                     break;
292                 case SnmpSMI.SMI_COUNTER64:
293                     value.insert_longlong( ((SnmpCounter64)vb.getValue()).getValue().longValue());
294                     break;
295                 case SnmpSMI.SMI_GAUGE32:
296                     value.insert_longlong( ((SnmpGauge32)vb.getValue()).getValue());
297                     break;
298                 case SnmpSMI.SMI_INTEGER:
299                     value.insert_long( ((SnmpInt32)vb.getValue()).getValue());
300                     break;
301                 case SnmpSMI.SMI_TIMETICKS:
302                     value.insert_longlong( ((SnmpTimeTicks)vb.getValue()).getValue());
303                     break;
304                 case SnmpSMI.SMI_IPADDRESS:
305                     value.insert_string( ((SnmpIPAddress)vb.getValue()).toString());
306                     break;
307                 case SnmpSMI.SMI_STRING:
308                     SnmpOctetString octetData = (SnmpOctetString) vb.getValue();
309                     byte[] octetDataBytes = octetData.getString();
310                     org.omg.CORBA.OctetSeqHelper.insert(value, octetDataBytes);
311                     //by digi
312
//value.insert_string( new String(((SnmpOctetString)vb.getValue()).getString()));
313
break;
314                 default:
315                     System.err.println("SnmpAdapter: processTrapData> Unknown Variable Binding.");
316                     break;
317
318             }
319
320             if (vb.getName().compare(SNMPv2_MIB_snmpTrapOid) == 0)
321                 trapObjectIdentifier = ((SnmpObjectId)vb.getValue()).toString();
322
323             dataSetType[i] = new DataTypeImpl(oid, value);
324
325         }
326
327         snmpTrapType = determineTrapType(trapObjectIdentifier);
328         if (snmpTrapType == UNKNOWN_TRAP_TYPE)
329             throw new SnmpApplicationError(ExceptionMessages.uknown_trap_error);
330
331         String JavaDoc objectClass = determineObjectClass(snmpTrapType);
332         if (objectClass == null) {
333             System.err.println("SnmpAdapter: processTrapData> Trap could not be mapped to an object class");
334             throw new SnmpApplicationError("Trap could not be mapped to an object class");
335         }
336
337         System.err.println("SnmpAdapter: processTrapData> Trap is " + trapTypeToString(snmpTrapType) +
338             " (trap type " + snmpTrapType +
339             " ), thrown by objects of objectclass " + objectClass);
340
341         NameComponent JavaDoc [] name = null;
342
343         if (isRootObject(objectClass)) {
344             name = findRegisteredRootObject(objectClass, agent.getHostAddress());
345             if (name == null) {
346                 System.err.println("SnmpAdapter: processTrapData> Trap could not be mapped to a registered (root) object.");
347                 throw new SnmpApplicationError(ExceptionMessages.uknown_trap_origin_error);
348             }
349         }
350         else {
351
352             boolean valueIsNeeded = determineIfValueIsNeeded(objectClass);
353
354             Any JavaDoc value = null;
355
356             if (valueIsNeeded == true) {
357                 value = determineValue(objectClass, dataSetType);
358
359                 if (value == null) {
360                     System.err.println("SnmpAdapter: processTrapData> Could not determine value for trap!");
361                     throw new SnmpApplicationError(ExceptionMessages.trap_misconfig_error);
362                 }
363             }
364
365             name = findRegisteredLeafObject(objectClass, agent.getHostAddress(), value);
366             if (name == null) {
367                 System.err.println("SnmpAdapter: processTrapData> Trap could not be mapped to a registered (leaf) object.");
368                 throw new SnmpApplicationError(ExceptionMessages.uknown_trap_origin_error);
369             }
370         }
371
372         String JavaDoc objectFacadeKind = Utils.name2facade(Utils.name2string(name));
373         String JavaDoc facadeNameKind = null;
374         boolean facadeFound = false;
375
376         System.err.println("SnmpAdapter: processTrapData> Object with name " + Utils.name2string(name) +
377             " is accessible through a facade with kind " + objectFacadeKind);
378
379         int index = 0;
380         String JavaDoc facadeName = new String JavaDoc();
381         trap_target_facades = get_context().get_connections_trap_target();
382         for (index = 0; index < trap_target_facades.length; index++) {
383
384             facadeName = trap_target_facades[index].objref.facade_name();
385             facadeNameKind = Utils.name2facade(facadeName);
386
387             //System.err.println("Checking with facade with name " +
388
// facadeName + " which has a kind " + facadeNameKind);
389

390             if (objectFacadeKind.equals(facadeNameKind)) {
391
392                 System.err.println("SnmpAdapter: processTrapData> Object with name " +
393                       Utils.name2string(name) +
394                     " is accessible through facade with name " + facadeName +
395                         " found at position " + index);
396
397                 facadeFound = true;
398
399                 break;
400
401             }
402         }
403
404         if (facadeFound == false) {
405
406             System.err.println("SnmpAdapter: processTrapData> Could not find a facade to send trap to");
407             throw new SnmpApplicationError("No Facade trap sink found");
408         }
409
410         int varBindNumber = pdu.getLength();
411
412         DataTypeImpl [] trapData = new DataTypeImpl[varBindNumber];
413
414         for (int j = 0; j < varBindNumber; j++) {
415
416             SnmpVarBind vb = pdu.getVarBindAt(j);
417
418             trapData[j] = new DataTypeImpl(vb.getName().toString(),
419                 convertSnmpSyntaxToAny(vb.getValue()),
420                 vb.getValue().typeId());
421
422         }
423
424         String JavaDoc community_str = (community != null) ?
425             new String JavaDoc(community.getString()) : new String JavaDoc();
426
427         System.err.println("Calling notifyTrap with arguments: ");
428         System.err.println("Name: " + name);
429         System.err.println("Community: " + community_str);
430         System.err.println("RequestId: " + pdu.getRequestId());
431         System.err.println("SnmpTrapType: " + snmpTrapType);
432         System.err.println("Length of trap data: " + trapData.length);
433
434         try {
435             ist.coach.coachEmfServices.SnmpAdapter.TrapCallback JavaDoc facade_callback =
436                 trap_target_facades[index].objref;
437
438             if (facade_callback != null) {
439                 facade_callback.notifyTrap( name,
440                         community_str,
441                         pdu.getRequestId(),
442                         snmpTrapType,
443                         trapData);
444                 System.err.println("SnmpAdapter has served Trap successfully");
445             }
446             else
447             System.err.println("SnmpAdapter: processTrapData> Could not retrieve reference to facade of " +
448                     Utils.name2string(name));
449         }
450         catch(SnmpApplicationError snmp_ex) {
451             System.err.println("SnmpAdapterProvider: SnmpApplicationError exception caught " +
452                 " while trying to forward trap to " + Utils.name2string(name));
453         }
454         catch(intt.itu.itut_x780.ApplicationError app_exc) {
455             System.err.println("SnmpAdapterProvider: ApplicationError exception caught " +
456                 " while trying to forward trap to " + Utils.name2string(name));
457         }
458
459     }
460
461     private int determineTrapType(String JavaDoc trapObjectIdentifier) {
462
463
464         int snmpTrapType = UNKNOWN_TRAP_TYPE;
465
466         for (int i = 0; i < this.config.availableTraps.length; i++) {
467             if (trapObjectIdentifier.equals(
468                 this.config.availableTraps[i].oid.toString())) {
469
470                 snmpTrapType = this.config.availableTraps[i].identifier;
471                 break;
472             }
473         }
474
475         return snmpTrapType;
476
477     }
478
479     private String JavaDoc determineObjectClass(int snmpTrapType) {
480
481         for (int i = 0; i < this.config.availableTraps.length; i++) {
482             if (snmpTrapType == this.config.availableTraps[i].identifier) {
483                 return this.config.availableTraps[i].objectclass;
484             }
485         }
486
487         return null;
488
489     }
490
491    private boolean determineIfValueIsNeeded(String JavaDoc objectClass) {
492
493         boolean valueNeeded = false;
494
495         for (int i = 0; i < this.config.availableTraps.length; i++) {
496
497             if (objectClass.equalsIgnoreCase(this.config.availableTraps[i].objectclass)) {
498
499                 if (this.config.availableTraps[i].valueOid == null) {
500                     System.err.println("SnmpAdapter: determineIfValueIsNeeded> No value needed to fetch " +
501                         "leaf object of objectclass " + objectClass);
502                     valueNeeded = false;
503                 }
504                 else
505                     valueNeeded = true;
506             }
507         }
508
509         return valueNeeded;
510     }
511
512
513     private Any JavaDoc determineValue(String JavaDoc objectClass, DataType [] varBindings) {
514
515         String JavaDoc valueOid = null;
516
517         //System.err.println("SnmpAdapter: determineValue> Determining value for objectClass..." +
518
// objectClass + ", with " + varBindings.length + " variable bindings");
519

520
521         for (int i = 0; i < this.config.availableTraps.length; i++) {
522
523             if (objectClass.equalsIgnoreCase(this.config.availableTraps[i].objectclass)) {
524
525                 if (this.config.availableTraps[i].valueOid != null)
526                     valueOid = new String JavaDoc(this.config.availableTraps[i].valueOid.toString());
527                 //else
528
// System.err.println("SnmpAdapter: determineValue> No value need to fetch leaf object of objectclass "
529
// + objectClass);
530

531                 break;
532             }
533
534         }
535
536         if (valueOid != null) {
537             for (int i = 0; i < varBindings.length; i++) {
538                 if (varBindings[i].identifier.equals(
539                     valueOid)) {
540                     return (varBindings[i].value);
541                 }
542             }
543         }
544         //System.err.println("SnmpAdapter: determineValue> Returning null");
545
return null;
546
547     }
548
549     private String JavaDoc trapTypeToString(int snmpTrapType) {
550         for (int i = 0; i < this.config.availableTraps.length; i++) {
551             if (this.config.availableTraps[i].identifier == snmpTrapType) {
552
553                 return this.config.availableTraps[i].id;
554             }
555
556         }
557
558         return null;
559     }
560
561     protected static synchronized boolean isRootObject(String JavaDoc objectClass) {
562
563         for (int i = 0; i < config.rootObjects.length; i++)
564             if (config.rootObjects[i].equals(objectClass))
565                 return true;
566
567         return false;
568     }
569     /**
570      * @param objectClass
571      * @param ipAddress
572      * @return NameComponent[]
573      *
574      * Returns the name of a root-object with the given
575      * objectclass and IP Address.
576      */

577     private NameComponent JavaDoc[] findRegisteredRootObject(
578         String JavaDoc objectClass, String JavaDoc ipAddress) {
579
580         ListIterator JavaDoc li = this.linkedList.listIterator();
581
582         //System.err.println("SnmpAdapter: findRegisteredRootObject> Trying to find Root object with object class " +
583
// objectClass + " and IP Address " + ipAddress);
584

585         while (li.hasNext()) {
586
587             SnmpObjectData objData = (SnmpObjectData)li.next();
588
589             NameComponent JavaDoc [] name = objData.getName();
590             String JavaDoc myObjectClass = name[name.length - 2].kind;
591             String JavaDoc myIpAddress = objData.getIPAddress();
592
593             //System.out.println("Comparing to object class " +
594
//myObjectClass + " and IP Address " + myIpAddress);
595

596             if (myObjectClass.equals(objectClass) &&
597                 myIpAddress.equals(ipAddress)) {
598
599                 //System.err.println("-----> Matched with object named " +
600
// Utils.name2string(objData.getName()));
601
return objData.getName();
602             }
603         }
604
605         return null;
606     }
607
608     /**
609      * @param objectClass
610      * @param ipAddress
611      * @param value
612      * @return NameComponent[]
613      *
614      * Returns the name of a registered leaf object with
615      * the given name, IP Address, registered with the
616      * given value.
617      */

618
619     private NameComponent JavaDoc[] findRegisteredLeafObject(
620         String JavaDoc objectClass, String JavaDoc ipAddress, Any JavaDoc value) {
621
622         ListIterator JavaDoc li = this.linkedList.listIterator();
623
624         //System.err.println("SnmpAdapter> Trying to find Leaf object with object class " +
625
// objectClass + " and IP Address " + ipAddress);
626

627         while (li.hasNext()) {
628
629             SnmpObjectData objData = (SnmpObjectData)li.next();
630
631             NameComponent JavaDoc [] name = objData.getName();
632             String JavaDoc myObjectClass = getObjectClass(name);
633             String JavaDoc myIpAddress = objData.getIPAddress();
634
635             if (myObjectClass.equals(objectClass) &&
636                 myIpAddress.equals(ipAddress)) {
637
638                 if (value != null) {
639                     if (objData.getValue().equal(value)) {
640
641                         //System.err.println("-----> Matched with object named" +
642
// Utils.name2string(objData.getName()));
643
return objData.getName();
644                     }
645                 }
646                 else {
647                     //System.err.println("-----> Matched with object named" +
648
// Utils.name2string(objData.getName()));
649
return objData.getName();
650                 }
651             }
652         }
653
654         return null;
655     }
656
657     protected static String JavaDoc getObjectClass(NameComponent JavaDoc[] name) {
658         return name[name.length - 2].kind;
659     }
660
661     private void listener_init() {
662         if (listenerThread == null) {
663             listenerThread = new Thread JavaDoc(this, "Listener");
664             listenerThread.start();
665         }
666     }
667
668     private void listener_stop() {
669
670         Thread JavaDoc dummyThread =listenerThread;
671         listenerThread = null;
672         dummyThread.interrupt();
673
674     }
675
676      // ==================================================================
677
//
678
// Runnable Interface methods.
679
//
680
// ===================================================================
681
public void run() {
682
683         Thread JavaDoc myThread = Thread.currentThread();
684         SnmpTrapSession trapSession = null;
685         while (listenerThread == myThread) {
686
687             try {
688                 trapSession = new SnmpTrapSession(this,
689                             SNMP_TRAP_PORT);
690                 System.err.println("SNMP Trap Receiver Started");
691                 synchronized(trapSession)
692                 {
693                     trapSession.wait();
694                 }
695             }
696             catch (InterruptedException JavaDoc ie) {
697                 System.err.println("SNMP Trap Receiver Exiting");
698                 trapSession.close();
699             }
700             catch (Exception JavaDoc e) {
701                 System.err.println("Exception in init(): " + e);
702                 e.printStackTrace();
703             }
704         }
705      }
706
707
708     // ==================================================================
709
//
710
// SnmpTrapHandler Interface methods.
711
//
712
// ===================================================================
713

714
715     /**
716      * Method from SnmpHandler interface, used to parse SNMPv2 Traps
717      */

718     public void snmpReceivedTrap(
719          SnmpTrapSession session,
720          java.net.InetAddress JavaDoc agent,
721          int port,
722          SnmpOctetString community,
723          SnmpPduPacket pdu) {
724
725         System.err.println("V2 Trap from agent " + agent.toString() + " on port " + port);
726         System.err.println("V2 Trap Community........... " + new String JavaDoc(community.getString()));
727         System.err.println("V2 Trap PDU command......... " + pdu.getCommand());
728         System.err.println("V2 Trap PDU ID.............. " + pdu.getRequestId());
729         System.err.println("V2 Trap PDU Length.......... " + pdu.getLength());
730
731         if(pdu instanceof SnmpPduRequest)
732         {
733             System.err.println("V2 Trap PDU Error Status.... " + ((SnmpPduRequest)pdu).getErrorStatus());
734             System.err.println("V2 Trap PDU Error Index..... " + ((SnmpPduRequest)pdu).getErrorIndex());
735         }
736
737         int k = pdu.getLength();
738
739         for (int i = 0; i < k ; i++ )
740         {
741             SnmpVarBind vb = pdu.getVarBindAt(i);
742             System.err.print("Varbind[" + i + "] := " + vb.getName().toString());
743             System.err.println(" --> " + vb.getValue().toString());
744         }
745
746         try {
747
748             processTrapData(agent, community, pdu);
749         }
750         catch (SnmpApplicationError e) {
751             System.err.println("Unable to process trap!");
752         }
753
754      }
755
756     /**
757      * Method from SnmpHandler interface used to parse SNMPv1 traps.
758      *
759      * @param session The Trap Session that received the PDU.
760      * @param agent The address of the remote sender.
761      * @param port The remote port where the pdu was transmitted from.
762      * @param community The decoded community string.
763      * @param pdu The decoded V1 trap pdu.
764      *
765      */

766     public void snmpReceivedTrap(
767         SnmpTrapSession session,
768          java.net.InetAddress JavaDoc agent,
769          int port,
770          SnmpOctetString community,
771          SnmpPduTrap pdu)
772
773     {
774
775         System.err.println("V1 Trap from agent " + agent.toString() + " on port " + port);
776         System.err.println("Ip Address................. " + pdu.getAgentAddress() );
777         System.err.println("Enterprise Id.............. " + pdu.getEnterprise() );
778         System.err.println("Generic ................... " + pdu.getGeneric() );
779         System.err.println("Specific .................. " + pdu.getSpecific() );
780         System.err.println("TimeStamp ................. " + pdu.getTimeStamp() );
781         System.err.println("Length..................... " + pdu.getLength() );
782
783
784         int k = pdu.getLength();
785         for (int i = 0; i < k ; i++ )
786         {
787             SnmpVarBind vb = pdu.getVarBindAt(i);
788             System.err.print("Varbind[" + i + "] := " + vb.getName().toString());
789             System.err.println(" --> " + vb.getValue().toString());
790         }
791         System.err.println("");
792
793         //synchronized(session)
794
//{
795
//session.notify();
796
//}
797
}
798
799     /**
800      * Process session errors.
801      *
802      * @param session The trap session in error.
803      * @param error The error condition.
804      * @param ref The reference object, if any.
805      */

806     public void snmpTrapSessionError(
807         SnmpTrapSession session,
808         int error,
809         java.lang.Object JavaDoc ref)
810     {
811
812         System.err.println("SnmpAdapter:snmpTrapSessionError> An error occured in the trap session");
813         System.err.println("Session error code = " + error);
814         if(ref != null)
815         {
816             System.err.println("SnmpAdapter:snmpTrapSessionError> Session error reference: " + ref.toString());
817         }
818
819         if(error == SnmpTrapSession.ERROR_EXCEPTION)
820         {
821             synchronized(session)
822             {
823                 session.notify(); // close the session
824
}
825         }
826      }
827
828
829     // ==================================================================
830
//
831
// Methods.
832
//
833
// ==================================================================
834
}
835
Popular Tags