[jboss-cvs] JBossAS SVN: r111459 - in branches/snmp4j-int: varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent and 2 other directories.

jboss-cvs-commits at lists.jboss.org jboss-cvs-commits at lists.jboss.org
Thu May 26 11:50:18 EDT 2011


Author: thauser at redhat.com
Date: 2011-05-26 11:50:18 -0400 (Thu, 26 May 2011)
New Revision: 111459

Modified:
   branches/snmp4j-int/build/build.xml
   branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/AttributeMappingsBinding.java
   branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/RequestHandlerImpl.java
   branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/SnmpAgentService.java
   branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/SnmpAgentServiceMBean.java
   branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/SnmpRequest.java
   branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/SnmpVarBindFactory.java
   branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/test/Test.java
   branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/trapd/TrapReceiver.java
Log:
snmpv3 conversion

Modified: branches/snmp4j-int/build/build.xml
===================================================================
--- branches/snmp4j-int/build/build.xml	2011-05-26 14:45:44 UTC (rev 111458)
+++ branches/snmp4j-int/build/build.xml	2011-05-26 15:50:18 UTC (rev 111459)
@@ -2177,7 +2177,7 @@
       <fileset refid="org.jboss.scanning:scanning-deployers:jar"/>
       <fileset refid="org.jboss.mc-int:jboss-mc-int-servlet:jar"/>
       <fileset refid="org.beanshell:bsh:jar"/>
-      <fileset refid="joesnmp:joesnmp:jar"/>
+      <!--<fileset refid="joesnmp:joesnmp:jar"/>-->
       <fileset refid="org.snmp4j:snmp4j:jar"/>
       <fileset refid="wutka-dtdparser:dtdparser:jar"/>
       <fileset refid="apache-bsf:bsf:jar"/>

Modified: branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/AttributeMappingsBinding.java
===================================================================
--- branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/AttributeMappingsBinding.java	2011-05-26 14:45:44 UTC (rev 111458)
+++ branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/AttributeMappingsBinding.java	2011-05-26 15:50:18 UTC (rev 111459)
@@ -41,7 +41,7 @@
  *       attribute, which would replace the mbean oid-prefix 
  *      -Remove the ability for there to be an oid-prefix for the MBeans. instead, but this into the "table" element.
  *       the reason we should do this is because SNMP works with "Objects" and "Instances". The way it is currently
- *       parsed makes it seem like each MIB is a table, and we do not want to force this behavior.
+ *       parsed makes it seem like each MBean is a table, and we do not want to force this behavior.
  *      
  *      New scheme for parsing: 
  *      <mbean name=...> (MBean we're interested in.)
@@ -110,10 +110,10 @@
 		MappedAttribute attribute = null;
 		
 		if ("attribute".equals(localName)) {
-			attribute = new MappedAttribute();
 			String oid = attrs.getValue("oid");
 			String name = attrs.getValue("name");
 			String mode = attrs.getValue("mode");
+			attribute = new MappedAttribute();
 			if ("rw".equalsIgnoreCase(mode))
 				attribute.setReadWrite(true);
 			attribute.setName(name);

Modified: branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/RequestHandlerImpl.java
===================================================================
--- branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/RequestHandlerImpl.java	2011-05-26 14:45:44 UTC (rev 111458)
+++ branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/RequestHandlerImpl.java	2011-05-26 15:50:18 UTC (rev 111459)
@@ -23,12 +23,12 @@
 
 import java.io.InputStream;
 import java.net.InetAddress;
+import java.util.HashSet;
 import java.util.Iterator;
 import java.util.List;
 import java.util.SortedMap;
 import java.util.SortedSet;
 import java.util.TreeMap;
-import java.util.HashSet;
 import java.util.TreeSet;
 import java.util.Vector;
 
@@ -39,7 +39,6 @@
 import org.jboss.jmx.adaptor.snmp.config.attribute.AttributeMappings;
 import org.jboss.jmx.adaptor.snmp.config.attribute.ManagedBean;
 import org.jboss.jmx.adaptor.snmp.config.attribute.MappedAttribute;
-//import org.jboss.jmx.adaptor.snmp.config.attribute.MappedTable;
 import org.jboss.logging.Logger;
 import org.jboss.xb.binding.ObjectModelFactory;
 import org.jboss.xb.binding.Unmarshaller;
@@ -48,7 +47,6 @@
 import org.snmp4j.PDUv1;
 import org.snmp4j.ScopedPDU;
 import org.snmp4j.Snmp;
-import org.snmp4j.event.ResponseEvent;
 import org.snmp4j.mp.SnmpConstants;
 import org.snmp4j.smi.Counter32;
 import org.snmp4j.smi.Counter64;
@@ -60,7 +58,6 @@
 import org.snmp4j.smi.Variable;
 import org.snmp4j.smi.VariableBinding;
 import org.snmp4j.util.DefaultPDUFactory;
-import org.snmp4j.util.PDUFactory;
 
 /**
  * Implement RequestHandler with mapping of snmp get/set requests
@@ -182,20 +179,12 @@
     */
    
    	public PDU snmpReceivedGetBulk(PDU pdu){
-   		PDU response;
+   		PDU response = getResponsePDU(pdu);
+   		if(response == null) {
+   			return response;
+   		}
    		
-		if (pdu instanceof ScopedPDU){
-			response = DefaultPDUFactory.createPDU(SnmpConstants.version3);
-		} else if (pdu instanceof PDUv1){
-			log.debug("snmpReceievedGetBulk: cannot getBulk with V1 PDU.");
-			return null;
-		} else {
-			response = new PDU();
-		} 
-		response.setType(PDU.RESPONSE);
-
 		final boolean trace = log.isTraceEnabled();
-			
 		if (trace) {
 			log.trace("requestID=" + pdu.getRequestID() + ", elementCount="
 					+ pdu.size());
@@ -317,19 +306,7 @@
 		// flags the end of the MIB 
 		boolean endOfMib = false;
 		
-		if (pdu instanceof ScopedPDU){
-			/* ScopedPDUs are not fully supported. this check is here so that when
-			 * SnmpAgentService is updated to support v3 correctly, we won't have to 
-			 * add it in.*/
-			response = DefaultPDUFactory.createPDU(SnmpConstants.version3);
-		} else if (pdu instanceof PDUv1){
-			// v1
-			response = DefaultPDUFactory.createPDU(SnmpConstants.version1);
-		} else {
-			// v2c
-			response = new PDU();
-		} 
-		response.setType(PDU.RESPONSE);
+		response = getResponsePDU(pdu); 		
 		//indicate by copying the Req ID that this response is for the PDU sent with that ReqID.
 		
 		final boolean trace = log.isTraceEnabled();
@@ -412,8 +389,8 @@
 	 	}
 		//TODO: check size constraints of the sender
 		return response;
-	}	
-		
+	}
+
 	/**
 	 * <P>
 	 * This method is defined to handle SNMP Set requests that are received by
@@ -434,21 +411,12 @@
 	 */
 	public PDU snmpReceivedSet(PDU pdu)
    {
-		PDU response;
+		PDU response = getResponsePDU(pdu);
 		// the modified OID entries so far.  
 		HashSet<VariableBinding> modified = new HashSet<VariableBinding>(); 
 		int errorIndex = 1;
 		Variable var, oldVar = null; // oldVar variable for storing into modified
 		
-		if (pdu instanceof ScopedPDU){
-			response = DefaultPDUFactory.createPDU(SnmpConstants.version3);
-		} else if (pdu instanceof PDUv1){
-			response = DefaultPDUFactory.createPDU(SnmpConstants.version1);
-		} else {
-			response = new PDU();
-		} 
-		response.setType(PDU.RESPONSE);
-		
 		final boolean trace = log.isTraceEnabled();
 		// TODO: why is this before a null check? if the pdu is null, pdu.getRequestID() and pdu.size() will both fail.
 		if (trace) {
@@ -514,8 +482,41 @@
 		}
 	return response;
    }		
-			
+	
 	/**
+	 * This method returns the correct response PDU from the given request PDU
+	 * passed in parameters.
+	 */
+	private PDU getResponsePDU(PDU pdu) {
+		PDU response;						
+		if (pdu instanceof ScopedPDU){
+			/* ScopedPDUs are not fully supported. this check is here so that when
+			 * SnmpAgentService is updated to support v3 correctly, we won't have to 
+			 * add it in.*/
+			response = DefaultPDUFactory.createPDU(SnmpConstants.version3);			
+			/* A.3.4.  Applications that Send Responses
+			   The contextEngineID, contextName, securityModel, securityName,
+			   securityLevel, and stateReference parameters are from the initial
+			   processPdu primitive.  The PDU and statusInformation are the results
+			   of processing.*/
+			((ScopedPDU)response).setContextEngineID(((ScopedPDU) pdu).getContextEngineID());
+			((ScopedPDU)response).setContextName(((ScopedPDU) pdu).getContextName());
+		} else if (pdu instanceof PDUv1){
+			if(pdu.getType() == PDU.GETBULK) {
+				log.debug("snmpReceievedGetBulk: cannot getBulk with V1 PDU.");
+				return null;			
+			}
+			// v1
+			response = DefaultPDUFactory.createPDU(SnmpConstants.version1);
+		} else {
+			// v2c
+			response = new PDU();
+		}
+		response.setType(PDU.RESPONSE);
+		return response;
+	}	
+	
+	/**
 	 * <P>
 	 * This method is defined to handle SNMP requests that are received by the
 	 * session. The parameters allow the handler to determine the host, port,
@@ -782,8 +783,15 @@
 		//TODO: all types managed by the PDU
 		if (val instanceof Long)
         {
-			result = new Counter32((Long)val);
+			result = new OctetString(((Long)val).toString());
 		}
+		else if (val instanceof Boolean)
+        {
+			if(((Boolean)val).booleanValue())
+				result = new Integer32(1);
+			else 
+				result = new Integer32(0);
+		}
         else if (val instanceof String)
         {
         	result = new OctetString((String) val);
@@ -822,24 +830,36 @@
 	 * @throws VariableTypeException if the method was unable to convert the type of val into
 	 * a type compatible with the MBean server.
 	 */
-	private Object convertVariableToValue(final Variable val) throws VariableTypeException{
+	private Object convertVariableToValue(final Variable val, final Object attribute) throws VariableTypeException{
 		Object result = null;
 		if (val instanceof OctetString)
 		{	
-			result = val.toString();
+			if(attribute instanceof Long) {
+				result = Long.parseLong(val.toString());
+			} else {
+				result = val.toString();
+			}
 		}
 		else if (val instanceof Integer32)
 		{
-			result = new Integer(((Integer32)val).getValue());
+			if(attribute instanceof Boolean) {
+				if(((Integer32)val).getValue() == 0) {
+					result = Boolean.FALSE;
+				} else {
+					result = Boolean.TRUE;
+				}
+			} else {
+				result = Integer.valueOf(((Integer32)val).getValue());
+			}
 		}
 		else if (val instanceof Counter32)
 		{
-			result = new Long(((Counter32)val).getValue());
+			result = Long.valueOf(((Counter32)val).getValue());
 		}
 		else if (val instanceof Counter64)
 		{
-			result = new Long(((Counter64)val).getValue());
-		}
+			result = Long.valueOf(((Counter64)val).getValue());
+		}		
 		else{
 			throw new VariableTypeException(); //no instance could be created.
 		}
@@ -887,13 +907,13 @@
 			try
 			{		
 				Object other = server.getAttribute(be.mbean, be.attr.getName());
-				Object val = convertVariableToValue(newVal);
+				Object val = convertVariableToValue(newVal, other);
 				
 				if (val.getClass() != other.getClass() ){
 					log.debug("setValueFor: attempt to set an MBean Attribute with the wrong type.");
 					ssy = newVal;
 				}
-				
+								
 				Attribute at = new Attribute(be.attr.getName(), val);
 				server.setAttribute(be.mbean, at);
 			

Modified: branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/SnmpAgentService.java
===================================================================
--- branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/SnmpAgentService.java	2011-05-26 14:45:44 UTC (rev 111458)
+++ branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/SnmpAgentService.java	2011-05-26 15:50:18 UTC (rev 111459)
@@ -19,33 +19,40 @@
  */
 package org.jboss.jmx.adaptor.snmp.agent;
 
+import java.io.InputStream;
 import java.net.InetAddress;
-import java.net.InetSocketAddress;
 import java.net.UnknownHostException;
+import java.util.ArrayList;
+import java.util.Iterator;
 
 import javax.management.Notification;
 import javax.management.ObjectName;
 
-import org.jboss.bootstrap.api.as.config.JBossASServerConfig;
+import org.jboss.jmx.adaptor.snmp.config.user.User;
 import org.jboss.system.ListenerServiceMBeanSupport;
-
-//SNMP4J IMPORTS
-import org.snmp4j.AbstractTarget;
-import org.snmp4j.CommandResponder;
-import org.snmp4j.CommandResponderEvent;
-import org.snmp4j.MessageDispatcher;
-import org.snmp4j.MessageException;
+import org.jboss.xb.binding.MappingObjectModelFactory;
+import org.jboss.xb.binding.Unmarshaller;
+import org.jboss.xb.binding.UnmarshallerFactory;
+import org.snmp4j.MessageDispatcherImpl;
 import org.snmp4j.Snmp;
-import org.snmp4j.Target;
-import org.snmp4j.event.CounterEvent;
-import org.snmp4j.mp.SnmpConstants;
-import org.snmp4j.mp.StateReference;
-import org.snmp4j.mp.StatusInformation;
-import org.snmp4j.smi.*;
-import org.snmp4j.transport.DefaultTcpTransportMapping;
+import org.snmp4j.TransportMapping;
+import org.snmp4j.mp.MPv1;
+import org.snmp4j.mp.MPv2c;
+import org.snmp4j.mp.MPv3;
+import org.snmp4j.security.Priv3DES;
+import org.snmp4j.security.PrivAES128;
+import org.snmp4j.security.PrivAES192;
+import org.snmp4j.security.PrivAES256;
+import org.snmp4j.security.PrivDES;
+import org.snmp4j.security.SecurityModels;
+import org.snmp4j.security.SecurityProtocols;
+import org.snmp4j.security.USM;
+import org.snmp4j.security.UsmUser;
+import org.snmp4j.smi.OctetString;
+import org.snmp4j.smi.UdpAddress;
 import org.snmp4j.transport.DefaultUdpTransportMapping;
-import org.snmp4j.PDU;
 
+
 /**
  * <tt>SnmpAgentService</tt> is an MBean class implementing an SNMP agent.
  *
@@ -82,6 +89,9 @@
    /** Trap counter */
    private Counter trapCounter = null;
 
+   /** Name of the file containing SNMP users */
+   private String usersResName = null;
+   
    /** Name of the file containing SNMP manager specifications */
    private String managersResName = null;  
 
@@ -129,13 +139,28 @@
 
    /** The trap emitting subsystem*/
    private TrapEmitter trapEmitter = null;
-
-   /** the snmp agent session for handling get/set requests */
-//   private SnmpAgentSession agentSession = null;
    
    /** the request handler instance handling get/set requests */
    private RequestHandler requestHandler;
    
+   /** the location of the agent's settings**/
+   private String configFileResName = null;
+   
+   /** the location of the boot counter persistent store **/
+   private String bootCounterResName = null;
+   
+   private Snmp session;
+   
+   private TransportMapping[] transportMappings;
+   
+   private SnmpRequest responder;
+  
+   private USM usm;
+   
+   private MPv3 mpv3;
+   
+   private MessageDispatcherImpl dispatcher;
+   
    // Constructors --------------------------------------------------
    
    /**
@@ -520,7 +545,6 @@
       // initialise the snmp agent
       log.debug("Starting snmp agent ...");
       
-      //At the moment does nothing
       startAgent();
       
       log.info("SNMP agent going active");
@@ -550,7 +574,7 @@
       log.debug("Stopping snmp agent ...");
 //      this.agentSession.close();
 //      this.agentSession = null;
-      
+      session.close();
       log.info("SNMP agent stopped");
    }    
    
@@ -577,27 +601,119 @@
    }
    
    // Private -------------------------------------------------------
+   
+   private void initResponder(){
+	   OctetString localEngineID=new OctetString(MPv3.createLocalEngineID());
+	   this.responder = new SnmpRequest(this.requestHandler, log, localEngineID);
+   }
+   // add updateEngineBoots to USM constuctor call
+   private void initMessageDispatcher(){
+	   this.dispatcher = new MessageDispatcherImpl();	   
+	   usm = new USM(SecurityProtocols.getInstance(),
+			   		 responder.getLocalEngineID(),
+			   		 0);
+	   mpv3 = new MPv3(usm);
+	   SecurityModels.getInstance().addSecurityModel(usm);
+	   SecurityProtocols.getInstance().addDefaultProtocols();
+	   // all other privacy and authentication protocols are provided by the above method
+	   SecurityProtocols.getInstance().addPrivacyProtocol(new Priv3DES());	   
+	   dispatcher.addMessageProcessingModel(new MPv1());
+	   dispatcher.addMessageProcessingModel(new MPv2c());
+	   dispatcher.addMessageProcessingModel(mpv3);
+   }
+   
+   private void initRequestHandler()throws Exception{
+	   this.requestHandler = (RequestHandler)Class.forName(this.requestHandlerClassName,true,this.getClass().getClassLoader()).newInstance();
+	   this.requestHandler.initialize(this.requestHandlerResName, 
+			   				     this.getServer(), 
+			   				     this.log, 
+			   				     this.clock); 
+   }
+   
+   private void initTransportMapping(){
+	   this.transportMappings = new TransportMapping[1];
+	   try{
+		   this.transportMappings[0] = new DefaultUdpTransportMapping(new UdpAddress(this.bindAddress, this.port));
+	   }catch(Exception e){
+		   log.debug("Exception in initialization of Tranport Map!!");
+	   }
+   }
+   
+   private void initSession(){
+	   this.session = new Snmp(dispatcher);
+	   for (int i = 0; i < transportMappings.length;i++){
+		   try{
+			   session.addTransportMapping(transportMappings[i]);
+		   }
+		   catch(Exception e){
+			   log.warn("Tranport mapping invalid. Failed to initialize mapping '"+
+					    transportMappings[i]+"' with: "+e.getMessage());
+			   
+		   }
+	   }
+	   this.session.addCommandResponder(responder);
+   }
+   
+   /*
+    * Read the users from the users.xml and add them to the usm
+    */
+   private void addUsmUsers() throws Exception {
+	   MappingObjectModelFactory momf = new MappingObjectModelFactory();
+	   momf.mapElementToClass("user-list", ArrayList.class);
+	   momf.mapElementToClass("user", User.class);
+	      
+	   ArrayList<User> userList = null;
+	   InputStream is = null;
+	   try {
+		   // locate managers.xml
+		   final String resName = this.usersResName;
+		   is = SecurityActions.getThreadContextClassLoaderResource(resName);
+         
+		   // create unmarshaller
+		   Unmarshaller unmarshaller = UnmarshallerFactory.newInstance()
+               .newUnmarshaller();
+         
+		   // let JBossXB do it's magic using the MappingObjectModelFactory
+		   userList = (ArrayList<User>) unmarshaller.unmarshal(is, momf, null);         
+      } catch (Exception e) {
+    	  log.error("Accessing resource '" + usersResName + "'");
+    	  throw e;
+      } finally {
+    	  if (is != null) {
+            // close the XML stream
+            is.close();            
+    	  }
+      }
+	  
+      for (Iterator<User> userIt = userList.iterator(); userIt.hasNext(); ) {
+    	  User user = userIt.next();
+        	 
+    	  UsmUser usmUser = new UsmUser(new OctetString(user.getSecurityName()),
+               user.getAuthenticationProtocolID(),
+               new OctetString(user.getAuthenticationPassphrase()),
+               user.getPrivacyProtocolID(),
+               new OctetString(user.getPrivacyPassphrase()));
+    	  this.usm.addUser(usmUser.getSecurityName(), usm.getLocalEngineID(),usmUser);
+      }
+   }
 
+   //TODO: for v3 support we need to have this Snmp object have a USM (user security model) associated with it
+   // as well as the appropriate MP. 
+   // the new Snmp(TransportMapping) constructor already initializes a MessageDispatcherImpl with all MP's associated. 
    /**
     * Start the embedded agent 
     */
    private void startAgent()
       throws Exception
    {
-	   
-      // Instantiate and initialize the RequestHandler implementation
-      requestHandler = (RequestHandler)Class.forName(
-         this.requestHandlerClassName, true, this.getClass().getClassLoader()).newInstance();
-      requestHandler.initialize(this.requestHandlerResName, this.getServer(), this.log, this.clock);
-	   
-      //TODO: for v3 support we need to have this Snmp object have a USM (user security model) associated with it
-      // as well as the appropriate MP. 
-      
-	   //Snmp snmp = new Snmp(new DefaultTcpTransportMapping(new TcpAddress(this.bindAddress, this.port)));
-       Snmp snmp = new Snmp(new DefaultUdpTransportMapping(new UdpAddress(this.bindAddress, this.port)));
-       SnmpRequest request = new SnmpRequest(requestHandler, log);
-	   snmp.addCommandResponder(request);
-	   snmp.listen();
+	  initRequestHandler();
+	  initResponder();
+	  initMessageDispatcher();	   
+	  initTransportMapping();
+      initSession();
+      addUsmUsers();
+     
+      session.listen();
    }
    
    /**
@@ -612,4 +728,18 @@
          return InetAddress.getByName(host);
    }
 
+	/**
+	 * @param usersResName the usersResName to set
+	 */
+	public void setUsersResName(String usersResName) {
+		this.usersResName = usersResName;
+	}
+	
+	/**
+	 * @return the usersResName
+	 */
+	public String getUsersResName() {
+		return usersResName;
+	}
+
 }

Modified: branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/SnmpAgentServiceMBean.java
===================================================================
--- branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/SnmpAgentServiceMBean.java	2011-05-26 14:45:44 UTC (rev 111458)
+++ branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/SnmpAgentServiceMBean.java	2011-05-26 15:50:18 UTC (rev 111459)
@@ -44,6 +44,10 @@
    /** The name of the file containing SNMP manager specifications */
    void setManagersResName(String managersResName);
    String getManagersResName();
+   
+   /** The name of the file containing SNMPv3 users */
+   void setUsersResName(String usersResName);
+   String getUsersResName();
 
    /** The name of the file containing the notification/trap mappings */
    void setNotificationMapResName(String notificationMapResName);

Modified: branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/SnmpRequest.java
===================================================================
--- branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/SnmpRequest.java	2011-05-26 14:45:44 UTC (rev 111458)
+++ branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/SnmpRequest.java	2011-05-26 15:50:18 UTC (rev 111459)
@@ -8,6 +8,7 @@
 import org.snmp4j.mp.SnmpConstants;
 import org.snmp4j.mp.StateReference;
 import org.snmp4j.mp.StatusInformation;
+import org.snmp4j.smi.OctetString;
 
 public class SnmpRequest implements CommandResponder {
 	
@@ -16,11 +17,22 @@
 	
 	/** the request handler instance handling get/set requests */
 	private RequestHandler requestHandler;
+	
+	
+	// the local engine ID for our CommandResponder. This is needed for
+	// v3 communication
+	private OctetString localContextEngineID;
 
 	public SnmpRequest(RequestHandler requestHandler, Logger log){
 		this.requestHandler = requestHandler;
 		this.log = log;
 	}
+	// constructor with engine ID as well
+	public SnmpRequest(RequestHandler requestHandler, Logger log, OctetString ceID){
+		this.requestHandler = requestHandler;
+		this.log = log;		
+		this.localContextEngineID = ceID;
+	}
 	
 	public void setRequestHandler(RequestHandler requestHandler){
 		this.requestHandler = requestHandler;
@@ -31,7 +43,6 @@
 	}
 
 	@Override
-	//TODO: catch thrown exceptions properly and decide what to do with them. 
 	public void processPdu(CommandResponderEvent event){
 		PDU pdu = event.getPDU();
 
@@ -77,45 +88,23 @@
 	
 	private void sendResponse(CommandResponderEvent requestEvent, PDU response) throws MessageException{
 	
-			if (response.getBERLength() > requestEvent.getMaxSizeResponsePDU()) {
-				// response is tooBig
-				if (response.getType() != PDU.REPORT) {
-					if (requestEvent.getPDU().getType() == PDU.GETBULK) {
-						while ((response.size() > 0) &&
-						   (response.getBERLength() >
-						    requestEvent.getMaxSizeResponsePDU())) 
-						{
-							response.trim();
-						}
-					}
-					else {
-						response.clear();
-						response.setRequestID(requestEvent.getPDU().getRequestID());
-						response.setErrorStatus(PDU.tooBig);
-					}
-				}
-				if (response.getBERLength() > requestEvent.getMaxSizeResponsePDU()) {
-					//still too big and can't send a response
-					return;
-				}
-			}
-
-			StatusInformation status = new StatusInformation();
-			StateReference stateRef = requestEvent.getStateReference();
-			if (stateRef == null) {
-				log.warn("No state reference available for requestEvent="+	
-			    requestEvent+". Cannot return response="+response);
-			}
-			else {
-				stateRef.setTransportMapping(requestEvent.getTransportMapping());
-				int resp = requestEvent.getMessageDispatcher().returnResponsePdu(requestEvent.getMessageProcessingModel(),
-				               requestEvent.getSecurityModel(),
-				               requestEvent.getSecurityName(),
-				               requestEvent.getSecurityLevel(),
-				               response,
-				               requestEvent.getMaxSizeResponsePDU(),
-				               stateRef,
-				               status);
-			}
+		response.setErrorIndex(0);
+		response.setErrorStatus(0);
+		response.setType(PDU.RESPONSE);
+	    StatusInformation statusInformation = new StatusInformation();
+	    StateReference ref = requestEvent.getStateReference();
+	    requestEvent.getMessageDispatcher().returnResponsePdu(requestEvent.
+	                                                 getMessageProcessingModel(),
+	                                                 requestEvent.getSecurityModel(),
+	                                                 requestEvent.getSecurityName(),
+	                                                 requestEvent.getSecurityLevel(),
+	                                                 response,
+	                                                 requestEvent.getMaxSizeResponsePDU(),
+	                                                 ref,
+	                                                 statusInformation);
 	}
+	
+	public OctetString getLocalEngineID(){
+		return this.localContextEngineID;
+	}
 }

Modified: branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/SnmpVarBindFactory.java
===================================================================
--- branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/SnmpVarBindFactory.java	2011-05-26 14:45:44 UTC (rev 111458)
+++ branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/SnmpVarBindFactory.java	2011-05-26 15:50:18 UTC (rev 111459)
@@ -24,11 +24,6 @@
 import java.util.Map;
 
 import org.jboss.logging.Logger;
-import org.opennms.protocols.snmp.SnmpCounter64;
-import org.opennms.protocols.snmp.SnmpInt32;
-import org.opennms.protocols.snmp.SnmpObjectId;
-import org.opennms.protocols.snmp.SnmpOctetString;
-import org.opennms.protocols.snmp.SnmpVarBind;
 import org.snmp4j.smi.Counter32;
 import org.snmp4j.smi.Counter64;
 import org.snmp4j.smi.Integer32;

Modified: branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/test/Test.java
===================================================================
--- branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/test/Test.java	2011-05-26 14:45:44 UTC (rev 111458)
+++ branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/test/Test.java	2011-05-26 15:50:18 UTC (rev 111459)
@@ -1,31 +1,25 @@
+package org.jboss.jmx.adaptor.snmp.test;
+
 import java.io.IOException;
-import java.net.InetAddress;
 import java.net.UnknownHostException;
-import java.util.Vector;
 
-import org.snmp4j.CommandResponder;
-import org.snmp4j.CommandResponderEvent;
 import org.snmp4j.CommunityTarget;
 import org.snmp4j.PDU;
+import org.snmp4j.ScopedPDU;
 import org.snmp4j.Snmp;
-import org.snmp4j.Target;
+import org.snmp4j.UserTarget;
 import org.snmp4j.event.ResponseEvent;
-import org.snmp4j.event.ResponseListener;
 import org.snmp4j.mp.SnmpConstants;
-import org.snmp4j.smi.*;
-import org.snmp4j.transport.DefaultTcpTransportMapping;
-import org.snmp4j.transport.DefaultUdpTransportMapping;
-//v3 requires the following
-import org.snmp4j.ScopedPDU;
-import org.snmp4j.UserTarget;
-import org.snmp4j.security.AuthMD5;
-import org.snmp4j.security.PrivDES;
-import org.snmp4j.security.UsmUser;
 import org.snmp4j.security.SecurityLevel;
+import org.snmp4j.security.SecurityModels;
 import org.snmp4j.security.SecurityProtocols;
-import org.snmp4j.security.SecurityModels;
 import org.snmp4j.security.USM;
-import org.snmp4j.mp.MPv3;
+import org.snmp4j.smi.Address;
+import org.snmp4j.smi.GenericAddress;
+import org.snmp4j.smi.OID;
+import org.snmp4j.smi.OctetString;
+import org.snmp4j.smi.VariableBinding;
+import org.snmp4j.transport.DefaultUdpTransportMapping;
 
 public class Test {
 	
@@ -44,6 +38,9 @@
 		else if (args[0].equals("set")){
 			set(args);
 		}
+		else if (args[0].equals("getv3")){
+			getv3();
+		}
 		else if (args[0].equals("testnullpdu")){
 			testnull();
 		}
@@ -110,19 +107,69 @@
 		   
 	   }
 	
+   public static void getv3(){
+	   ScopedPDU pdu = new ScopedPDU();
+	   pdu.add(new VariableBinding(new OID("1.3.6")));
+	   pdu.setType(PDU.GETNEXT);
+	   Address targetAddress = GenericAddress.parse("udp:127.0.0.1/1161");
+	   UserTarget target = new UserTarget();
+	   target.setVersion(SnmpConstants.version3);
+	   target.setAddress(targetAddress);
+	   target.setRetries(2);
+	   target.setTimeout(10000);
+	   target.setSecurityLevel(SecurityLevel.AUTH_PRIV);
+	   target.setSecurityName(new OctetString("MD5DES"));
+	   
+		try {
+			DefaultUdpTransportMapping transport = new DefaultUdpTransportMapping();
+			transport.listen();
+			System.out.println("READY: "+System.currentTimeMillis());
+ 			Snmp snmp = new Snmp(transport);
+			USM usm = new USM(SecurityProtocols.getInstance(), new OctetString(), 0);
+			SecurityModels.getInstance().addSecurityModel(usm);
+			long t1 = System.currentTimeMillis();
+			System.out.println("SENDING: "+t1);
+			System.out.println("PDU: "+pdu);
+			ResponseEvent responseEvent = snmp.send(pdu, target);
+			long t2=System.currentTimeMillis();
+			System.out.println("SENT: "+t2);
+			System.out.println("ELAPSED: "+(t2-t1));
+			System.out.println("response " + responseEvent.toString());
+
+			PDU responsePDU = responseEvent.getResponse();
+			if (responsePDU == null){
+				System.out.println("Request timed out");
+			}
+			else{
+				System.out.println("Received response "+responsePDU);
+			}
+				System.out.println("Peer Address: "+responseEvent.getPeerAddress());
+		} catch (UnknownHostException e1) {
+			// TODO Auto-generated catch block
+			e1.printStackTrace();
+		} catch (IOException e1) {
+			// TODO Auto-generated catch block
+			e1.printStackTrace();
+		} catch (Exception e) {
+			System.out.println("Some Other exception!!");
+		}
+	   
+
+   }
 	
-	
    public static void getnext(String [] oids){
-	PDU pdu = new PDU();
+	ScopedPDU pdu = new ScopedPDU();
 	pdu.setType(PDU.GETNEXT);
 	for (int i =1; i < oids.length; i++){
 		pdu.add(new VariableBinding(new OID(oids[i])));	
 	}
 	
-	CommunityTarget target = new CommunityTarget();
-	OctetString community = new OctetString("public");
-	target.setCommunity(community);
-	target.setVersion(SnmpConstants.version2c);
+	//CommunityTarget target = new CommunityTarget();
+	//OctetString community = new OctetString("public");
+	//target.setCommunity(community);
+	//target.setVersion(SnmpConstants.version2c);
+	UserTarget target = new UserTarget();
+	target.setVersion(SnmpConstants.version3);
 	Address targetAddress = GenericAddress.parse("udp:127.0.0.1/1161");
 	target.setAddress(targetAddress);
 	target.setRetries(2);

Modified: branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/trapd/TrapReceiver.java
===================================================================
--- branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/trapd/TrapReceiver.java	2011-05-26 14:45:44 UTC (rev 111458)
+++ branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/trapd/TrapReceiver.java	2011-05-26 15:50:18 UTC (rev 111459)
@@ -22,13 +22,6 @@
 import java.net.InetAddress;
 
 import org.jboss.logging.Logger;
-import org.opennms.protocols.snmp.SnmpOctetString;
-import org.opennms.protocols.snmp.SnmpPduPacket;
-import org.opennms.protocols.snmp.SnmpPduRequest;
-import org.opennms.protocols.snmp.SnmpPduTrap;
-import org.opennms.protocols.snmp.SnmpTrapHandler;
-import org.opennms.protocols.snmp.SnmpTrapSession;
-import org.opennms.protocols.snmp.SnmpVarBind;
 
 /**
  * Implements an SNMP trap reception engine
@@ -39,7 +32,6 @@
  * @author  <a href="mailto:dimitris at jboss.org">Dimitris Andreadis</a>
 **/
 public class TrapReceiver
-    implements SnmpTrapHandler
 {
     /** target logger */
     protected final Logger log;
@@ -54,114 +46,114 @@
       this.log = log; 
    }
     
-   /**
-    * Receives and logs information about SNMPv2 traps.
-    *
-    * @param session   the trap session that received the PDU
-    * @param agent     the address of the remote sender
-    * @param port      the remote port where the pdu was transmitted from
-    * @param community the decoded community string
-    * @param pdu       the decoded v2 trap pdu
-   **/
-   public void snmpReceivedTrap(SnmpTrapSession session, InetAddress agent, 
-                                int port, SnmpOctetString community,
-                                SnmpPduPacket pdu)
-   {
-      StringBuffer sbuf = new StringBuffer();
-        
-      sbuf.append("V2 Trap from ").append(agent.toString());
-      sbuf.append(" on port ").append(port);
-      sbuf.append("\nPDU command......... ").append(pdu.getCommand());
-      sbuf.append("\nPDU Length.......... ").append(pdu.getLength());
-      sbuf.append("\nCommunity string.... ").append(community.toString());
-		
-      if(pdu instanceof SnmpPduRequest)
-      {
-         SnmpPduRequest spdu = (SnmpPduRequest) pdu;
-         
-         sbuf.append("\nPDU Error Status.... ").append(spdu.getErrorStatus());
-         sbuf.append("\nPDU Error Index..... ").append(spdu.getErrorIndex());
-         sbuf.append("\n");
-      }
-	
-      for (int i = 0; i < pdu.getLength(); i++ )
-      {
-         SnmpVarBind vb = pdu.getVarBindAt(i);
-         
-         sbuf.append("Varbind[").append(i).append("] := ");
-         sbuf.append(vb.getName().toString()).append(" --> ");
-         sbuf.append(vb.getValue().toString()).append("\n");		
-      }
-      log.debug(sbuf.toString());
-   } // snmpReceivedTrap
-
-   /**
-    * Receives and logs information about SNMPv1 traps.
-    *
-     * @param session   the trap session that received the PDU
-    * @param agent     the address of the remote sender
-    * @param port      the remote port where the pdu was transmitted from
-    * @param community the decoded community string
-    * @param pdu       the decoded v1 trap pdu
-   **/
-   public void snmpReceivedTrap(SnmpTrapSession session, InetAddress agent, 
-                                int port, SnmpOctetString community,
-                                SnmpPduTrap pdu)
-   {
-      StringBuffer sbuf = new StringBuffer();
-        
-      sbuf.append("V1 Trap from agent ").append(agent.toString());
-      sbuf.append(" on port ").append(port);
-      sbuf.append("\nIP Address......... ").append(pdu.getAgentAddress());
-      sbuf.append("\nEnterprise Id...... ").append(pdu.getEnterprise());
-      sbuf.append("\nGeneric ........... ").append(pdu.getGeneric());
-      sbuf.append("\nSpecific .......... ").append(pdu.getSpecific());
-      sbuf.append("\nTimeStamp ......... ").append(pdu.getTimeStamp());
-      sbuf.append("\nLength............. ").append(pdu.getLength());
-      sbuf.append("\nCommunity string... ").append(community.toString());
-      sbuf.append("\n");
-	
-      for (int i = 0; i < pdu.getLength(); i++ )
-      {
-         SnmpVarBind vb = pdu.getVarBindAt(i);
-         
-         sbuf.append("Varbind[").append(i).append("] := ");
-         sbuf.append(vb.getName().toString()).append(" --> ");
-         sbuf.append(vb.getValue().toString()).append("\n");			
-      }
-      log.debug(sbuf.toString());
-   } // snmpReceivedTrap
-	
-   /**
-    * Processes session errors.
-    *
-    * @param session the trap session in error
-    * @param error   the error condition
-    * @param ref     the reference object, if any
-   **/
-   public void snmpTrapSessionError(SnmpTrapSession session,
-                                    int error, Object ref)
-   {
-      StringBuffer sbuf = new StringBuffer();
-           
-      if(ref != null) {
-          sbuf.append("Session error (").append(error).append(") reference: ");
-          sbuf.append(ref.toString());
-      }
-      else {
-           sbuf.append("Session error (").append(error).append(")");
-      }
-	
-      try {
-         if(error == SnmpTrapSession.ERROR_EXCEPTION)
-            session.raise();    
-      }
-      catch (Throwable e) {
-          sbuf.append(" <").append(e).append(">"); 
-      }
-       
-      log.error(sbuf.toString());
-       
-   } // snmpTrapSessionError
+//   /**
+//    * Receives and logs information about SNMPv2 traps.
+//    *
+//    * @param session   the trap session that received the PDU
+//    * @param agent     the address of the remote sender
+//    * @param port      the remote port where the pdu was transmitted from
+//    * @param community the decoded community string
+//    * @param pdu       the decoded v2 trap pdu
+//   **/
+//   public void snmpReceivedTrap(SnmpTrapSession session, InetAddress agent, 
+//                                int port, SnmpOctetString community,
+//                                SnmpPduPacket pdu)
+//   {
+//      StringBuffer sbuf = new StringBuffer();
+//        
+//      sbuf.append("V2 Trap from ").append(agent.toString());
+//      sbuf.append(" on port ").append(port);
+//      sbuf.append("\nPDU command......... ").append(pdu.getCommand());
+//      sbuf.append("\nPDU Length.......... ").append(pdu.getLength());
+//      sbuf.append("\nCommunity string.... ").append(community.toString());
+//		
+//      if(pdu instanceof SnmpPduRequest)
+//      {
+//         SnmpPduRequest spdu = (SnmpPduRequest) pdu;
+//         
+//         sbuf.append("\nPDU Error Status.... ").append(spdu.getErrorStatus());
+//         sbuf.append("\nPDU Error Index..... ").append(spdu.getErrorIndex());
+//         sbuf.append("\n");
+//      }
+//	
+//      for (int i = 0; i < pdu.getLength(); i++ )
+//      {
+//         SnmpVarBind vb = pdu.getVarBindAt(i);
+//         
+//         sbuf.append("Varbind[").append(i).append("] := ");
+//         sbuf.append(vb.getName().toString()).append(" --> ");
+//         sbuf.append(vb.getValue().toString()).append("\n");		
+//      }
+//      log.debug(sbuf.toString());
+//   } // snmpReceivedTrap
+//
+//   /**
+//    * Receives and logs information about SNMPv1 traps.
+//    *
+//     * @param session   the trap session that received the PDU
+//    * @param agent     the address of the remote sender
+//    * @param port      the remote port where the pdu was transmitted from
+//    * @param community the decoded community string
+//    * @param pdu       the decoded v1 trap pdu
+//   **/
+//   public void snmpReceivedTrap(SnmpTrapSession session, InetAddress agent, 
+//                                int port, SnmpOctetString community,
+//                                SnmpPduTrap pdu)
+//   {
+//      StringBuffer sbuf = new StringBuffer();
+//        
+//      sbuf.append("V1 Trap from agent ").append(agent.toString());
+//      sbuf.append(" on port ").append(port);
+//      sbuf.append("\nIP Address......... ").append(pdu.getAgentAddress());
+//      sbuf.append("\nEnterprise Id...... ").append(pdu.getEnterprise());
+//      sbuf.append("\nGeneric ........... ").append(pdu.getGeneric());
+//      sbuf.append("\nSpecific .......... ").append(pdu.getSpecific());
+//      sbuf.append("\nTimeStamp ......... ").append(pdu.getTimeStamp());
+//      sbuf.append("\nLength............. ").append(pdu.getLength());
+//      sbuf.append("\nCommunity string... ").append(community.toString());
+//      sbuf.append("\n");
+//	
+//      for (int i = 0; i < pdu.getLength(); i++ )
+//      {
+//         SnmpVarBind vb = pdu.getVarBindAt(i);
+//         
+//         sbuf.append("Varbind[").append(i).append("] := ");
+//         sbuf.append(vb.getName().toString()).append(" --> ");
+//         sbuf.append(vb.getValue().toString()).append("\n");			
+//      }
+//      log.debug(sbuf.toString());
+//   } // snmpReceivedTrap
+//	
+//   /**
+//    * Processes session errors.
+//    *
+//    * @param session the trap session in error
+//    * @param error   the error condition
+//    * @param ref     the reference object, if any
+//   **/
+//   public void snmpTrapSessionError(SnmpTrapSession session,
+//                                    int error, Object ref)
+//   {
+//      StringBuffer sbuf = new StringBuffer();
+//           
+//      if(ref != null) {
+//          sbuf.append("Session error (").append(error).append(") reference: ");
+//          sbuf.append(ref.toString());
+//      }
+//      else {
+//           sbuf.append("Session error (").append(error).append(")");
+//      }
+//	
+//      try {
+//         if(error == SnmpTrapSession.ERROR_EXCEPTION)
+//            session.raise();    
+//      }
+//      catch (Throwable e) {
+//          sbuf.append(" <").append(e).append(">"); 
+//      }
+//       
+//      log.error(sbuf.toString());
+//       
+//   } // snmpTrapSessionError
     
 } // class TrapReceiver



More information about the jboss-cvs-commits mailing list