[jboss-cvs] JBossAS SVN: r112095 - in trunk/varia: src/assembly and 9 other directories.
jboss-cvs-commits at lists.jboss.org
jboss-cvs-commits at lists.jboss.org
Fri Aug 19 10:58:50 EDT 2011
Author: thauser at redhat.com
Date: 2011-08-19 10:58:49 -0400 (Fri, 19 Aug 2011)
New Revision: 112095
Added:
trunk/varia/src/assembly/mib-generator.xml
trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/AttributeTableMapper.java
trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/BindEntry.java
trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/EndOfMibViewException.java
trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/NoSuchInstanceException.java
trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/NoSuchObjectException.java
trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/SnmpAgentRequestHandler.java
trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/SnmpRequest.java
trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/TableMapper.java
trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/VariableTypeException.java
trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/config/user/
trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/config/user/AuthenticationProtocol.java
trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/config/user/PrivacyProtocol.java
trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/config/user/User.java
trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/generator/
trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/generator/CmdLineParser.java
trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/generator/Generator.java
trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/generator/MIBGenerator.java
trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/generator/Parser.java
trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/generator/ParserAttributeBindings.java
trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/generator/ParserNotificationBindings.java
trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/generator/exceptions/
trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/generator/exceptions/NotEnoughInformationException.java
trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/generator/metrics/
trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/generator/metrics/AttributeMappings.java
trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/generator/metrics/ManagedBean.java
trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/generator/metrics/MappedAttribute.java
trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/generator/metrics/Mapping.java
trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/generator/metrics/VarBind.java
trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/generator/metrics/VarBindList.java
trunk/varia/src/resources/services/snmp/config/Attributes.xsd
trunk/varia/src/resources/services/snmp/config/Users.xsd
trunk/varia/src/resources/services/snmp/deploy/users.xml
Modified:
trunk/varia/pom.xml
Log:
adding missing classes from previous snmp-adaptor upgrade;
modify version of mibgen-maven-plugin used to 1.0 instead of 1.0-SNAPSHOT
Modified: trunk/varia/pom.xml
===================================================================
--- trunk/varia/pom.xml 2011-08-18 20:45:19 UTC (rev 112094)
+++ trunk/varia/pom.xml 2011-08-19 14:58:49 UTC (rev 112095)
@@ -196,7 +196,7 @@
<plugin>
<groupId>org.jboss</groupId>
<artifactId>mibgen-maven-plugin</artifactId>
- <version>1.0-SNAPSHOT</version>
+ <version>1.0</version>
<configuration>
<attributesFile>${project.basedir}/src/resources/services/snmp/deploy/attributes.xml</attributesFile>
<notificationsFile>${project.basedir}/src/resources/services/snmp/deploy/notifications.xml</notificationsFile>
Added: trunk/varia/src/assembly/mib-generator.xml
===================================================================
--- trunk/varia/src/assembly/mib-generator.xml (rev 0)
+++ trunk/varia/src/assembly/mib-generator.xml 2011-08-19 14:58:49 UTC (rev 112095)
@@ -0,0 +1,26 @@
+<assembly>
+ <id>mib-generator</id>
+ <formats>
+ <format>jar</format>
+ </formats>
+ <includeBaseDirectory>false</includeBaseDirectory>
+ <dependencySets>
+ <dependencySet>
+ <outputDirectory>/</outputDirectory>
+ <unpack>true</unpack>
+ <includes>
+ <include>org.jboss:jbossxb</include>
+ <include>org.jboss.logging:jboss-logging</include>
+ </includes>
+ </dependencySet>
+ </dependencySets>
+ <fileSets>
+ <fileSet>
+ <directory>target/classes</directory>
+ <outputDirectory>/</outputDirectory>
+ <includes>
+ <include>org/jboss/jmx/adaptor/snmp/generator/**</include>
+ </includes>
+ </fileSet>
+ </fileSets>
+</assembly>
Added: trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/AttributeTableMapper.java
===================================================================
--- trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/AttributeTableMapper.java (rev 0)
+++ trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/AttributeTableMapper.java 2011-08-19 14:58:49 UTC (rev 112095)
@@ -0,0 +1,343 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2011, Red Hat Middleware LLC, and individual contributors
+ * by the @authors tag. See the copyright.txt in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.jmx.adaptor.snmp.agent;
+
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
+import java.util.SortedMap;
+import java.util.SortedSet;
+import java.util.TreeMap;
+import java.util.TreeSet;
+
+import javax.management.MBeanServer;
+import javax.management.ObjectName;
+
+import org.jboss.jmx.adaptor.snmp.config.attribute.ManagedBean;
+import org.jboss.jmx.adaptor.snmp.config.attribute.MappedAttribute;
+import org.jboss.logging.Logger;
+import org.snmp4j.smi.OID;
+import org.snmp4j.smi.OctetString;
+import org.snmp4j.smi.Variable;
+
+/**
+ * @author jean.deruelle at gmail.com
+ *
+ */
+public class AttributeTableMapper {
+
+ private SortedSet<OID> tables = new TreeSet<OID>();
+// private SortedSet<OID> tableRowEntrys = new TreeSet<OID>();
+ /**
+ * keep an index of the OID from attributes.xml
+ */
+ private SortedMap<OID, BindEntry> tableMappings = new TreeMap<OID, BindEntry>();
+// private SortedMap<OID, BindEntry> tableRowEntryMappings = new TreeMap<OID, BindEntry>();
+
+ private MBeanServer server;
+ private Logger log;
+
+ public AttributeTableMapper(MBeanServer server, Logger log) {
+ this.server = server;
+ this.log = log;
+ }
+
+ /**
+ *
+ * @param oid
+ * @return
+ */
+ public BindEntry getTableBinding(OID oid, boolean isRowEntry) {
+ Set<Entry<OID,BindEntry>> entries = null;
+// if(isRowEntry) {
+// entries = tableRowEntryMappings.entrySet();
+// } else {
+ entries = tableMappings.entrySet();
+// }
+ for (Entry<OID,BindEntry> entry : entries) {
+ if (oid.startsWith(entry.getKey())) {
+ BindEntry value = entry.getValue();
+ BindEntry bindEntry = (BindEntry) value.clone();
+ int[] oidValue = oid.getValue();
+ int[] subOid = new int[oid.size() - entry.getKey().size()];
+ System.arraycopy(oidValue, entry.getKey().size(), subOid, 0, oid.size() - entry.getKey().size());
+ if(subOid.length > 0) {
+ bindEntry.setTableIndexOID(new OID(subOid));
+ }
+ return bindEntry;
+ }
+ }
+ return null;
+ }
+
+ public OID getNextTable(OID oid) {
+ OID currentOID = (OID) oid.clone();
+ // means that the oid is the one from the table itself
+ boolean isRowEntry = false;
+ if(tables.contains(oid)) {
+ currentOID = oid.append(1);
+ }
+// if(tableRowEntrys.contains(currentOID)) {
+// currentOID = oid.append(1);
+// isRowEntry = true;
+// }
+ BindEntry be = getTableBinding(currentOID, isRowEntry);
+// if(be == null) {
+// be = getTableBinding(currentOID, true);
+// isRowEntry = true;
+// }
+ if(be == null) {
+ return null; // it's not there
+ }
+ Object val = null;
+ try {
+ val = server.getAttribute(be.getMbean(), be.getAttr().getName());
+ } catch(Exception e) {
+ log.error("Impossible to fetch " + be.getAttr().getName());
+ return null;
+ }
+ OID tableIndexOID = be.getTableIndexOID();
+ if(tableIndexOID == null) {
+ if(val instanceof Map) {
+ Set<Object> keySet = new TreeSet(((Map)val).keySet());
+ if(keySet.size() > 0) {
+ return new OID(currentOID.append("'" + keySet.iterator().next().toString() + "'"));
+ } else {
+ return null;
+ }
+ } else {
+ return new OID(currentOID).append(1);
+ }
+ }
+ if(val instanceof List) {
+ int index = Integer.valueOf(tableIndexOID.toString());
+ if(index - 1 < 0) {
+ return null;
+ }
+ index++;
+ if(index <= ((List)val).size()) {
+ return new OID(currentOID.trim().append(index));
+ } else {
+// if(isRowEntry) {
+// return new OID(currentOID.trim().trim().append(2).append(1));
+// } else {
+ return null;
+// }
+ }
+ }
+ if(val instanceof Map) {
+// if(tableIndexOID.size() <= 1) {
+// int index = Integer.valueOf(tableIndexOID.toString());
+// if(index - 1 < 0) {
+// return null;
+// }
+// index++;
+// if(index <= ((Map)val).size()) {
+// return new OID(currentOID.trim().append(index));
+// } else {
+// Set<Object> keySet = ((Map)val).keySet();
+// if(keySet.size() > 0) {
+// return new OID(currentOID.trim().trim().append(2).append("'" + keySet.iterator().next().toString() + "'"));
+// } else {
+// return null;
+// }
+// }
+// } else {
+ String key = new String(tableIndexOID.toByteArray());
+ Iterator<Object> keySet = new TreeSet(((Map)val).keySet()).iterator();
+ while (keySet.hasNext()) {
+ Object entryKey = keySet.next();
+ if(entryKey.equals(key)) {
+ if(keySet.hasNext()) {
+ Object nextKey = keySet.next();
+ OID nextOID = new OID(currentOID);
+ nextOID.trim(tableIndexOID.size());
+ nextOID.append("'" + nextKey + "'");
+ return nextOID;
+ } else {
+ return null;
+ }
+ }
+ }
+ return null;
+// }
+ }
+ if (val instanceof int[]) {
+ int index = Integer.valueOf(tableIndexOID.toString());
+ if(index - 1 < 0) {
+ return null;
+ }
+ index++;
+ if(index <= ((int[])val).length) {
+ return new OID(currentOID.trim().append(index));
+ } else {
+ if(isRowEntry) {
+ return new OID(currentOID.trim().trim().append(2).append(1));
+ } else {
+ return null;
+ }
+ }
+ }
+ if (val instanceof long[]) {
+ int index = Integer.valueOf(tableIndexOID.toString());
+ if(index - 1 < 0) {
+ return null;
+ }
+ index++;
+ if(index <= ((long[])val).length) {
+ return new OID(currentOID.trim().append(index));
+ } else {
+ if(isRowEntry) {
+ return new OID(currentOID.trim().trim().append(2).append(1));
+ } else {
+ return null;
+ }
+ }
+ }
+ if (val instanceof boolean[]) {
+ int index = Integer.valueOf(tableIndexOID.toString());
+ if(index - 1 < 0) {
+ return null;
+ }
+ index++;
+ if(index <= ((boolean[])val).length) {
+ return new OID(currentOID.trim().append(index));
+ } else {
+ if(isRowEntry) {
+ return new OID(currentOID.trim().trim().append(2).append(1));
+ } else {
+ return null;
+ }
+ }
+ }
+ if (val instanceof Object[]) {
+ int index = Integer.valueOf(tableIndexOID.toString());
+ if(index - 1 < 0) {
+ return null;
+ }
+ index++;
+ if(index <= ((Object[])val).length) {
+ return new OID(currentOID.trim().append(index));
+ } else {
+ if(isRowEntry) {
+ return new OID(currentOID.trim().trim().append(2).append(1));
+ } else {
+ return null;
+ }
+ }
+ }
+ return null;
+ }
+
+ /**
+ *
+ * @param mmb
+ * @param oname
+ */
+ public void addTableMapping(ManagedBean mmb, MappedAttribute ma) {
+ String oid;
+ String oidPrefix = mmb.getOidPrefix();
+ if (oidPrefix != null) {
+ oid = oidPrefix + ma.getOid();
+ } else {
+ oid = ma.getOid();
+ }
+ OID coid = new OID(oid);
+ BindEntry be = new BindEntry(coid, mmb.getName(), ma.getName());
+ be.setReadWrite(ma.isReadWrite());
+ be.setTable(ma.isAttributeTable());
+
+ if (log.isTraceEnabled())
+ log.trace("New bind entry " + be);
+ if (tables.contains(coid)) {
+ log.info("Duplicate oid " + coid + RequestHandlerImpl.SKIP_ENTRY);
+ }
+ if (mmb == null || mmb.equals("")) {
+ log.info("Invalid mbean name for oid " + coid + RequestHandlerImpl.SKIP_ENTRY);
+ }
+ if (ma == null || ma.equals("")) {
+ log.info("Invalid attribute name " + ma + " for oid " + coid
+ + RequestHandlerImpl.SKIP_ENTRY);
+ }
+// tableRowEntrys.add(coid);
+ tables.add(coid.trim());
+// tableRowEntryMappings.put(new OID(coid).append(1), be);
+ tableMappings.put(new OID(coid), be);
+// tableMappings.put(new OID(coid.trim()), be);
+ }
+
+ public boolean belongsToTables(OID oid) {
+ for (OID attributeOID : tables) {
+ if (oid.startsWith(attributeOID)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ public void removeTableMapping(ManagedBean mmb, MappedAttribute ma) {
+
+ }
+
+ public Variable getIndexValue(OID oid) {
+ BindEntry be = getTableBinding(oid, true);
+ Object val = null;
+ if(be == null) {
+ return null;
+ }
+ try {
+ val = server.getAttribute(be.getMbean(), be.getAttr().getName());
+ } catch(Exception e) {
+ log.error("Impossible to fetch " + be.getAttr().getName());
+ return null;
+ }
+ OID tableIndexOID = be.getTableIndexOID();
+ if(val instanceof List) {
+ return new OctetString("" + oid.get(oid.size()-1));
+ }
+ if(val instanceof Map) {
+ int index = oid.get(oid.size()-1);
+ int i = 1;
+ for(Object key : ((Map) val).keySet()) {
+ if(i == index) {
+ return new OctetString((String)key);
+ }
+ i++;
+ }
+ }
+ if (val instanceof int[]) {
+ return new OctetString("" + oid.get(oid.size()-1));
+ }
+ if (val instanceof long[]) {
+ return new OctetString("" + oid.get(oid.size()-1));
+ }
+ if (val instanceof boolean[]) {
+ return new OctetString("" + oid.get(oid.size()-1));
+ }
+ if (val instanceof Object[]) {
+ return new OctetString("" + oid.get(oid.size()-1));
+ }
+ return null;
+ }
+}
Added: trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/BindEntry.java
===================================================================
--- trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/BindEntry.java (rev 0)
+++ trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/BindEntry.java 2011-08-19 14:58:49 UTC (rev 112095)
@@ -0,0 +1,205 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2011, Red Hat Middleware LLC, and individual contributors
+ * by the @authors tag. See the copyright.txt in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.jmx.adaptor.snmp.agent;
+
+import javax.management.Attribute;
+import javax.management.ObjectName;
+
+import org.snmp4j.smi.OID;
+
+/**
+ * @author jean.deruelle at gmail.com
+ *
+ */
+/**
+ * An entry containing the mapping between oid and mbean/attribute
+ *
+ * @author <a href="mailto:pilhuhn at user.sf.net>">Heiko W. Rupp</a>
+ */
+public class BindEntry implements Comparable {
+ private final OID oid;
+
+ private ObjectName mbean;
+ private Attribute attr;
+ private String mName;
+ private String aName;
+ private boolean isReadWrite = false;
+ private boolean isTable = false;
+ private OID tableIndexOID;
+
+ /**
+ * Constructs a new BindEntry
+ *
+ * @param oid
+ * The SNMP-oid, this entry will use.
+ * @param mbName
+ * The name of an MBean with attribute to query
+ * @param attrName
+ * The name of the attribute to query
+ */
+// BindEntry(final String oidString, final String mbName, final String attrName) {
+// this(new OID(oidString), mbName, attrName);
+// }
+
+ /**
+ * Constructs a new BindEntry.
+ *
+ * @param coid
+ * The SNMP-oid, this entry will use.
+ * @param mbName
+ * The name of an MBean with attribute to query
+ * @param attrName
+ * The name of the attribute to query
+ */
+ BindEntry(final OID coid, final String mbName, final String attrName) {
+ oid = coid;
+ this.mName = mbName;
+ this.aName = attrName;
+ try {
+ setMbean(new ObjectName(mbName));
+ setAttr(new Attribute(attrName, null));
+
+ } catch (Exception e) {
+// log.warn(e.toString());
+ mName = "-unset-";
+ aName = "-unset-";
+ }
+ }
+
+ /**
+ * A string representation of this BindEntry
+ */
+ public String toString() {
+ StringBuffer buf = new StringBuffer();
+ buf.append("[oid=");
+ buf.append(oid).append(", mbean=");
+ buf.append(mName).append(", attr=");
+ buf.append(aName).append(", rw=");
+ buf.append(", table=").append(isTable());
+ buf.append(isReadWrite()).append("]");
+
+ return buf.toString();
+ }
+
+ public Attribute getAttr() {
+ return attr;
+ }
+
+ public ObjectName getMbean() {
+ return mbean;
+ }
+
+ public OID getOid() {
+ return oid;
+ }
+
+ /**
+ * Compare two BindEntries. Ordering is defined at oid-level.
+ *
+ * @param other
+ * The BindEntry to compare to.
+ * @return 0 on equals, 1 if this is bigger than other
+ */
+ public int compareTo(Object other) {
+ if (other == null)
+ throw new NullPointerException("Can't compare to NULL");
+
+ if (!(other instanceof BindEntry))
+ throw new ClassCastException("Parameter is no BindEntry");
+
+ // trivial case
+ if (this.equals(other))
+ return 0;
+
+ BindEntry obe = (BindEntry) other;
+ // if (getOid().equals(obe.getOid()))
+ // return 0;
+
+ int res = oid.compareTo(obe.getOid());
+ return res;
+ }
+
+ /**
+ * @param isReadWrite the isReadWrite to set
+ */
+ public void setReadWrite(boolean isReadWrite) {
+ this.isReadWrite = isReadWrite;
+ }
+
+ /**
+ * @return the isReadWrite
+ */
+ public boolean isReadWrite() {
+ return isReadWrite;
+ }
+
+ /**
+ * @param mbean the mbean to set
+ */
+ public void setMbean(ObjectName mbean) {
+ this.mbean = mbean;
+ }
+
+ /**
+ * @param attr the attr to set
+ */
+ public void setAttr(Attribute attr) {
+ this.attr = attr;
+ }
+
+ /**
+ * @param isTable the isTable to set
+ */
+ public void setTable(boolean isTable) {
+ this.isTable = isTable;
+ }
+
+ /**
+ * @return the isTable
+ */
+ public boolean isTable() {
+ return isTable;
+ }
+
+ /**
+ * @param tableIndexOID the tableIndexOID to set
+ */
+ public void setTableIndexOID(OID tableIndexOID) {
+ this.tableIndexOID = tableIndexOID;
+ }
+
+ /**
+ * @return the tableIndexOID
+ */
+ public OID getTableIndexOID() {
+ return tableIndexOID;
+ }
+
+ protected BindEntry clone(){
+ BindEntry bindEntry = new BindEntry(oid, mName, aName);
+ bindEntry.setAttr(attr);
+ bindEntry.setMbean(mbean);
+ bindEntry.setReadWrite(isReadWrite);
+ bindEntry.setTable(isTable);
+ return bindEntry;
+ }
+}
Added: trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/EndOfMibViewException.java
===================================================================
--- trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/EndOfMibViewException.java (rev 0)
+++ trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/EndOfMibViewException.java 2011-08-19 14:58:49 UTC (rev 112095)
@@ -0,0 +1,20 @@
+package org.jboss.jmx.adaptor.snmp.agent;
+
+/** This exception is thrown when a GETNEXT or GETBULK operation
+ * attempts to get an OID that is not in the MIB
+ *
+ * @author Thomas Hauser <a href="mailto:thauser at redhat.com"></a>
+ *
+ */
+
+public class EndOfMibViewException extends Exception {
+
+ public EndOfMibViewException(){
+ super("Traversal of the tree left the subtree.");
+
+ }
+
+ public EndOfMibViewException(String m){
+ super(m);
+ }
+}
Added: trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/NoSuchInstanceException.java
===================================================================
--- trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/NoSuchInstanceException.java (rev 0)
+++ trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/NoSuchInstanceException.java 2011-08-19 14:58:49 UTC (rev 112095)
@@ -0,0 +1,20 @@
+package org.jboss.jmx.adaptor.snmp.agent;
+
+import org.snmp4j.smi.OID;
+
+/** This exception is thrown when a manager attempts to retrieve an instance of an object
+ * that does not exist.
+ *
+ * @author Thomas Hauser <a href="mailto:thauser at redhat.com"></a>
+ */
+
+public class NoSuchInstanceException extends Exception {
+
+ public NoSuchInstanceException(){
+ super("Error: Requested an Instance of an Object that does not exist.");
+ }
+
+ public NoSuchInstanceException(OID oid){
+ super("Error: The following Instance does not exist: "+oid);
+ }
+}
Added: trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/NoSuchObjectException.java
===================================================================
--- trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/NoSuchObjectException.java (rev 0)
+++ trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/NoSuchObjectException.java 2011-08-19 14:58:49 UTC (rev 112095)
@@ -0,0 +1,20 @@
+package org.jboss.jmx.adaptor.snmp.agent;
+
+import org.snmp4j.smi.OID;
+
+/** This exception is thrown when a manager attempts to retrieve information
+ * about an OID that does not exist in the attributes.xml
+ *
+ * @author Thomas Hauser <a href="mailto:thauser at redhat.com"></a>
+ */
+
+public class NoSuchObjectException extends Exception {
+
+ public NoSuchObjectException(){
+ super("Error: Requested an OID that does not exist.");
+ }
+
+ public NoSuchObjectException(OID oid){
+ super("Error: The following OID does not exist: "+oid);
+ }
+}
Added: trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/SnmpAgentRequestHandler.java
===================================================================
--- trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/SnmpAgentRequestHandler.java (rev 0)
+++ trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/SnmpAgentRequestHandler.java 2011-08-19 14:58:49 UTC (rev 112095)
@@ -0,0 +1,103 @@
+package org.jboss.jmx.adaptor.snmp.agent;
+
+import java.net.InetAddress;
+
+import org.snmp4j.PDU;
+import org.snmp4j.Snmp;
+import org.snmp4j.smi.OctetString;
+
+/**
+* <P>The SnmpAgentRequestHandler interface is implemented by an object that
+* wishs to receive callbacks when an SNMP protocol data unit
+* is received from a manager.</P>
+*
+*/
+public interface SnmpAgentRequestHandler
+{
+/**
+* <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, and
+* community string of the received PDU</P>
+*
+* @param session The SNMP session
+* @param manager The remote sender
+* @param port The remote senders port
+* @param community The community string
+* @param pdu The SNMP pdu
+*
+*/
+void snmpReceivedPdu(Snmp session,
+ InetAddress manager,
+ int port,
+ OctetString community,
+ PDU pdu);
+
+/**
+* <P>This method is defined to handle SNMP Get requests
+* that are received by the session. The request has already
+* been validated by the system. This routine will build a
+* response and pass it back to the caller.</P>
+*
+* @param pdu The SNMP pdu
+* @param getNext The agent is requesting the lexically NEXT item after each
+* item in the pdu. *** THIS IS NO LONGER REQUIRED. REMOVED.***
+*
+* @return PDU filled in with the proper response, or null if cannot process. PDU's
+* version is based on the @param pdu.
+*
+* NOTE: this might be changed to throw an exception.
+*/
+PDU snmpReceivedGet(PDU pdu);
+
+/**
+ * <P> This method handles SNMP Get Bulk requests received by the session
+ * Builds a response PDU and passes it back to the caller.
+ * </P
+ *
+ * @param pdu The SNMP pdu
+ * @return PDU filled with the proper response. This PDU is either V2c or V3.
+ * this PDU will always try to ignore errors and fill with as much info
+ * as possible.
+ */
+
+PDU snmpReceivedGetBulk(PDU pdu);
+
+/**
+* <P>This method is defined to handle SNMP Set requests
+* that are received by the session. The request has already
+* been validated by the system. This routine will build a
+* response and pass it back to the caller.</P>
+*
+* @param pdu The SNMP pdu
+*
+* @return PDU filled in with the proper response, or null if cannot process
+* NOTE: this might be changed to throw an exception.
+*/
+PDU snmpReceivedSet(PDU pdu);
+//ResponseEvent maybe
+
+///**
+//* <P>This method is invoked if an error occurs in
+//* the session. The error code that represents
+//* the failure will be passed in the second parameter,
+//* 'error'. The error codes can be found in the class
+//* SnmpAgentSession class.</P>
+//*
+//* <P>If a particular PDU is part of the error condition
+//* it will be passed in the third parameter, 'pdu'. The
+//* pdu will be of the type SnmpPduRequest or SnmpPduTrap
+//* object. The handler should use the "instanceof" operator
+//* to determine which type the object is. Also, the object
+//* may be null if the error condition is not associated
+//* with a particular PDU.</P>
+//*
+//* @param session The SNMP Session
+//* @param error The error condition value.
+//* @param ref The PDU reference, or potentially null.
+//* It may also be an exception.
+//*/
+//void SnmpAgentSessionError(Snmp session,
+// int error,
+// Object ref);
+}
\ No newline at end of file
Added: trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/SnmpRequest.java
===================================================================
--- trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/SnmpRequest.java (rev 0)
+++ trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/SnmpRequest.java 2011-08-19 14:58:49 UTC (rev 112095)
@@ -0,0 +1,110 @@
+package org.jboss.jmx.adaptor.snmp.agent;
+
+import org.jboss.logging.Logger;
+import org.snmp4j.CommandResponder;
+import org.snmp4j.CommandResponderEvent;
+import org.snmp4j.MessageException;
+import org.snmp4j.PDU;
+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 {
+
+ /** Logger object */
+ protected Logger log;
+
+ /** 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;
+ }
+
+ public RequestHandler getRequestHandler(){
+ return this.requestHandler;
+ }
+
+ @Override
+ public void processPdu(CommandResponderEvent event){
+ PDU pdu = event.getPDU();
+
+ if (pdu == null) {
+ log.warn("Null request PDU received ... skipping");
+ return;
+ }
+
+ if(log.isDebugEnabled()) {
+ log.debug("Received Snmp request of type: "+PDU.getTypeString(pdu.getType()));
+ }
+ int type = pdu.getType();
+
+ PDU response = null;
+ //switch based on pdu.getType() == ___
+ switch (type) {
+ case PDU.GET:
+ case PDU.GETNEXT:
+ response = requestHandler.snmpReceivedGet(pdu);
+ break;
+ case PDU.GETBULK:
+ response = requestHandler.snmpReceivedGetBulk(pdu);
+ break;
+ case PDU.SET:
+ response = requestHandler.snmpReceivedSet(pdu);
+ break;
+ default:
+ log.warn("Cannot process request PDU of type: " +
+ PDU.getTypeString(type) + "unsupported");
+ return;
+ }
+ if (response != null) {
+
+ //VERY IMPORTANT LINE
+ response.setRequestID(event.getPDU().getRequestID());
+ try {
+ sendResponse(event, response);
+ } catch (MessageException e) {
+ log.warn("Response may not have been sent correctly. " +
+ "An error occured snmp4j message processing: " +
+ e.getMessage());
+ }
+ }
+ }
+
+ private void sendResponse(CommandResponderEvent requestEvent, PDU response) throws MessageException{
+
+ 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;
+ }
+}
Added: trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/TableMapper.java
===================================================================
--- trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/TableMapper.java (rev 0)
+++ trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/TableMapper.java 2011-08-19 14:58:49 UTC (rev 112095)
@@ -0,0 +1,254 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2011, Red Hat Middleware LLC, and individual contributors
+ * by the @authors tag. See the copyright.txt in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.jmx.adaptor.snmp.agent;
+
+import java.util.List;
+import java.util.Map.Entry;
+import java.util.Set;
+import java.util.SortedMap;
+import java.util.SortedSet;
+import java.util.TreeMap;
+import java.util.TreeSet;
+
+import javax.management.MBeanServer;
+import javax.management.ObjectName;
+
+import org.jboss.jmx.adaptor.snmp.config.attribute.ManagedBean;
+import org.jboss.jmx.adaptor.snmp.config.attribute.MappedAttribute;
+import org.jboss.logging.Logger;
+import org.snmp4j.smi.OID;
+import org.snmp4j.smi.OctetString;
+import org.snmp4j.smi.Variable;
+
+/**
+ * @author jean.deruelle at gmail.com
+ *
+ */
+public class TableMapper {
+
+ /**
+ * keep an index of the OID from attributes.xml for mbean name defined a
+ * pattern (with a wildcard in it) and the corresponding ManagedBean. The
+ * OID will be the OID defined in the oid-prefix minus the last .X as this
+ * will be used as the entry
+ */
+ private SortedMap<OID, ManagedBean> tables = new TreeMap<OID, ManagedBean>();
+ private SortedMap<OID, BindEntry> tableBindings = new TreeMap<OID, BindEntry>();
+ private SortedMap<OID, OID> tableIndexes = new TreeMap<OID, OID>();
+ private SortedMap<OID, Variable> objectNameIndexes = new TreeMap<OID, Variable>();
+
+ private MBeanServer server;
+ private Logger log;
+
+ public TableMapper(MBeanServer server, Logger log) {
+ this.server = server;
+ this.log = log;
+ }
+
+ /**
+ *
+ * @param oid
+ * @return
+ */
+ public BindEntry getTableBinding(OID oid) {
+ return tableBindings.get(oid);
+ }
+
+ /**
+ *
+ * @param oid
+ * @return
+ */
+ public OID getNextTable(OID oid) {
+ return tableIndexes.get(oid);
+ }
+
+ /**
+ *
+ * @param oid
+ * @return
+ */
+ public Variable getObjectNameIndexValue(OID oid) {
+ return objectNameIndexes.get(oid);
+ }
+
+ /**
+ *
+ * @param mmb
+ * @param oname
+ */
+ public void addTableMapping(ManagedBean mmb, ObjectName oname) {
+ tables.put(
+ new OID(mmb.getOidPrefix().substring(0,
+ mmb.getOidPrefix().lastIndexOf("."))), mmb);
+ // get all ObjectNames of MBeans matched by the given name.
+ // they should be treated as Rows of the table defined which will have the oid
+ // oidPrefix.
+ Set<ObjectName> mbeanNames = server.queryNames(oname, null);
+ if(mbeanNames.size() > 0) {
+ createMappings(mbeanNames, mmb.getAttributes(), mmb.getOidPrefix());
+ }
+ }
+
+ /**
+ * hacked together method that iterates through a list of object names and
+ * adds metrics to the bind entry set
+ *
+ * @param mbeanNames
+ * Set of ObjectNames associated with a wildcard ObjectName
+ * @param attrs
+ * List of attributes that we want to know about for each entry
+ * in mbeanNames
+ * @param oidPrefix
+ * the oidPrefix for each of these, because Ideally we are
+ * creating a table.
+ */
+ private void createMappings(Set<ObjectName> mbeanNames,
+ List<MappedAttribute> attrs, String tableOid) {
+ boolean firstColumnIndexSet = false;
+ SortedSet<String> onameStrings = new TreeSet<String>();
+ for (ObjectName oname : mbeanNames) {
+ onameStrings.add(oname.toString());
+ }
+ String previousMBeanName = null;
+ String lastMBeanName = onameStrings.last();
+// OID rowIndexOID = null;
+// OID previousRowIndexOID = null;
+ OID firstOID = null;
+// int rowIndex = 1;
+ for (String mbeanRealName : onameStrings) {
+ String previousAttribute = null;
+ for (MappedAttribute ma : attrs) {
+ String oid = tableOid;
+ String columnOid = oid + ma.getOid();
+ String previousOid = null;
+ String fullOid = columnOid + ".'" + mbeanRealName + "'";
+ if(previousMBeanName != null) {
+ previousOid = columnOid + ".'" + previousMBeanName + "'";
+ }
+ OID coid = new OID(fullOid);
+ // adding entry for the given OID
+ addBindEntry(coid, mbeanRealName, ma.getName(), ma.isReadWrite());
+ // adding mapping between the oid and the previous oid with the same attribute in the table
+ if(previousOid != null) {
+ OID previousOID = new OID(previousOid);
+ tableIndexes.put(previousOID, coid);
+ }
+ if(firstOID == null) {
+ firstOID = coid;
+ }
+ // By issuing a GETNEXT request with the bare MIB name of one of the columns, the agent will return that entry from the first row of the table:
+ if(!firstColumnIndexSet) {
+ // adding mapping between the table oid and table entry oid and the first OID in the table
+// tableIndexes.put(new OID(oid + ".'" + ma.getName() + "'"), coid);
+ tableIndexes.put(new OID(oid + ma.getOid()), coid);
+ if(previousAttribute != null) {
+ String lastRowOID = oid + previousAttribute + ".'" + lastMBeanName + "'";
+ tableIndexes.put(new OID(lastRowOID), coid);
+ }
+ }
+ previousAttribute = ma.getOid();
+ }
+// rowIndexOID = new OID(tableOid + ".1." + rowIndex);
+// if(previousRowIndexOID == null) {
+// // adding mapping between the table oid and table entry oid and the first OID in the table
+// tableIndexes.put(new OID(tableOid), rowIndexOID);
+// tableIndexes.put(new OID(tableOid.substring(0,
+// tableOid.lastIndexOf("."))), rowIndexOID);
+// objectNameIndexes.put(rowIndexOID, new OctetString(mbeanRealName));
+// previousRowIndexOID = rowIndexOID;
+// } else {
+// tableIndexes.put(previousRowIndexOID, rowIndexOID);
+// objectNameIndexes.put(rowIndexOID, new OctetString(mbeanRealName));
+// previousRowIndexOID = rowIndexOID;
+// }
+// rowIndex++;
+ firstColumnIndexSet = true;
+ previousMBeanName = mbeanRealName;
+ }
+ tableIndexes.put(new OID(tableOid), firstOID);
+ tableIndexes.put(new OID(tableOid.substring(0,
+ tableOid.lastIndexOf("."))), firstOID);
+// if(firstOID != null && previousRowIndexOID != null) {
+// tableIndexes.put(previousRowIndexOID, firstOID);
+// }
+ }
+
+ /**
+ *
+ * @param oid
+ * The OID bound to this particular attribute
+ * @param mmb
+ * the name of the MBean server
+ * @param ma
+ * the name of the MBeam attribute the OID is concerning
+ * @param rw
+ * indicates whether this Attribute is read-write or not
+ * (readonly if false)
+ */
+ private void addBindEntry(OID coid, String mmb, String ma, boolean rw) {
+ BindEntry be = new BindEntry(coid, mmb, ma);
+ be.setReadWrite(rw);
+
+ if (log.isTraceEnabled())
+ log.trace("New bind entry " + be);
+ if (tableBindings.containsKey(coid)) {
+ log.info("Duplicate oid " + coid + RequestHandlerImpl.SKIP_ENTRY);
+ }
+ if (mmb == null || mmb.equals("")) {
+ log.info("Invalid mbean name for oid " + coid + RequestHandlerImpl.SKIP_ENTRY);
+ }
+ if (ma == null || ma.equals("")) {
+ log.info("Invalid attribute name " + ma + " for oid " + coid
+ + RequestHandlerImpl.SKIP_ENTRY);
+ }
+ tableBindings.put(coid, be);
+ }
+
+ // To be optimized to call only the app needed
+ public void checkTables(OID oid) {
+ for (Entry<OID, ManagedBean> tableEntry : tables.entrySet()) {
+ ManagedBean managedBean = tableEntry.getValue();
+ if (oid.startsWith(tableEntry.getKey()) && tableBindings.tailMap(tableEntry.getKey()).isEmpty()) {
+ ObjectName oname = null;
+ try {
+ oname = new ObjectName(managedBean.getName());
+ } catch (Exception e) {
+ }
+ // get all ObjectNames of MBeans matched by the given name.
+ // they should be treated as Rows of the table defined which will have the oid
+ // oidPrefix.
+ Set<ObjectName> mbeanNames = server.queryNames(oname, null);
+ createMappings(mbeanNames, managedBean.getAttributes(),
+ managedBean.getOidPrefix());
+ }
+ }
+ }
+
+ public boolean belongsToTable(OID oid) {
+ return tableBindings.get(oid) != null;
+ }
+
+ public void removeTableMapping(ManagedBean mmb, ObjectName oname) {
+
+ }
+}
Added: trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/VariableTypeException.java
===================================================================
--- trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/VariableTypeException.java (rev 0)
+++ trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/VariableTypeException.java 2011-08-19 14:58:49 UTC (rev 112095)
@@ -0,0 +1,22 @@
+package org.jboss.jmx.adaptor.snmp.agent;
+
+/**
+ * This exception is thrown when a client attempts to either GET a variable that
+ * is of a type not supported by our SNMP adaptor (hopefully very few types eventually),
+ * or if the client attempts to SET an attribute of type T to something of a type that is not T
+ * (ie a String to an int)
+ *
+ * @author Thomas Hauser <a href="mailto:thauser at redhat.com"></a>
+ *
+ */
+
+public class VariableTypeException extends Exception{
+
+ public VariableTypeException(){
+ super("Error: Variable type mismatch.");
+ }
+
+ public VariableTypeException(String m){
+ super(m);
+ }
+}
Added: trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/config/user/AuthenticationProtocol.java
===================================================================
--- trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/config/user/AuthenticationProtocol.java (rev 0)
+++ trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/config/user/AuthenticationProtocol.java 2011-08-19 14:58:49 UTC (rev 112095)
@@ -0,0 +1,30 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2011, Red Hat Middleware LLC, and individual contributors
+ * by the @authors tag. See the copyright.txt in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.jmx.adaptor.snmp.config.user;
+
+/**
+ * @author jean.deruelle at gmail.com
+ *
+ */
+public enum AuthenticationProtocol {
+ MD5, SHA;
+}
Added: trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/config/user/PrivacyProtocol.java
===================================================================
--- trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/config/user/PrivacyProtocol.java (rev 0)
+++ trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/config/user/PrivacyProtocol.java 2011-08-19 14:58:49 UTC (rev 112095)
@@ -0,0 +1,30 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2011, Red Hat Middleware LLC, and individual contributors
+ * by the @authors tag. See the copyright.txt in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.jmx.adaptor.snmp.config.user;
+
+/**
+ * @author jean.deruelle at gmail.com
+ *
+ */
+public enum PrivacyProtocol {
+ DES, TRIPLE_DES, AES128, AES192, AES256;
+}
Added: trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/config/user/User.java
===================================================================
--- trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/config/user/User.java (rev 0)
+++ trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/config/user/User.java 2011-08-19 14:58:49 UTC (rev 112095)
@@ -0,0 +1,198 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.jmx.adaptor.snmp.config.user;
+
+import org.snmp4j.security.AuthMD5;
+import org.snmp4j.security.AuthSHA;
+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.SecurityLevel;
+import org.snmp4j.smi.OID;
+
+/**
+ * Simple POJO class to model XML data
+ *
+ * @author <a href="mailto:jean.deruelle at gmail.com">Jean Deruelle</a>
+ *
+ */
+public class User
+{
+ // Private Data --------------------------------------------------
+
+ private String securityName;
+ private String authenticationProtocol;
+ private String authenticationPassphrase;
+ private String privacyProtocol;
+ private String privacyPassphrase;
+ private int securityLevel;
+
+ // Constructors -------------------------------------------------
+
+ /**
+ * Default CTOR
+ */
+ public User()
+ {
+ // empty
+ }
+
+ // Accessors/Modifiers -------------------------------------------
+ /**
+ * @param securityName the securityName to set
+ */
+ public void setSecurityName(String securityName) {
+ this.securityName = securityName;
+ }
+
+ /**
+ * @return the securityName
+ */
+ public String getSecurityName() {
+ return securityName;
+ }
+
+ /**
+ * @param authenticationProtocol the authenticationProtocol to set
+ */
+ public void setAuthenticationProtocol(String authenticationProtocol) {
+ this.authenticationProtocol = authenticationProtocol;
+ }
+
+ /**
+ * @return the authenticationProtocol
+ */
+ public String getAuthenticationProtocol() {
+ return authenticationProtocol;
+ }
+
+ /**
+ * @return the authenticationProtocol
+ */
+ public OID getAuthenticationProtocolID() {
+ AuthenticationProtocol authenticationProtocolID = AuthenticationProtocol.valueOf(authenticationProtocol.trim());
+ switch (authenticationProtocolID) {
+ case MD5:
+ return AuthMD5.ID;
+ case SHA:
+ return AuthSHA.ID;
+ default:
+ return null;
+ }
+ }
+
+ /**
+ * @param authenticationPassphrase the authenticationPassphrase to set
+ */
+ public void setAuthenticationPassphrase(String authenticationPassphrase) {
+ this.authenticationPassphrase = authenticationPassphrase;
+ }
+
+ /**
+ * @return the authenticationPassphrase
+ */
+ public String getAuthenticationPassphrase() {
+ return authenticationPassphrase;
+ }
+
+ /**
+ * @param privacyProtocol the privacyProtocol to set
+ */
+ public void setPrivacyProtocol(String privacyProtocol) {
+ this.privacyProtocol = privacyProtocol;
+ }
+
+ /**
+ * @return the privacyProtocol
+ */
+ public String getPrivacyProtocol() {
+ return privacyProtocol;
+ }
+
+ /**
+ * @return the authenticationProtocol
+ */
+ public OID getPrivacyProtocolID() {
+ PrivacyProtocol privacyProtocolID = PrivacyProtocol.valueOf(privacyProtocol.trim());
+ switch (privacyProtocolID) {
+ case DES:
+ return PrivDES.ID;
+ case TRIPLE_DES:
+ return Priv3DES.ID;
+ case AES128:
+ return PrivAES128.ID;
+ case AES192:
+ return PrivAES192.ID;
+ case AES256:
+ return PrivAES256.ID;
+ default:
+ return null;
+ }
+ }
+
+ /**
+ * @param privacyPassphrase the privacyPassphrase to set
+ */
+ public void setPrivacyPassphrase(String privacyPassphrase) {
+ this.privacyPassphrase = privacyPassphrase;
+ }
+
+ /**
+ * @return the privacyPassphrase
+ */
+ public String getPrivacyPassphrase() {
+ return privacyPassphrase;
+ }
+ /**
+ * Returns the given security level depending on te authentication protocol and privacy protocol chosen
+ * @return
+ */
+ public int getSecurityLevel() {
+ if(authenticationProtocol == null) {
+ return SecurityLevel.NOAUTH_NOPRIV;
+ } else if(privacyProtocol == null) {
+ return SecurityLevel.AUTH_NOPRIV;
+ } else {
+ return SecurityLevel.AUTH_PRIV;
+ }
+
+ }
+
+ // Object overrides ----------------------------------------------
+
+ public String toString()
+ {
+ StringBuffer sbuf = new StringBuffer(256);
+
+ sbuf.append('[')
+ .append("securityName=").append(securityName)
+ .append(", authenticationProtocol=").append(authenticationProtocol)
+ .append(", authenticationPassphrase=").append(authenticationPassphrase)
+ .append(", privacyProtocol=").append(privacyProtocol)
+ .append(", privacyPassphrase=").append(privacyPassphrase)
+ .append(']');
+
+ return sbuf.toString();
+ }
+}
Added: trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/generator/CmdLineParser.java
===================================================================
--- trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/generator/CmdLineParser.java (rev 0)
+++ trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/generator/CmdLineParser.java 2011-08-19 14:58:49 UTC (rev 112095)
@@ -0,0 +1,558 @@
+/* Copyright (c) 2001-2003 Steve Purcell.
+ * Copyright (c) 2002 Vidar Holen.
+ * Copyright (c) 2002 Michal Ceresna.
+ * Copyright (c) 2005 Ewan Mellor.
+ *
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met: Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer. Redistributions in
+ * binary form must reproduce the above copyright notice, this list of
+ * conditions and the following disclaimer in the documentation and/or other
+ * materials provided with the distribution. Neither the name of the copyright
+ * holder nor the names of its contributors may be used to endorse or promote
+ * products derived from this software without specific prior written
+ * permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+
+package org.jboss.jmx.adaptor.snmp.generator;
+
+import java.text.NumberFormat;
+import java.text.ParseException;
+import java.util.Hashtable;
+import java.util.Vector;
+import java.util.Enumeration;
+import java.util.Locale;
+
+/**
+ * Largely GNU-compatible command-line options parser. Has short (-v) and
+ * long-form (--verbose) option support, and also allows options with
+ * associated values (-d 2, --debug 2, --debug=2). Option processing
+ * can be explicitly terminated by the argument '--'.
+ *
+ * @author Steve Purcell
+ * @version $Revision: 1.10 $
+ * @see jargs.examples.gnu.OptionTest
+ */
+public class CmdLineParser {
+
+ /**
+ * Base class for exceptions that may be thrown when options are parsed
+ */
+ public static abstract class OptionException extends Exception {
+ OptionException(String msg) { super(msg); }
+ }
+
+ /**
+ * Thrown when the parsed command-line contains an option that is not
+ * recognised. <code>getMessage()</code> returns
+ * an error string suitable for reporting the error to the user (in
+ * English).
+ */
+ public static class UnknownOptionException extends OptionException {
+ UnknownOptionException( String optionName ) {
+ this(optionName, "Unknown option '" + optionName + "'");
+ }
+
+ UnknownOptionException( String optionName, String msg ) {
+ super(msg);
+ this.optionName = optionName;
+ }
+
+ /**
+ * @return the name of the option that was unknown (e.g. "-u")
+ */
+ public String getOptionName() { return this.optionName; }
+ private String optionName = null;
+ }
+
+ /**
+ * Thrown when the parsed commandline contains multiple concatenated
+ * short options, such as -abcd, where one is unknown.
+ * <code>getMessage()</code> returns an english human-readable error
+ * string.
+ * @author Vidar Holen
+ */
+ public static class UnknownSuboptionException
+ extends UnknownOptionException {
+ private char suboption;
+
+ UnknownSuboptionException( String option, char suboption ) {
+ super(option, "Illegal option: '"+suboption+"' in '"+option+"'");
+ this.suboption=suboption;
+ }
+ public char getSuboption() { return suboption; }
+ }
+
+ /**
+ * Thrown when the parsed commandline contains multiple concatenated
+ * short options, such as -abcd, where one or more requires a value.
+ * <code>getMessage()</code> returns an english human-readable error
+ * string.
+ * @author Vidar Holen
+ */
+ public static class NotFlagException extends UnknownOptionException {
+ private char notflag;
+
+ NotFlagException( String option, char unflaggish ) {
+ super(option, "Illegal option: '"+option+"', '"+
+ unflaggish+"' requires a value");
+ notflag=unflaggish;
+ }
+
+ /**
+ * @return the first character which wasn't a boolean (e.g 'c')
+ */
+ public char getOptionChar() { return notflag; }
+ }
+
+ /**
+ * Thrown when an illegal or missing value is given by the user for
+ * an option that takes a value. <code>getMessage()</code> returns
+ * an error string suitable for reporting the error to the user (in
+ * English).
+ */
+ public static class IllegalOptionValueException extends OptionException {
+ public IllegalOptionValueException( Option opt, String value ) {
+ super("Illegal value '" + value + "' for option " +
+ (opt.shortForm() != null ? "-" + opt.shortForm() + "/" : "") +
+ "--" + opt.longForm());
+ this.option = opt;
+ this.value = value;
+ }
+
+ /**
+ * @return the name of the option whose value was illegal (e.g. "-u")
+ */
+ public Option getOption() { return this.option; }
+
+ /**
+ * @return the illegal value
+ */
+ public String getValue() { return this.value; }
+ private Option option;
+ private String value;
+ }
+
+ /**
+ * Representation of a command-line option
+ */
+ public static abstract class Option {
+
+ protected Option( String longForm, boolean wantsValue ) {
+ this(null, longForm, wantsValue);
+ }
+
+ protected Option( char shortForm, String longForm,
+ boolean wantsValue ) {
+ this(new String(new char[]{shortForm}), longForm, wantsValue);
+ }
+
+ private Option( String shortForm, String longForm, boolean wantsValue ) {
+ if ( longForm == null )
+ throw new IllegalArgumentException("Null longForm not allowed");
+ this.shortForm = shortForm;
+ this.longForm = longForm;
+ this.wantsValue = wantsValue;
+ }
+
+ public String shortForm() { return this.shortForm; }
+
+ public String longForm() { return this.longForm; }
+
+ /**
+ * Tells whether or not this option wants a value
+ */
+ public boolean wantsValue() { return this.wantsValue; }
+
+ public final Object getValue( String arg, Locale locale )
+ throws IllegalOptionValueException {
+ if ( this.wantsValue ) {
+ if ( arg == null ) {
+ throw new IllegalOptionValueException(this, "");
+ }
+ return this.parseValue(arg, locale);
+ }
+ else {
+ return Boolean.TRUE;
+ }
+ }
+
+ /**
+ * Override to extract and convert an option value passed on the
+ * command-line
+ */
+ protected Object parseValue( String arg, Locale locale )
+ throws IllegalOptionValueException {
+ return null;
+ }
+
+ private String shortForm = null;
+ private String longForm = null;
+ private boolean wantsValue = false;
+
+ public static class BooleanOption extends Option {
+ public BooleanOption( char shortForm, String longForm ) {
+ super(shortForm, longForm, false);
+ }
+ public BooleanOption( String longForm ) {
+ super(longForm, false);
+ }
+ }
+
+ /**
+ * An option that expects an integer value
+ */
+ public static class IntegerOption extends Option {
+ public IntegerOption( char shortForm, String longForm ) {
+ super(shortForm, longForm, true);
+ }
+ public IntegerOption( String longForm ) {
+ super(longForm, true);
+ }
+ protected Object parseValue( String arg, Locale locale )
+ throws IllegalOptionValueException {
+ try {
+ return new Integer(arg);
+ }
+ catch (NumberFormatException e) {
+ throw new IllegalOptionValueException(this, arg);
+ }
+ }
+ }
+
+ /**
+ * An option that expects a long integer value
+ */
+ public static class LongOption extends Option {
+ public LongOption( char shortForm, String longForm ) {
+ super(shortForm, longForm, true);
+ }
+ public LongOption( String longForm ) {
+ super(longForm, true);
+ }
+ protected Object parseValue( String arg, Locale locale )
+ throws IllegalOptionValueException {
+ try {
+ return new Long(arg);
+ }
+ catch (NumberFormatException e) {
+ throw new IllegalOptionValueException(this, arg);
+ }
+ }
+ }
+
+ /**
+ * An option that expects a floating-point value
+ */
+ public static class DoubleOption extends Option {
+ public DoubleOption( char shortForm, String longForm ) {
+ super(shortForm, longForm, true);
+ }
+ public DoubleOption( String longForm ) {
+ super(longForm, true);
+ }
+ protected Object parseValue( String arg, Locale locale )
+ throws IllegalOptionValueException {
+ try {
+ NumberFormat format = NumberFormat.getNumberInstance(locale);
+ Number num = (Number)format.parse(arg);
+ return new Double(num.doubleValue());
+ }
+ catch (ParseException e) {
+ throw new IllegalOptionValueException(this, arg);
+ }
+ }
+ }
+
+ /**
+ * An option that expects a string value
+ */
+ public static class StringOption extends Option {
+ public StringOption( char shortForm, String longForm ) {
+ super(shortForm, longForm, true);
+ }
+ public StringOption( String longForm ) {
+ super(longForm, true);
+ }
+ protected Object parseValue( String arg, Locale locale ) {
+ return arg;
+ }
+ }
+ }
+
+ /**
+ * Add the specified Option to the list of accepted options
+ */
+ public final Option addOption( Option opt ) {
+ if ( opt.shortForm() != null )
+ this.options.put("-" + opt.shortForm(), opt);
+ this.options.put("--" + opt.longForm(), opt);
+ return opt;
+ }
+
+ /**
+ * Convenience method for adding a string option.
+ * @return the new Option
+ */
+ public final Option addStringOption( char shortForm, String longForm ) {
+ return addOption(new Option.StringOption(shortForm, longForm));
+ }
+
+ /**
+ * Convenience method for adding a string option.
+ * @return the new Option
+ */
+ public final Option addStringOption( String longForm ) {
+ return addOption(new Option.StringOption(longForm));
+ }
+
+ /**
+ * Convenience method for adding an integer option.
+ * @return the new Option
+ */
+ public final Option addIntegerOption( char shortForm, String longForm ) {
+ return addOption(new Option.IntegerOption(shortForm, longForm));
+ }
+
+ /**
+ * Convenience method for adding an integer option.
+ * @return the new Option
+ */
+ public final Option addIntegerOption( String longForm ) {
+ return addOption(new Option.IntegerOption(longForm));
+ }
+
+ /**
+ * Convenience method for adding a long integer option.
+ * @return the new Option
+ */
+ public final Option addLongOption( char shortForm, String longForm ) {
+ return addOption(new Option.LongOption(shortForm, longForm));
+ }
+
+ /**
+ * Convenience method for adding a long integer option.
+ * @return the new Option
+ */
+ public final Option addLongOption( String longForm ) {
+ return addOption(new Option.LongOption(longForm));
+ }
+
+ /**
+ * Convenience method for adding a double option.
+ * @return the new Option
+ */
+ public final Option addDoubleOption( char shortForm, String longForm ) {
+ return addOption(new Option.DoubleOption(shortForm, longForm));
+ }
+
+ /**
+ * Convenience method for adding a double option.
+ * @return the new Option
+ */
+ public final Option addDoubleOption( String longForm ) {
+ return addOption(new Option.DoubleOption(longForm));
+ }
+
+ /**
+ * Convenience method for adding a boolean option.
+ * @return the new Option
+ */
+ public final Option addBooleanOption( char shortForm, String longForm ) {
+ return addOption(new Option.BooleanOption(shortForm, longForm));
+ }
+
+ /**
+ * Convenience method for adding a boolean option.
+ * @return the new Option
+ */
+ public final Option addBooleanOption( String longForm ) {
+ return addOption(new Option.BooleanOption(longForm));
+ }
+
+ /**
+ * Equivalent to {@link #getOptionValue(Option, Object) getOptionValue(o,
+ * null)}.
+ */
+ public final Object getOptionValue( Option o ) {
+ return getOptionValue(o, null);
+ }
+
+
+ /**
+ * @return the parsed value of the given Option, or null if the
+ * option was not set
+ */
+ public final Object getOptionValue( Option o, Object def ) {
+ Vector v = (Vector)values.get(o.longForm());
+
+ if (v == null) {
+ return def;
+ }
+ else if (v.isEmpty()) {
+ return null;
+ }
+ else {
+ Object result = v.elementAt(0);
+ v.removeElementAt(0);
+ return result;
+ }
+ }
+
+
+ /**
+ * @return A Vector giving the parsed values of all the occurrences of the
+ * given Option, or an empty Vector if the option was not set.
+ */
+ public final Vector getOptionValues( Option option ) {
+ Vector result = new Vector();
+
+ while (true) {
+ Object o = getOptionValue(option, null);
+
+ if (o == null) {
+ return result;
+ }
+ else {
+ result.addElement(o);
+ }
+ }
+ }
+
+
+ /**
+ * @return the non-option arguments
+ */
+ public final String[] getRemainingArgs() {
+ return this.remainingArgs;
+ }
+
+ /**
+ * Extract the options and non-option arguments from the given
+ * list of command-line arguments. The default locale is used for
+ * parsing options whose values might be locale-specific.
+ */
+ public final void parse( String[] argv )
+ throws IllegalOptionValueException, UnknownOptionException {
+
+ // It would be best if this method only threw OptionException, but for
+ // backwards compatibility with old user code we throw the two
+ // exceptions above instead.
+
+ parse(argv, Locale.getDefault());
+ }
+
+ /**
+ * Extract the options and non-option arguments from the given
+ * list of command-line arguments. The specified locale is used for
+ * parsing options whose values might be locale-specific.
+ */
+ public final void parse( String[] argv, Locale locale )
+ throws IllegalOptionValueException, UnknownOptionException {
+
+ // It would be best if this method only threw OptionException, but for
+ // backwards compatibility with old user code we throw the two
+ // exceptions above instead.
+
+ Vector otherArgs = new Vector();
+ int position = 0;
+ this.values = new Hashtable(10);
+ while ( position < argv.length ) {
+ String curArg = argv[position];
+ if ( curArg.startsWith("-") ) {
+ if ( curArg.equals("--") ) { // end of options
+ position += 1;
+ break;
+ }
+ String valueArg = null;
+ if ( curArg.startsWith("--") ) { // handle --arg=value
+ int equalsPos = curArg.indexOf("=");
+ if ( equalsPos != -1 ) {
+ valueArg = curArg.substring(equalsPos+1);
+ curArg = curArg.substring(0,equalsPos);
+ }
+ } else if(curArg.length() > 2) { // handle -abcd
+ for(int i=1; i<curArg.length(); i++) {
+ Option opt=(Option)this.options.get
+ ("-"+curArg.charAt(i));
+ if(opt==null) throw new
+ UnknownSuboptionException(curArg,curArg.charAt(i));
+ if(opt.wantsValue()) throw new
+ NotFlagException(curArg,curArg.charAt(i));
+ addValue(opt, opt.getValue(null,locale));
+
+ }
+ position++;
+ continue;
+ }
+
+ Option opt = (Option)this.options.get(curArg);
+ if ( opt == null ) {
+ throw new UnknownOptionException(curArg);
+ }
+ Object value = null;
+ if ( opt.wantsValue() ) {
+ if ( valueArg == null ) {
+ position += 1;
+ if ( position < argv.length ) {
+ valueArg = argv[position];
+ }
+ }
+ value = opt.getValue(valueArg, locale);
+ }
+ else {
+ value = opt.getValue(null, locale);
+ }
+
+ addValue(opt, value);
+
+ position += 1;
+ }
+ else {
+ otherArgs.addElement(curArg);
+ position += 1;
+ }
+ }
+ for ( ; position < argv.length; ++position ) {
+ otherArgs.addElement(argv[position]);
+ }
+
+ this.remainingArgs = new String[otherArgs.size()];
+ otherArgs.copyInto(remainingArgs);
+ }
+
+
+ private void addValue(Option opt, Object value) {
+ String lf = opt.longForm();
+
+ Vector v = (Vector)values.get(lf);
+
+ if (v == null) {
+ v = new Vector();
+ values.put(lf, v);
+ }
+
+ v.addElement(value);
+ }
+
+
+ private String[] remainingArgs = null;
+ private Hashtable options = new Hashtable(10);
+ private Hashtable values = new Hashtable(10);
+}
\ No newline at end of file
Added: trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/generator/Generator.java
===================================================================
--- trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/generator/Generator.java (rev 0)
+++ trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/generator/Generator.java 2011-08-19 14:58:49 UTC (rev 112095)
@@ -0,0 +1,849 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.jmx.adaptor.snmp.generator;
+
+
+import java.io.*;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.Set;
+import java.util.HashMap;
+
+import org.jboss.jmx.adaptor.snmp.generator.metrics.MappedAttribute;
+import org.jboss.jmx.adaptor.snmp.generator.metrics.AttributeMappings;
+import org.jboss.jmx.adaptor.snmp.generator.metrics.ManagedBean;
+import org.jboss.jmx.adaptor.snmp.generator.metrics.Mapping;
+import org.jboss.jmx.adaptor.snmp.generator.metrics.VarBind;
+import org.jboss.jmx.adaptor.snmp.generator.exceptions.NotEnoughInformationException;
+
+import javax.management.ObjectName;
+
+
+/**
+* This class will be able to generate MIBs or XMLs, depending on the invocation by the user.
+* It will utilize mibble libraries to parse MIBs to generate xmls from them, and will use
+* objects gathered from the parsing of XMLs to generate MIBs. Types are determined by either an
+* attribute in the attributes.xml (snmp-type), or, if missing, a check on the attribute's type after
+* querying the server.
+*
+* @author <a href="mailto:tom.hauser at gmail.com>Tom Hauser</a>
+**/
+
+public class Generator {
+ private String outputResName; // the name of the output file (.mib or .xml)
+ private String moduleName; // the name of the output SNMP module
+ private ArrayList<MIBObject> miboList; // internal list of MIBObjects
+ private ArrayList<MIBNotification> mibnList;
+ private ArrayList<MIBTable> tableList;
+ private ArrayList<MappedAttribute> maList; // list of Mapped Attributes we care about
+ private ArrayList<Mapping> nmList; // list of notification mappings we care about
+ private ArrayList<VarBind> vbList;
+ private AttributeMappings mbList;
+
+ private HashMap<String, OIDDef> oidDefMap;
+
+ /**
+ * Default constructor. Nulls all around.
+ */
+
+ public Generator(){
+ this.outputResName = null;
+ this.mbList = null;
+ this.miboList = null;
+ this.maList = null;
+ }
+
+ /**
+ * Constructor for use when also parsing Notifications.xml
+ * @param outputResName the output filename
+ * @param maList list of MappedAttributes received from the parser
+ * @param mbList list of ManagedBeans, can be null if we're generating an XML from an MIB
+ * @param nmList list of notifications received from the parser
+ */
+
+ public Generator(String outputResName, String moduleName, ArrayList<MappedAttribute> maList, AttributeMappings mbList, ArrayList<Mapping> nmList){
+ this.outputResName = outputResName;
+ this.moduleName = moduleName;
+ this.mbList = mbList;
+ this.miboList = new ArrayList<MIBObject>();
+ this.maList = maList;
+ this.oidDefMap = new HashMap<String, OIDDef>();
+ this.nmList = nmList;
+ this.mibnList = new ArrayList<MIBNotification>();
+ this.tableList = new ArrayList<MIBTable>();
+ }
+
+ //mutators
+ public String getOutputResName(){
+ return this.outputResName;
+ }
+
+ public void setOutputResName(String outputResName){
+ this.outputResName = outputResName;
+ }
+
+ public ArrayList<MappedAttribute> getMaList(){
+ return this.maList;
+ }
+
+ public void setMaList(ArrayList<MappedAttribute> maList){
+ this.maList = maList;
+ }
+
+ public AttributeMappings getMbList(){
+ return this.mbList;
+ }
+
+ public void setMbList(AttributeMappings mbList){
+ this.mbList = mbList;
+ }
+
+ public HashMap<String, OIDDef> getOidDefMap(){
+ return this.oidDefMap;
+ }
+
+ public void setOidDefMap(HashMap<String, OIDDef> oidDefMap){
+ this.oidDefMap = oidDefMap;
+ }
+
+ /**
+ * Entry point method. Called by MIBGenerator class after all of the parsing is completed.
+ * Does nothing really itself.
+ */
+
+ public void writeFile(){
+ if (outputResName == null){
+ System.out.println("No output file location given. Aborting.");
+ System.exit(2);
+ }
+ try{
+
+ PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(outputResName)));
+ createEntries();
+ writeMibHeader(out);
+ writeMibImports(out);
+ writeMibObjectDefinitions(out);
+ writeEntries(out);
+ out.print("END");
+ out.close();
+ }
+ catch (Exception e){e.printStackTrace();}
+ }
+
+ /**
+ * Simple method that writes the header to the MIB file.
+ * TODO: make the name JBOSS-AS-MIB configurable.
+ * @param out the PrintWriter to output to.
+ */
+
+ private void writeMibHeader(PrintWriter out){
+ out.println("-- This MIB Generated by the JBoss MIB Generator");
+ out.println();
+ out.println(this.moduleName+" DEFINITIONS ::=BEGIN");
+ out.println();
+ // maybe add more here, if not we don't need this to be a seperate method.
+ }
+
+ /**
+ * Another simple method that outputs the Imports of the generated MIB.
+ * The current imports will be recognized by any standard snmp tool (notably net-snmp)
+ * TODO: Make these imports configurable.
+ * @param out
+ */
+
+ private void writeMibImports(PrintWriter out){
+ out.println("IMPORTS");
+ out.println("\tOBJECT-TYPE,");
+ out.println("\tNOTIFICATION-TYPE,");
+ out.println("\tCounter32,");
+ out.println("\tGauge32,");
+ out.println("\tCounter64,");
+ out.println("\tTimeTicks");
+ out.println("\t\tFROM SNMPv2-SMI");
+ out.println("\tDisplayString,");
+ out.println("\tTruthValue");
+ out.println("\t\tFROM SNMPv2-TC;");
+ out.println();
+ }
+
+ /**
+ * This method outputs all of the Object OID definitions we need in order for a manager
+ * that loads the generated MIB to be able to know the names of metrics it is getting back.
+ * TODO: enable exact configuration of this section
+ * @param out The PrintWriter that writes to the file we need it to
+ * @author <a href="mailto:tom.hauser at gmail.com>Tom Hauser</a>
+ */
+ private void writeMibObjectDefinitions(PrintWriter out){
+ Set<String> oidKeySet = oidDefMap.keySet();
+ Iterator<String> oidIt = oidKeySet.iterator();
+ while (oidIt.hasNext()){
+ out.println(oidDefMap.get(oidIt.next()));
+ }
+ out.println();
+ }
+
+ /**
+ * Outputs all of the objects to the output file
+ * @param out
+ */
+
+ private void writeEntries(PrintWriter out){
+ for (MIBObject mibo : miboList){
+ out.println(mibo);
+ }
+ for (MIBNotification noti : mibnList){
+ out.println(noti);
+ }
+ for (MIBTable table : tableList){
+ out.println(table);
+ }
+ }
+
+
+
+ /**
+ * This method generates an appropriate MIBObject from a given MappedAttribute, and adds
+ * it to this instance's list of mibObjects for writing to the file.
+ */
+
+ private void createEntries(){
+ if (maList != null){
+ for (MappedAttribute ma : maList){
+ try{
+ if (ma.isAttributeTable())
+ tableList.add(new MIBTable(ma));
+ else{
+ MIBObject mibo = new MIBObject(ma);
+ miboList.add(mibo);
+ }
+ }
+ catch (NotEnoughInformationException e){
+ e.printStackTrace();
+ System.err.println(e.getMessage());
+ System.exit(1);
+ }
+ }
+ }
+ else {
+ maList = new ArrayList<MappedAttribute>(0);
+ System.out.println("Attribute parsing was skipped. No attribute MIB definitions written.");
+ }
+ if (mbList != null){
+ for(ManagedBean mb : mbList){
+ // we only want to make a table if the MBean's name is a wildcard.
+ ObjectName test = null;
+ try{
+ test = new ObjectName(mb.getName());
+ }
+ catch(Exception e){
+ e.printStackTrace();
+ System.exit(1);
+ }
+ if (test != null && test.isPattern()){
+ try{
+ MIBTable mibT = new MIBTable(mb);
+ tableList.add(mibT);
+ }
+ catch (NotEnoughInformationException e){
+ e.printStackTrace();
+ System.err.println(e.getMessage());
+ System.exit(1);
+ }
+ }
+ }
+ }
+ else {
+ mbList = new AttributeMappings();
+ System.out.println("Attribute parsing was skipped. No list of MBeans is available.");
+ }
+ if (nmList != null){
+ for(Mapping nm : nmList){
+ try{
+ MIBNotification mibN = new MIBNotification(nm);
+ mibnList.add(mibN);
+ }
+ catch (NotEnoughInformationException e){
+ e.printStackTrace();
+ System.err.println(e.getMessage());
+ System.exit(1);
+ }
+ }
+ }
+ else {
+ nmList = new ArrayList<Mapping>(0);
+ System.out.println("Notification parsing was skipped. No notification MIB definitions written.");
+ }
+ }
+
+ /* Internal Classes ----- */
+
+
+ /**
+ * Internal class used to represent a single MIB Object. Created by reading the required
+ * data from a MappedAttribute object, and filling in the rest.
+ */
+ private class MIBObject extends MIBEntity{
+ private String fullOid;
+ private boolean rowEntry; //internally used to avoid adding an OIDDef for a member of an entry
+
+ MIBObject(String name, VarBind vb) throws NotEnoughInformationException {
+ super();
+ this.name = name;
+ this.syntax = (vb.getType()!=null) ? vb.getType() : "DisplayString";
+ this.maxAccess = "not-accessible";
+ this.status = "current";
+ this.description = (vb.getDesc()!=null) ? vb.getDesc() : "";
+ this.fullOid = vb.getOid();
+ String[] temp = fullOid.split("\\.");
+ this.objectId = temp[temp.length-1];
+ String oidPrefix="";
+ for (int i = 0; i<temp.length-1;i++){
+ if(i==temp.length-2)
+ oidPrefix+=temp[i];
+ else
+ oidPrefix+=temp[i]+".";
+ }
+ setOidDef(oidPrefix, null);
+
+
+ }
+
+ MIBObject(MappedAttribute ma) throws NotEnoughInformationException{
+ this(ma, false);
+ }
+
+ MIBObject(MappedAttribute ma, boolean rowEntry) throws NotEnoughInformationException{
+ // names must begin with lowercase, or the manager complains / gives warnings
+ this.name = ma.getName().substring(0,1).toLowerCase() + ma.getName().substring(1);
+
+ this.rowEntry = rowEntry; // default value with this constructor.
+ //if the ma has an snmpType defined, we use that as the type. Otherwise we cannot know it, use
+ //the general OCTET STRING type.
+ this.syntax = (ma.getSnmpType()!=null) ? ma.getSnmpType() : "OCTET STRING (SIZE(0..255))";
+
+ //there are more values possible here for an MIB, but not for a JMX attr; we only
+ //need to worry about these possibilities
+ this.maxAccess = ma.getMaxAccess();
+
+ if (this.maxAccess == null){
+ if (ma.isReadWrite())
+ maxAccess = "read-write";
+ else
+ maxAccess = "read-only";
+ }
+
+ this.status = (ma.getStatus()!=null) ? ma.getStatus() : "current";
+
+ // perhaps have this as an optional attribute in the attributes.xml? Left as blank
+ // because there is no way to query the server about a given attribute
+ this.description = (ma.getSnmpDesc()!= null) ? ma.getSnmpDesc() : "";
+
+ String[] temp = ma.getOid().split("\\."); // this will contain the full numerical OID.
+ // We need the last element in the array to be the registered OID, so we can put the correct
+ // name in the output MIB
+ this.objectId = temp[temp.length-1];
+ this.fullOid = ma.getOidPrefix()+"."+this.objectId;
+ // check if there is already an OID definition for this prefix. If there is make this MIBObject's
+ // oidDef reflect that
+ if (this.rowEntry)
+ this.oidDef = ma.getOidDefName();
+ else
+ setOidDef(ma.getOidPrefix(), ma.getOidDefName());
+ }
+
+ public String getName(){
+ return this.name;
+ }
+
+ public String getFullOid(){
+ return this.fullOid;
+ }
+
+ public boolean equals(Object o){
+ return super.equals(o);
+ }
+
+ @Override
+ public String toString(){
+ StringBuffer buf = new StringBuffer();
+ buf.append(this.name+" OBJECT-TYPE\n");
+ buf.append("\tSYNTAX ").append(this.syntax);
+ buf.append("\n");
+ buf.append("\tACCESS ").append(this.maxAccess);
+ buf.append("\n");
+ buf.append("\tSTATUS ").append(this.status);
+ buf.append("\n");
+ buf.append("\tDESCRIPTION ");
+ buf.append("\n\t\t");
+ buf.append("\""+this.description+"\"");
+ buf.append("\n");
+ buf.append("::= {").append(" ");
+ buf.append(this.oidDef + " " + this.objectId + " }");
+ buf.append("\n");
+ return buf.toString();
+ }
+ }
+
+ /**
+ * Internal class for generating an MIB Notification from a notification mapping parsed from the notification.xml
+ * @author <a href="mailto:tom.hauser at gmail.com>Tom Hauser
+ */
+
+ private class MIBNotification extends MIBEntity{
+ private ArrayList<String> objects;
+
+ public MIBNotification(Mapping mp) throws NotEnoughInformationException {
+ this.objects = new ArrayList<String>();
+
+ this.name = mp.getName();
+ if (this.name==null){
+ throw new NotEnoughInformationException("The notification "+mp.getNotificationType()+" has no valid name for the MIB.");
+ }
+ this.status = (mp.getStatus()!=null) ? mp.getStatus() : "current";
+ this.description = (mp.getDesc()!=null) ? mp.getDesc() : "";
+ ArrayList<VarBind> vbList = (ArrayList<VarBind>)mp.getVarBindList().getVarBindList();
+ setObjects(vbList);
+ // the OID of a v2 trap = <enterpriseid>.0.<specificid>
+ // for predefined traps, see RFC1907 / 3413 / 3418 / http://www.oid-info.com/get/1.3.6.1.6.3.13
+ String oidPrefix = mp.getEnterprise()+"."+String.valueOf(mp.getGeneric());
+ this.objectId = String.valueOf(mp.getSpecific());
+ // check if there is already an OID definition for this prefix. If there is make this MIBObject's
+ // oidDef reflect that
+ setOidDef(oidPrefix, mp.getOidDef());
+
+ }
+
+ public void setObjects(ArrayList<VarBind> vbList) throws NotEnoughInformationException{
+ // there are special conditions in this section that we need to account for, and
+ // define more MIBObjects. They are all of the n:tags and u:tags
+ // more changes need to be done
+ Iterator<VarBind>vbIt = vbList.iterator();
+ ArrayList<String> oids = new ArrayList<String>(10);
+ while(vbIt.hasNext()){
+ VarBind vb = vbIt.next();
+ oids.add(vb.getOid());
+ if (vb.getTag().matches("^n:.*") || vb.getTag().matches("^u:.*")){
+ createNotifPayloadMibo(vb);
+ }
+ }
+ // have all the oids. compare these to the MIBObject's full OID. if it fails,
+ // put OID into the Objects ArrayList.
+ int index = 0;
+ Iterator<String> oidIt = oids.iterator();
+
+ nextOid: while (oidIt.hasNext()){
+ String oidString = oidIt.next();
+ for(index=0; index<miboList.size();index++){
+ if (oidString.equals(miboList.get(index).getFullOid())){
+ this.objects.add(miboList.get(index).getName());
+ continue nextOid;
+ }
+ }
+ // if we get here; there is no matching MIBObject for this oid. put UNKNOWNOBJECT here instead.
+ //this.objects.add("UNKNOWNOBJECT");
+ throw new NotEnoughInformationException("The notification "+this.name+" contains an OID that does not exist in the MIB.");
+ }
+ }
+
+ //if we found a tag that matches n:.*, we create a new MIBObject so that this object
+ //is included in the mib.
+
+ public void createNotifPayloadMibo(VarBind vb) throws NotEnoughInformationException{
+ String[] tag = vb.getTag().split(":");
+ //hacky. maybe a cleaner way to do this later?
+ String name = "jbossJmxNotification"+tag[tag.length-1].substring(0,1).toUpperCase()+tag[tag.length-1].substring(1);
+ // maybe better way to glean it
+ miboList.add(new MIBObject(name,vb));
+ }
+
+ public String printObjects(){
+ StringBuffer buf = new StringBuffer();
+ buf.append("{\n");
+ for( int index = 0; index < this.objects.size(); index++){
+ if (index == this.objects.size()-1)
+ buf.append("\t\t"+this.objects.get(index));
+ else
+ buf.append("\t\t"+this.objects.get(index)).append(",\n");
+ }
+
+ buf.append("\n\t\t}\n");
+ return buf.toString();
+
+ }
+
+ @Override
+ public String toString(){
+ StringBuffer buf = new StringBuffer();
+ buf.append(this.name+" NOTIFICATION-TYPE\n");
+ buf.append("\tOBJECTS ").append(printObjects());
+ buf.append("\tSTATUS ").append(this.status);
+ buf.append("\n");
+ buf.append("\tDESCRIPTION ");
+ buf.append("\n\t\t");
+ buf.append("\""+this.description+"\"");
+ buf.append("\n");
+ buf.append("::= { ");
+ buf.append(this.oidDef + " " + this.objectId + " }");
+ buf.append("\n");
+ return buf.toString();
+ }
+ }
+
+ /**
+ * Internal class for keeping track of an OID Definition (used at the top of an MIB for naming purposes)
+ * see http://www.simpleweb.org/ietf/mibs/modules/IETF/txt/SNMPv2-SMI
+ * @author thauser
+ *
+ */
+ private class OIDDef{
+ private String name; // the name of the OID definition
+ private String definition; // the OID with '.' replaced by ' ', ready to be output into the MIB
+ private String rawOid; // the full dotted-string oid, untouched.
+
+ public OIDDef(String name, String oid){
+ this.name = name;
+ setRawOid(oid);
+ setDefinition();
+ }
+
+ //mutators
+ public String getName(){
+ return this.name;
+ }
+
+ public void setDefinition(){
+ String temp = "{ ";
+ temp += this.rawOid;
+ temp += "}";
+ this.definition = temp;
+ }
+
+ public void setRawOid(String oid){
+ String [] tokens = oid.split("\\.");
+ this.rawOid = replaceDottedOid(tokens).trim()+ " ";
+ }
+
+ private String replaceDottedOid(String [] tokens){
+ String temp = "";
+ for (int i = 0; i < tokens.length; i++){
+ temp+=tokens[i].trim()+" ";
+ }
+ return temp;
+ }
+
+ @Override
+ public String toString(){
+ StringBuffer buf = new StringBuffer();
+ buf.append(this.name);
+ buf.append("\t\tOBJECT IDENTIFIER ::= ");
+ buf.append(this.definition);
+ return buf.toString();
+ }
+
+ @Override
+ public boolean equals(Object o){
+ if (this == o){
+ return true;
+ }
+
+ if (o == null){
+ return false;
+ }
+
+ OIDDef that = (OIDDef) o;
+
+ return (this.rawOid == that.rawOid);
+ }
+ }//end OIDDef
+
+
+ /** Internal class representing a Table entry in the MIB **/
+ private class MIBTable extends MIBEntity{
+ private String tablePrefix;
+ private String rowName;
+ private MIBTableRow row; // the row created from information contained in
+ // this MIBTable
+ //creating a table out of an attribute
+ public MIBTable(MappedAttribute ma) throws NotEnoughInformationException {
+ this.tablePrefix=ma.getName().substring(0,1).toLowerCase() + ma.getName().substring(1);
+ this.name = this.tablePrefix+"Table";
+ this.maxAccess = "not-accessible";
+
+ this.description = (ma.getSnmpDesc()!=null) ? ma.getSnmpDesc() : "";
+ this.rowName = this.tablePrefix+"Entry";
+ this.syntax = this.rowName.substring(0,1).toUpperCase() + this.rowName.substring(1);
+ this.status = (ma.getStatus()!=null) ? ma.getStatus() : "current";
+ setOidDef(ma.getOidPrefix(), ma.getOidDefName());
+ String [] temp = ma.getOid().split("\\.");
+ // TODO: make this more elegant.
+
+ // HACKS::
+ if (temp.length == 3){ // .x.y, .x == TableOid, .y = RowOid
+ this.objectId = temp[1];
+ row = new MIBTableRow(this.name, this.tablePrefix, this.rowName, temp[2], ma.getMode());
+ }
+ else{
+ this.objectId = temp[temp.length-1];
+ row = new MIBTableRow(this.name, this.tablePrefix, this.rowName, "1", ma.getMode());
+ }
+
+ }
+
+
+ // if we find a managedbean with a wildcard object name, we make a table
+ public MIBTable(ManagedBean mb) throws NotEnoughInformationException{
+ this.tablePrefix = mb.getTableName();
+ if (this.tablePrefix == null){
+ throw new NotEnoughInformationException("The mbean "+mb.getName()+" has no table-name attribute defined. MIB Generation failed.");
+ }
+ this.name = this.tablePrefix+"Table";
+ this.maxAccess = "not-accessible";
+ String oid = mb.getOidPrefix();
+ if (oid == null){
+ throw new NotEnoughInformationException("The mbean "+mb.getName()+" has no oid-prefix attribute defined. MIB Generation failed.");
+ }
+ String oidPrefix = "";
+ String [] temp = oid.split("\\.");
+ this.objectId = temp[temp.length-2];
+ for (int i = 0; i < temp.length-2; i++){
+ if (i==temp.length-3)
+ oidPrefix += temp[i];
+ else if (temp[i].equals("."))
+ continue;
+ else
+ oidPrefix += temp[i]+".";
+ }
+ this.description = (mb.getDesc()!=null) ? mb.getDesc() : "";
+ this.rowName = this.tablePrefix+"Entry";
+ this.syntax = this.rowName.substring(0,1).toUpperCase() + this.rowName.substring(1);
+ this.status = (mb.getStatus()!=null) ? mb.getStatus() : "current";
+ setOidDef(oidPrefix, mb.getOidDefinition());
+ row = new MIBTableRow(this.name, this.tablePrefix, this.rowName, temp[temp.length-1], (ArrayList<MappedAttribute>)mb.getAttributes());
+ }
+
+ @Override
+ public String toString(){
+ StringBuffer buf = new StringBuffer();
+ buf.append(this.name).append(" OBJECT-TYPE").append("\n")
+ .append("\tSYNTAX\tSEQUENCE OF ").append(this.syntax).append("\n")
+ .append("\tMAX-ACCESS\t").append(this.maxAccess).append("\n")
+ .append("\tSTATUS\t").append(this.status).append("\n")
+ .append("\tDESCRIPTION\n\t\t").append("\""+this.description+"\"").append("\n")
+ .append("::= { ").append(this.oidDef+" " +this.objectId+" }\n\n")
+ .append(row);
+ return buf.toString();
+ }
+
+ }
+
+ /**Internal class representing a Table Row entry in the MIB **/
+
+ private class MIBTableRow extends MIBEntity{
+ private ArrayList<MIBObject> rowObjects;
+ private String tableName;
+ private String tablePrefix;
+ private String typeName;
+ private String indexName;
+
+ //build from a table=true attribute index and contents are generic.
+ MIBTableRow(String tableName, String tablePrefix, String rowName, String rowOid, String mode) throws NotEnoughInformationException{
+ this.tableName = tableName;
+ this.tablePrefix = tablePrefix;
+ this.name = rowName;
+ this.objectId = rowOid;
+ this.typeName = this.name.substring(0,1).toUpperCase() + this.name.substring(1);
+ this.syntax = rowName;
+ this.maxAccess="not-accessible";
+ this.status = "current";
+ this.description = "";
+ this.rowObjects = new ArrayList<MIBObject>(1);
+ MappedAttribute index = new MappedAttribute();
+ index.setSnmpType("DisplayString");
+ index.setName("index");
+ index.setOid(".1");
+ index.setMode("ro");
+ index.setOidDefName(this.name);
+ index.setMaxAccess("not-accessible");
+ index.setStatus("current");
+ rowObjects.add(new MIBObject(index,true));
+ this.indexName = "index";
+ MappedAttribute element = new MappedAttribute();
+ element.setSnmpType("DisplayString");
+ element.setName("element");
+ element.setOid(".2");
+ element.setMode(mode);
+ element.setOidDefName(this.name);
+ if (element.isReadWrite())
+ element.setMaxAccess("read-write");
+
+ else
+ element.setMaxAccess("read-only");
+ element.setStatus("current");
+ rowObjects.add(new MIBObject(element,true));
+ }
+
+ // build from ManagedBean, so we have an attrlist.
+ MIBTableRow(String tableName, String tablePrefix, String rowName, String rowOid, ArrayList<MappedAttribute> attrList) throws NotEnoughInformationException{
+ this.tableName = tableName;
+ this.tablePrefix = tablePrefix;
+ this.name = rowName;
+ this.objectId = rowOid;
+ this.typeName = this.name.substring(0,1).toUpperCase() + this.name.substring(1);
+ this.syntax = rowName;
+ this.maxAccess = "not-accessible";
+ this.status = "current"; // doesn't make sense to define a table that is not current
+ this.description = "";
+ this.indexName = this.tablePrefix+"ObjectName";
+ setRowObjects(attrList);
+ }
+
+ private void setRowObjects(ArrayList<MappedAttribute> attrList) throws NotEnoughInformationException{
+ this.rowObjects = new ArrayList<MIBObject>(1);
+ // check if there's an invalid OID in the attrList, ie: one defined with a .1 oid
+ for (MappedAttribute ma: attrList){
+ if (ma.getOid().equals(".1")){
+ System.out.println("The attribute '"+ma.getName()+"' has an OID of 1. This value is reserved for the index in a table. MIB Generation failed.");
+ System.exit(1);
+ }
+ }
+ MappedAttribute objectName = new MappedAttribute();
+ objectName.setSnmpType("DisplayString");
+ objectName.setName(this.tablePrefix+"ObjectName");
+ objectName.setOid(".1");
+ objectName.setMode("ro");
+ objectName.setOidDefName(this.name);
+ objectName.setMaxAccess("not-accessible");
+ objectName.setStatus("current");
+ rowObjects.add(new MIBObject(objectName, true));
+ for (MappedAttribute ma : attrList){
+ ma.setOidDefName(this.name);
+ ma.setName(this.tablePrefix+ma.getName().substring(0,1).toUpperCase() + ma.getName().substring(1));
+ rowObjects.add(new MIBObject(ma,true));
+ }
+ }
+
+ private String writeRowDefinition(){
+ StringBuffer buf = new StringBuffer();
+ buf.append(this.typeName + " ::= SEQUENCE {\n");
+ for (int i = 0; i < rowObjects.size(); i++){
+ if(i == rowObjects.size()-1)
+ buf.append("\t"+rowObjects.get(i).getName()+"\t"+rowObjects.get(i).getSyntax());
+ else
+ buf.append("\t"+rowObjects.get(i).getName()+"\t"+rowObjects.get(i).getSyntax()+",\n");
+ }
+ buf.append("\n}\n");
+ return buf.toString();
+ }
+
+ @Override
+ public String toString(){
+ StringBuffer buf = new StringBuffer();
+ buf.append(this.name) .append(" OBJECT-TYPE") .append("\n")
+ .append("\tSYNTAX\t") .append(this.typeName) .append("\n")
+ .append("\tMAX-ACCESS\t") .append(this.maxAccess) .append("\n")
+ .append("\tSTATUS\t") .append(this.status) .append("\n")
+ .append("\tDESCRIPTION\n\t\t").append("\""+this.description+"\"\n")
+ .append("\n\t\t").append("INDEX\t{\n\t\tIMPLIED "+this.indexName+"\n\t\t}\n")
+ .append("::= { ").append(this.tableName).append(" "+this.objectId)
+ .append(" }\n\n");
+ buf.append(writeRowDefinition()+"\n");
+ // print the rest of the objects
+ for (MIBObject object : rowObjects){
+ buf.append(object).append("\n");
+ }
+ return buf.toString();
+ }
+ }
+
+ /** Abstract class containing all the different common fields of an entry in the MIB **/
+ private abstract class MIBEntity{
+ String name;
+ String syntax;
+ String maxAccess;
+ String status;
+ String description;
+ String oidDef;
+ String objectId;
+
+ MIBEntity(){
+ name="";
+ syntax="";
+ maxAccess="";
+ status="";
+ description="";
+ oidDef="";
+ objectId="";
+ }
+
+ public String getSyntax(){
+ return this.syntax;
+ }
+
+ public abstract String toString();
+
+ public void setOidDef(String oidPrefix, String oidDefName) throws NotEnoughInformationException{
+ if (oidDefMap.containsKey(oidPrefix)){
+ this.oidDef = oidDefMap.get(oidPrefix).getName();
+ }
+ else{
+ if (oidDefName != null){
+ // the name to be used is in the attributes.xml. use it.
+ OIDDef newOidDef = new OIDDef(oidDefName, oidPrefix);
+ oidDefMap.put(oidPrefix, newOidDef);
+ this.oidDef=oidDefName;
+ }
+ else { // everything failed. the attributes.xml doesn't specify a name for the oid definition to be used,
+ // nor do we already know about it.
+ throw new NotEnoughInformationException("There was no definition-name for oid-prefix: "+oidPrefix);
+ }
+ }
+ }
+
+ /**
+ * Compares two MIBEntities, in order to allow us to know if there are duplicates or not, or maybe even use SortedSet.
+ * If the OIDDef and objectId are not equal, then we return false. This is because, no MIB Object can have the same OIDDef and the same objectId.
+ *
+ * @param o Object to compare to
+ * @return true if equal, false otherwise
+ */
+ @Override
+ public boolean equals(Object o){
+ if (this == o)
+ return true;
+
+ if (o == null)
+ return false;
+
+ MIBEntity test = (MIBEntity) o;
+
+ if (this.objectId != null ? !this.objectId.equals(test.objectId) : test.objectId != null)
+ return false;
+
+ if (this.oidDef != null ? !this.oidDef.equals(test.oidDef) : test.oidDef != null)
+ return false;
+
+ return true;
+
+ }
+ }
+
+}// end MIB Generator
\ No newline at end of file
Added: trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/generator/MIBGenerator.java
===================================================================
--- trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/generator/MIBGenerator.java (rev 0)
+++ trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/generator/MIBGenerator.java 2011-08-19 14:58:49 UTC (rev 112095)
@@ -0,0 +1,103 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+//package org.jboss.jmx.adaptor.snmp.generator;
+
+/**
+ * This class serves as the entry point for MIB Generation. It recieves input from the CLI,
+ * parses the xml and creates an appropriate Generator object to actually write the MIB.
+ * For now, only xml > mib conversions are supported.
+ *
+ * TODO: Add switch for MIB to XML conversions, using Mibble
+ * @author thauser
+ *
+ */
+
+package org.jboss.jmx.adaptor.snmp.generator;
+
+public class MIBGenerator {
+ /**
+ * Get the filenames from the command line. Parse the input file, whether it be an mib or an xml.
+ * Create the needed objects for either one, and create a new generator object with the information.
+ * Write the file using the generator.
+ * TODO: add checks for the input arguments
+ *
+ * @param args
+ * @author Tom Hauser
+ */
+ public static void main (String [] args){
+ CmdLineParser cmdParser = new CmdLineParser();
+ Parser parser = new Parser();
+ /*
+ * Adds the desired options to the command line parser.
+ * Options:
+ * -h , --help : display the usage information
+ * -a , --attributes : indicate the name of attributes.xml, if any
+ * -n , --notifications : indicate the name of the notification.xml file, if any.
+ * -m , --mib : indicate the desired name of the MIB file. this can be a path.
+ */
+ CmdLineParser.Option help = cmdParser.addBooleanOption('h', "help");
+ CmdLineParser.Option attributes = cmdParser.addStringOption('a', "attributes");
+ CmdLineParser.Option notifications = cmdParser.addStringOption('n', "notifications");
+ CmdLineParser.Option output = cmdParser.addStringOption('o', "output");
+ CmdLineParser.Option module = cmdParser.addStringOption('m', "module");
+
+ try {
+ cmdParser.parse(args);
+ }
+ catch (Exception e){
+ printUsageMessage();
+ System.exit(1);
+ }
+ Boolean isHelp = (Boolean)cmdParser.getOptionValue(help, Boolean.FALSE);
+ String aFile = (String)cmdParser.getOptionValue(attributes);
+ String nFile = (String)cmdParser.getOptionValue(notifications);
+ String oFile = (String)cmdParser.getOptionValue(output);
+ String moduleName = (String)cmdParser.getOptionValue(module);
+
+ if (moduleName == null){
+ moduleName = "JBOSS-AS-MIB";
+ }
+
+ if (isHelp){
+ printUsageMessage();
+ System.exit(0);
+ }
+
+ parser = new Parser(aFile, nFile);
+ parser.parse();
+ Generator generator = new Generator(oFile, moduleName, parser.getMaList(), parser.getMbList(), parser.getNmList());
+ generator.writeFile();
+ }
+
+
+ private static void printUsageMessage(){
+ System.out.println("Usage: java -jar mib-generator.jar [FLAG][FILENAME] .. [FLAG][FILENAME] .. [FLAG][FILENAME]\n" +
+ "[FLAG]s:\n-h , --help : display the usage information\n" +
+ "-a , --attributes : indicate the name of the snmp-adaptor formatted attributes.xml, if any.\n" +
+ "-n , --notifications : indicate the name of the snmp-adaptor formatted notification.xml file, if any.\n" +
+ "-o , --output : indicate the desired name of the output MIB file. This can be a path.\n" +
+ "-m , --module : indicate the desired name of the output MIB module. This is the name that the SNMP manager will know the MIB by. \n" +
+ " Defaults to JBOSS-AS-MIB if not specified\n"+
+ "Example: java -jar mib-generator.jar -a attributes.xml -n notifications.xml -m /home/user/TEST-MIB.mib");
+ }
+
+}
\ No newline at end of file
Added: trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/generator/Parser.java
===================================================================
--- trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/generator/Parser.java (rev 0)
+++ trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/generator/Parser.java 2011-08-19 14:58:49 UTC (rev 112095)
@@ -0,0 +1,301 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.jmx.adaptor.snmp.generator;
+
+import java.io.*;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+
+import javax.management.ObjectName;
+
+
+
+import org.jboss.jmx.adaptor.snmp.generator.metrics.MappedAttribute;
+import org.jboss.jmx.adaptor.snmp.generator.metrics.AttributeMappings;
+import org.jboss.jmx.adaptor.snmp.generator.metrics.ManagedBean;
+import org.jboss.jmx.adaptor.snmp.generator.metrics.Mapping;
+
+import org.jboss.xb.binding.ObjectModelFactory;
+import org.jboss.xb.binding.Unmarshaller;
+import org.jboss.xb.binding.UnmarshallerFactory;
+
+/**
+ * This class is used by the MIBGenerator to get the initial list of MappedAttributes out of an input file.
+ *
+ * TODO: allow for the parser to have a list of files and implement an object that can hold all needed data for the generator
+ * inside it for each file. This will allow the generator to amalgate attribute definitions from deployed webapps once that
+ * feature has been implemented.
+ *
+ * @author<a href="mailto:tom.hauser at gmail.com"> or <a href="mailto:thauser at redhat.com">Tom Hauser
+ *
+ */
+
+public class Parser {
+ String inputAttrFile;
+ String inputNotificationFile;
+ ArrayList<MappedAttribute> maList;
+ ArrayList<Mapping> nmList;//list of notifications that we care about.
+ AttributeMappings mbList;
+
+ public Parser(){}
+
+ public Parser(String inputAttrFile, String inputNotificationFile){
+ this.inputAttrFile = inputAttrFile;
+ this.inputNotificationFile = inputNotificationFile;
+ this.maList = new ArrayList<MappedAttribute>(1);
+ this.mbList = new AttributeMappings();
+ this.nmList = new ArrayList<Mapping>(1);
+ }
+
+ public String getNotiFile(){
+ return this.inputNotificationFile;
+ }
+
+ public void setNotiFile(String inputNotiFile){
+ this.inputNotificationFile = inputNotiFile;
+ }
+
+ public String getAttrFile(){
+ return this.inputAttrFile;
+ }
+
+ public void setAttrFile(String inputAttrFile){
+ this.inputAttrFile = inputAttrFile;
+ }
+
+ public ArrayList<MappedAttribute> getMaList(){
+ return this.maList;
+ }
+
+ public void setMaList(ArrayList<MappedAttribute> maList){
+ this.maList = maList;
+ }
+
+ public AttributeMappings getMbList(){
+ return this.mbList;
+ }
+
+ public void setMbList(AttributeMappings mbList){
+ this.mbList = mbList;
+ }
+
+ public ArrayList<Mapping> getNmList(){
+ return this.nmList;
+ }
+
+ public void setNmList(ArrayList<Mapping> nmList){
+ this.nmList = nmList;
+ }
+
+ /**
+ *
+ * */
+
+ public void parse(){
+ // TODO: refine the checks here. they are not enough
+ try {
+ if (this.inputAttrFile != null){
+ parseAttributesXml();
+ }
+ else
+ System.out.println("Parser: No attributes file indicated, skipping.");
+
+ if (this.inputNotificationFile != null){
+ parseNotificationsXml();
+ }
+ else
+ System.out.println("Parser: No notifications file indicated, skipping;");
+ }
+ catch (Exception e){
+ e.printStackTrace();
+ System.exit(1);
+ }
+ }
+
+
+ private void parseNotificationsXml() throws Exception{
+ ObjectModelFactory omf = new ParserNotificationBindings();
+ ArrayList<Mapping> mappings = null;
+ FileInputStream is = null;
+ try{
+
+ is = new FileInputStream(this.inputNotificationFile);
+
+
+ Unmarshaller unmarshaller = UnmarshallerFactory.newInstance().newUnmarshaller();
+
+ mappings = (ArrayList)unmarshaller.unmarshal(is,omf,null);
+ }
+ catch (NoClassDefFoundError e){
+ System.err.println("Parser: The notifications file is not formatted correctly: '"+this.inputNotificationFile+"'");
+ System.exit(1);
+ }
+ catch (FileNotFoundException e){
+ System.err.println("Parser: Filename given for notifications does not exist: '"+this.inputNotificationFile+"'");
+ System.exit(1);
+ }
+ catch (Exception e){
+ throw e;
+ }
+ finally{
+ if (is!=null){
+ try{
+ is.close();
+ }
+ catch (Exception e){
+ throw e;
+ }
+ }
+ }
+ if (mappings == null){
+ return;
+ }
+
+ // mappings recieved! add them to our nmList
+ Iterator<Mapping> mIt = mappings.iterator();
+ while (mIt.hasNext()){
+ nmList.add(mIt.next());
+ }
+ }//end parseNotificationXml
+ /**
+ * All work is done here, using ObjectModelFactory. ParseBindings is used to define how the given xml is parsed,
+ * and creates a AttributeMappings object, which is then used to add all ManagedAttributes along with their associated
+ * data to the member maList.
+ *
+ * @throws Exception
+ */
+ private void parseAttributesXml() throws Exception{
+ ObjectModelFactory omf = new ParserAttributeBindings();
+ AttributeMappings mappings = null;
+ FileInputStream is = null;
+ try{
+
+ is = new FileInputStream(this.inputAttrFile);
+
+
+ // create unmarshaller
+ Unmarshaller unmarshaller = UnmarshallerFactory.newInstance().newUnmarshaller();
+
+ // let JBossXB do it's magic using the AttributeMappingsBinding
+ mappings = (AttributeMappings)unmarshaller.unmarshal(is, omf, null);
+ setMbList(mappings);
+ }
+ catch (NoClassDefFoundError e){
+ System.err.println("Parser: The attributes file is not formatted correctly: '"+this.inputAttrFile+"'");
+ System.exit(1);
+ }
+ catch (FileNotFoundException e){
+ System.err.println("Parser: Filename given for attributes.xml does not exist: '"+this.inputAttrFile+"'");
+ System.exit(1);
+ }
+ catch (Exception e){
+ throw e;
+ }
+ finally{
+ if (is != null){
+ try{
+ is.close();
+ }
+ catch (Exception e){
+ throw e;
+ }
+ }
+ }
+ if (mappings == null){
+ return;
+ }
+ /**
+ * We have the MBeans now. Put them into the bindings.
+ */
+
+ Iterator it = mappings.iterator();
+ while (it.hasNext()){
+ ManagedBean mmb = (ManagedBean)it.next();
+ String mbeanName = mmb.getName();
+ ObjectName test = null;
+ try {
+ test = new ObjectName(mbeanName);
+ } catch (Exception e) {}
+
+ if (test == null){
+ System.err.println("Parser: The mbeanName '"+mbeanName+"' could not be converted to an ObjectName. MIB generation failed.");
+ System.exit(1);
+ }
+
+ if(!test.isPattern()){
+ String oidPrefix = mmb.getOidPrefix();
+ String oidDefName = mmb.getOidDefinition();
+ List attrs = mmb.getAttributes();
+ Iterator aIt = attrs.iterator();
+ while (aIt.hasNext()){
+ Object check = aIt.next();
+
+ MappedAttribute ma = (MappedAttribute)check;
+
+ if (oidPrefix != null)
+ ma.setOidPrefix(oidPrefix);
+ else{
+ ma.setOidPrefix(removeLast(ma.getOid()));
+ ma.setOid("."+getLast(ma.getOid()));
+ }
+
+ ma.setOidDefName(oidDefName);
+
+ // for the MIB Generator
+ ma.setMbean(mmb.getName());
+ if(!maList.contains(ma)){
+ maList.add(ma);
+ }
+ else{
+ System.err.println("Parser: The attribute '"+ma.getName()+"' is defined using a duplicated OID. MIB generation failed.");
+ System.exit(1);
+ }
+ }
+ }
+ }
+ }//end parseXml
+
+ /**
+ * This method returns the last element of a dotted string representing an OID
+ */
+ private String getLast(String oid){
+ String [] split = oid.split("\\.");
+ return split[split.length-1];
+ }
+
+ /**
+ * This private method removes the last element of a dotted string like
+ * 1.3.6.1.2.1.1, and returns the rest of the string.
+ */
+ private String removeLast(String oid){
+ String [] split = oid.split("\\.");
+ String retVal = "";
+ for (int i = 0; i < split.length-1; i++){
+ if (i == split.length-2)
+ retVal+=split[i];
+ else
+ retVal+=split[i]+".";
+ }
+ return retVal;
+ }
+}// end Parser
\ No newline at end of file
Added: trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/generator/ParserAttributeBindings.java
===================================================================
--- trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/generator/ParserAttributeBindings.java (rev 0)
+++ trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/generator/ParserAttributeBindings.java 2011-08-19 14:58:49 UTC (rev 112095)
@@ -0,0 +1,128 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.jmx.adaptor.snmp.generator;
+
+import java.util.ArrayList;
+
+import org.jboss.jmx.adaptor.snmp.generator.metrics.MappedAttribute;
+import org.jboss.jmx.adaptor.snmp.generator.metrics.AttributeMappings;
+import org.jboss.jmx.adaptor.snmp.generator.metrics.ManagedBean;
+import org.jboss.xb.binding.ObjectModelFactory;
+import org.jboss.xb.binding.UnmarshallingContext;
+import org.xml.sax.Attributes;
+
+/**
+ * Parse the mapping of JMX mbean attributes to SNMP OIDs
+ *
+ * </mbean>
+ *
+ * @author <a href="mailto:tom.hauser at gmail.com>Tom Hauser</a>
+ * @version $Revision: 111505 $
+ */
+public class ParserAttributeBindings implements ObjectModelFactory
+{
+
+ public Object newRoot(Object root, UnmarshallingContext ctx,
+ String namespaceURI, String localName, Attributes attrs)
+ {
+ if (!localName.equals("attribute-mappings"))
+ {
+ throw new IllegalStateException("Unexpected root " + localName + ". Expected <attribute-mappings>");
+ }
+ return new AttributeMappings();
+ }
+
+ public Object completeRoot(Object root, UnmarshallingContext ctx, String uri, String name)
+ {
+ return root;
+ }
+
+ public void setValue(AttributeMappings mappings, UnmarshallingContext navigator,
+ String namespaceUri, String localName, String value)
+ {
+ }
+
+ public Object newChild(AttributeMappings mappings, UnmarshallingContext navigator,
+ String namespaceUri, String localName, Attributes attrs)
+ {
+ if ("mbean".equals(localName))
+ {
+ String name = attrs.getValue("name");
+ String oidPrefix = attrs.getValue("oid-prefix");
+ String oidDefinition = attrs.getValue("definition-name");
+ String tableName = attrs.getValue("table-name");
+ String desc = attrs.getValue("description");
+ String status = attrs.getValue("status");
+ ManagedBean child = new ManagedBean();
+ child.setName(name);
+ child.setOidPrefix(oidPrefix);
+ child.setOidDefinition(oidDefinition);
+ child.setTableName(tableName);
+ child.setDesc(desc);
+ child.setStatus(status);
+ return child;
+ }
+ return null;
+ }
+
+ public void addChild(AttributeMappings mappings, ManagedBean mbean,
+ UnmarshallingContext navigator, String namespaceURI, String localName)
+ {
+ mappings.addMonitoredMBean(mbean);
+ }
+
+ public Object newChild(ManagedBean mbean, UnmarshallingContext navigator,
+ String namespaceUri, String localName, Attributes attrs)
+ {
+
+ MappedAttribute attribute = null;
+ if ("attribute".equals(localName)) {
+ String name = attrs.getValue("name");
+ String oid = attrs.getValue("oid");
+ String mode = attrs.getValue("mode");
+ String snmpType = attrs.getValue("snmp-type");
+ String maxAccess = attrs.getValue("max-access");
+ String desc = attrs.getValue("description");
+ String status = attrs.getValue("status");
+ String table = attrs.getValue("table");
+ attribute = new MappedAttribute();
+ attribute.setName(name);
+ attribute.setOid(oid);
+ attribute.setMode(mode);
+ attribute.setSnmpType(snmpType);
+ attribute.setMaxAccess(maxAccess);
+ attribute.setSnmpDesc(desc);
+ attribute.setStatus(status);
+ attribute.setTable(table);
+ }
+ return attribute;
+ }
+
+ public void addChild(ManagedBean mbean, MappedAttribute attribute,
+ UnmarshallingContext navigator, String namespaceURI, String localName)
+ {
+ if (mbean.getAttributes() == null)
+ mbean.setAttributes(new ArrayList());
+
+ mbean.getAttributes().add(attribute);
+ }
+}
Added: trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/generator/ParserNotificationBindings.java
===================================================================
--- trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/generator/ParserNotificationBindings.java (rev 0)
+++ trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/generator/ParserNotificationBindings.java 2011-08-19 14:58:49 UTC (rev 112095)
@@ -0,0 +1,171 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.jmx.adaptor.snmp.generator;
+
+import java.util.ArrayList;
+
+import org.jboss.jmx.adaptor.snmp.generator.metrics.Mapping;
+import org.jboss.jmx.adaptor.snmp.generator.metrics.VarBind;
+import org.jboss.jmx.adaptor.snmp.generator.metrics.VarBindList;
+import org.jboss.xb.binding.GenericObjectModelFactory;
+import org.jboss.xb.binding.UnmarshallingContext;
+import org.xml.sax.Attributes;
+
+ public class ParserNotificationBindings implements GenericObjectModelFactory {
+ // GenericObjectModelFactory implementation ----------------------
+
+ public Object completeRoot(Object root, UnmarshallingContext ctx,
+ String uri, String name) {
+ return root;
+ }
+
+ public Object newRoot(Object root, UnmarshallingContext navigator,
+ String namespaceURI, String localName, Attributes attrs) {
+ ArrayList notifList;
+
+ if (root == null) {
+ root = notifList = new ArrayList();
+ } else {
+ notifList = (ArrayList) root;
+ }
+ return root;
+ }
+
+ public Object newChild(Object parent, UnmarshallingContext navigator,
+ String namespaceURI, String localName, Attributes attrs) {
+ Object child = null;
+
+ if ("mapping".equals(localName)) {
+ Mapping m = new Mapping();
+
+ String notificationType = attrs.getValue("notification-type");
+ String generic = attrs.getValue("generic");
+ String specific = attrs.getValue("specific");
+ String enterprise = attrs.getValue("enterprise");
+ String inform = attrs.getValue("inform");
+ String securityName = attrs.getValue("security-name");
+ String name = attrs.getValue("name");
+ String oidDef = attrs.getValue("definition-name");
+ String desc = attrs.getValue("description");
+ m.setName(name);
+ m.setOidDef(oidDef);
+ m.setNotificationType(notificationType);
+ m.setGeneric(Integer.parseInt(generic));
+ m.setSpecific(Integer.parseInt(specific));
+ m.setEnterprise(enterprise);
+ m.setInform(Boolean.parseBoolean(inform));
+ m.setSecurityName(securityName);
+ m.setDesc(desc);
+
+ child = m;
+ } else if ("var-bind-list".equals(localName)) {
+ VarBindList vblist = new VarBindList();
+ child = vblist;
+ if (attrs.getLength() > 0) {
+ for (int i = 0; i < attrs.getLength(); i++) {
+ if ("wrapper-class".equals(attrs.getLocalName(i))) {
+ vblist.setWrapperClass(attrs.getValue(i));
+ }
+ }
+ }
+ // check that wrapper-class is set
+ if (vblist.getWrapperClass() == null) {
+ throw new RuntimeException(
+ "'wrapper-class' must be set at 'var-bind-list' element");
+ }
+ } else if ("var-bind".equals(localName)) {
+ VarBind vb = new VarBind();
+ String oid = attrs.getValue("oid");
+ String tag = attrs.getValue("tag");
+ String type = attrs.getValue("type");
+ vb.setOid(oid);
+ vb.setTag(tag);
+ vb.setType(type);
+ child = vb;
+ }
+ return child;
+ }
+
+ public void addChild(Object parent, Object child,
+ UnmarshallingContext navigator, String namespaceURI,
+ String localName) {
+ if (parent instanceof ArrayList) {
+ ArrayList notifList = (ArrayList) parent;
+
+ if (child instanceof Mapping) {
+ notifList.add(child);
+ }
+ } else if (parent instanceof Mapping) {
+ Mapping m = (Mapping) parent;
+
+ if (child instanceof VarBindList) {
+ m.setVarBindList((VarBindList) child);
+ }
+ } else if (parent instanceof VarBindList) {
+ VarBindList vblist = (VarBindList) parent;
+
+ if (child instanceof VarBind) {
+ vblist.addVarBind((VarBind) child);
+ }
+ }
+ }
+
+ public void setValue(Object o, UnmarshallingContext navigator,
+ String namespaceURI, String localName, String value) {
+ if (o instanceof Mapping) {
+ Mapping m = (Mapping) o;
+
+ if ("notification-type".equals(localName)) {
+ m.setNotificationType(value);
+ } else if ("generic".equals(localName)) {
+ m.setGeneric(Integer.parseInt(value));
+ } else if ("specific".equals(localName)) {
+ m.setSpecific(Integer.parseInt(value));
+ } else if ("enterprise".equals(localName)) {
+ m.setEnterprise(value);
+ } else if ("inform".equals(localName)) {
+ m.setInform(Boolean.parseBoolean(value));
+ } else if ("security-name".equals(localName)) {
+ m.setSecurityName(value);
+ } else if ("name".equals(localName)){
+ m.setName(value);
+ } else if ("definition-name".equals(localName)){
+ m.setOidDef(value);
+ }
+
+ } else if (o instanceof VarBind) {
+ VarBind vb = (VarBind) o;
+
+ if ("tag".equals(localName)) {
+ vb.setTag(value);
+ } else if ("oid".equals(localName)) {
+ vb.setOid(value);
+ }
+ }
+ }
+
+ public Object completedRoot(Object root,
+ UnmarshallingContext navigator, String namespaceURI,
+ String localName) {
+ return root;
+ }
+ }
\ No newline at end of file
Added: trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/generator/exceptions/NotEnoughInformationException.java
===================================================================
--- trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/generator/exceptions/NotEnoughInformationException.java (rev 0)
+++ trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/generator/exceptions/NotEnoughInformationException.java 2011-08-19 14:58:49 UTC (rev 112095)
@@ -0,0 +1,18 @@
+package org.jboss.jmx.adaptor.snmp.generator.exceptions;
+/** This exception is thrown when there is not enough information inside the input files
+ * to create a complete, valid MIB.
+ *
+ * @author Thomas Hauser <a href="mailto:thauser at redhat.com"></a>
+ *
+ */
+public class NotEnoughInformationException extends Exception {
+
+ public NotEnoughInformationException(){
+ super("Incomplete information in the parsed files. MIB cannot be created.");
+ }
+
+ public NotEnoughInformationException(String m){
+ super(m);
+ }
+
+}
\ No newline at end of file
Added: trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/generator/metrics/AttributeMappings.java
===================================================================
--- trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/generator/metrics/AttributeMappings.java (rev 0)
+++ trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/generator/metrics/AttributeMappings.java 2011-08-19 14:58:49 UTC (rev 112095)
@@ -0,0 +1,37 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.jmx.adaptor.snmp.generator.metrics;
+
+import java.util.ArrayList;
+
+/**
+ * List of mbean attribute mappings to snmp oids.
+ *
+ * @author Heiko W. Rupp <pilhuhn at user.sf.net>
+ * @version $Revision: 111649 $
+ */
+public class AttributeMappings extends ArrayList<ManagedBean> {
+
+ public void addMonitoredMBean(ManagedBean mbean) {
+ add(mbean);
+ }
+}
Added: trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/generator/metrics/ManagedBean.java
===================================================================
--- trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/generator/metrics/ManagedBean.java (rev 0)
+++ trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/generator/metrics/ManagedBean.java 2011-08-19 14:58:49 UTC (rev 112095)
@@ -0,0 +1,118 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.jmx.adaptor.snmp.generator.metrics;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.xml.bind.annotation.XmlAttribute;
+import javax.xml.bind.annotation.XmlElement;
+
+/**
+ * ManagedBean holding list of MappedAttributes
+ *
+ * @author Heiko W. Rupp <pilhuhn at user.sf.net>
+ * @version $Release:$
+ */
+public class ManagedBean {
+ private String name;
+ private String oidPrefix;
+ private String oidDefinition;
+ private String tableName;
+ private String description;
+ private String status;
+ private List<MappedAttribute> attributes;
+
+ /**
+ * Default CTOR
+ * */
+ public ManagedBean() {
+ // empty
+ }
+
+ public List<MappedAttribute> getAttributes() {
+ return attributes;
+ }
+
+ public void setAttributes(List<MappedAttribute> attributes) {
+ this.attributes = attributes;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getOidPrefix() {
+ return oidPrefix;
+ }
+
+ public void setOidPrefix(String oid_prefix) {
+ this.oidPrefix = oid_prefix;
+ }
+
+ public String getOidDefinition()
+ {
+ return oidDefinition;
+ }
+
+ public void setOidDefinition(String oidDefinition)
+ {
+ this.oidDefinition = oidDefinition;
+ }
+
+ public String getTableName(){
+ return this.tableName;
+ }
+
+ public void setTableName(String tableName){
+ this.tableName = tableName;
+ }
+
+ public String getDesc(){
+ return this.description;
+ }
+
+ public void setDesc(String desc){
+ this.description = desc;
+ }
+
+ public String getStatus(){
+ return this.status;
+ }
+
+ public void setStatus(String status){
+ this.status = status;
+ }
+
+ public String toString() {
+ StringBuffer buf = new StringBuffer();
+ buf.append("[name=").append(name);
+ buf.append(", oidPrefix=").append(oidPrefix);
+ buf.append(", attributes=").append(attributes);
+ buf.append("]");
+ return buf.toString();
+ }
+}
Added: trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/generator/metrics/MappedAttribute.java
===================================================================
--- trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/generator/metrics/MappedAttribute.java (rev 0)
+++ trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/generator/metrics/MappedAttribute.java 2011-08-19 14:58:49 UTC (rev 112095)
@@ -0,0 +1,198 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.jmx.adaptor.snmp.generator.metrics;
+
+import javax.xml.bind.annotation.XmlAttribute;
+
+/**
+ * An attribute mapping, by default readonly, and a blank description
+ *
+ * @author <a href="mailto:hwr at pilhuhn.de">Heiko W. Rupp</a>
+ * @version $Revision: 111649 $
+ */
+public class MappedAttribute
+{
+ private String name;
+ private String oid;
+ private String mode;
+ private boolean isReadWrite = false;
+ private String table;
+ private boolean isAttributeTable = false;
+
+ private String mbName = ""; //the name of the mBean this MappedAttribute is associated with
+ private String snmpType = ""; //the type for the MIB we should use, if provided
+ private String oidPrefix = ""; // all of these metrics are useful in the MIB Generator
+ private String oidDefName = "";
+ private String maxAccess = "";
+ private String description = "";
+ private String status = "";
+
+ public MappedAttribute() {
+ }
+
+ /** Attribute name */
+ public String getName() {
+ return name;
+ }
+
+ @XmlAttribute(name="name")
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ /** Attribute oid */
+ public String getOid() {
+ return oid;
+ }
+
+ @XmlAttribute(name="oid")
+ public void setOid(String oid) {
+ this.oid = oid;
+ }
+
+ /** Attribute mode (ro/rw) */
+ public boolean isReadWrite() {
+ return isReadWrite;
+ }
+
+ /** Attribute mode (ro/rw) */
+ public String getMode() {
+ return mode;
+ }
+
+ @XmlAttribute(name="mode")
+ public void setMode(String mode) {
+ this.mode = mode;
+ if(mode != null && mode.equalsIgnoreCase("rw")) {
+ isReadWrite = true;
+ }
+ }
+ /** Attribute table */
+ public boolean isAttributeTable() {
+ return isAttributeTable;
+ }
+
+ /** Attribute table */
+ public String getTable() {
+ return table;
+ }
+
+ @XmlAttribute(name="table")
+ public void setTable(String table) {
+ this.table = table;
+ if(table != null && Boolean.valueOf(table)) {
+ isAttributeTable = true;
+ }
+ }
+
+ public String getMbean(){
+ return this.mbName;
+ }
+
+ @XmlAttribute(name="name")
+ public void setMbean(String mbName){
+ this.mbName = mbName;
+ }
+
+ public String getSnmpType(){
+ return this.snmpType;
+ }
+
+ public void setSnmpType(String snmpType){
+ this.snmpType=snmpType;
+ }
+
+ public String getOidPrefix(){
+ return this.oidPrefix;
+ }
+
+ public void setOidPrefix(String oidPrefix){
+ if (oidPrefix.charAt(0) == '.')
+ this.oidPrefix = oidPrefix.substring(1);
+ else
+ this.oidPrefix = oidPrefix;
+ }
+
+ public String getOidDefName(){
+ return this.oidDefName;
+ }
+
+ public void setOidDefName(String oidDefName){
+ this.oidDefName = oidDefName;
+ }
+
+ public String getMaxAccess(){
+ return this.maxAccess;
+ }
+
+ public void setMaxAccess(String maxAccess){
+ this.maxAccess = maxAccess;
+ }
+
+ public String getSnmpDesc(){
+ return this.description;
+ }
+
+ public void setSnmpDesc(String snmpDesc){
+ this.description = snmpDesc;
+ }
+
+ public String getStatus(){
+ return this.status;
+ }
+
+ public void setStatus(String status){
+ this.status = status;
+ }
+
+ public String toString() {
+ StringBuffer buf = new StringBuffer();
+ buf.append("[name=").append(name);
+ buf.append(", oid=").append(oid);
+ buf.append(", rw=").append(isReadWrite);
+ buf.append("]");
+ return buf.toString();
+ }
+
+ @Override
+ public boolean equals(Object o){
+ if (this == o)
+ return true;
+
+ if (o == null)
+ return false;
+
+ MappedAttribute that = (MappedAttribute) o;
+
+ String fullOidThis = this.oidPrefix+"."+this.oid;
+ String fullOidThat = that.oidPrefix+"."+that.oid;
+ return (fullOidThis.equals(fullOidThat));
+ }
+
+ @Override
+ public int hashCode(){
+ int result = 4;
+ int PRIME = 31;
+ String fullOid = this.oidPrefix+"."+this.oid;
+ return PRIME * result + fullOid.hashCode();
+ }
+}
Added: trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/generator/metrics/Mapping.java
===================================================================
--- trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/generator/metrics/Mapping.java (rev 0)
+++ trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/generator/metrics/Mapping.java 2011-08-19 14:58:49 UTC (rev 112095)
@@ -0,0 +1,193 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.jmx.adaptor.snmp.generator.metrics;
+
+import javax.xml.bind.annotation.XmlAttribute;
+import javax.xml.bind.annotation.XmlElement;
+
+/**
+ * Simple POJO class to model XML data
+ *
+ * @author <a href="mailto:dimitris at jboss.org">Dimitris Andreadis</a>
+ *
+ * @version $Revision: 111649 $
+ */
+public class Mapping
+{
+ // Private Data --------------------------------------------------
+
+ private String notificationType;
+ private int generic;
+ private int specific;
+ private String enterprise;
+ private boolean inform;
+ private String securityName;
+ private VarBindList varBindList;
+ private String name;
+ private String oidDefName;
+ private String description;
+ private String status;
+
+ // Constructors -------------------------------------------------
+
+ /**
+ * Default CTOR
+ */
+ public Mapping() {
+ // empty
+ }
+
+ // Accessors/Modifiers -------------------------------------------
+
+ public String getEnterprise(){
+ return enterprise;
+ }
+
+ public int getGeneric() {
+ return generic;
+ }
+
+ public String getNotificationType() {
+ return notificationType;
+ }
+
+ public int getSpecific() {
+ return specific;
+ }
+
+ public VarBindList getVarBindList() {
+ return varBindList;
+ }
+
+
+
+ @XmlAttribute(name="enterprise")
+ public void setEnterprise(String enterprise) {
+ this.enterprise = enterprise;
+ }
+
+ @XmlAttribute(name="generic")
+ public void setGeneric(int generic) {
+ this.generic = generic;
+ }
+
+ @XmlAttribute(name="notification-type")
+ public void setNotificationType(String notificationType) {
+ this.notificationType = notificationType;
+ }
+
+
+ @XmlAttribute(name="specific")
+ public void setSpecific(int specific) {
+ this.specific = specific;
+ }
+
+ @XmlElement(name="var-bind-list")
+ public void setVarBindList(VarBindList varBindList) {
+ this.varBindList = varBindList;
+ }
+
+ /**
+ * @param inform
+ * the inform to set
+ */
+ @XmlAttribute(name="inform")
+ public void setInform(boolean inform) {
+ this.inform = inform;
+ }
+
+ /**
+ * @return the inform
+ */
+ public boolean isInform() {
+ return inform;
+ }
+
+ /**
+ * @param securityName
+ * the securityName to set
+ */
+ @XmlAttribute(name="security-name")
+ public void setSecurityName(String securityName) {
+ this.securityName = securityName;
+ }
+
+ public void setOidDef(String en){
+ this.oidDefName = en;
+ }
+
+ public String getOidDef(){
+ return this.oidDefName;
+ }
+
+ /**
+ * @return the securityName
+ */
+ public String getSecurityName() {
+ return securityName;
+ }
+
+
+
+ public void setName(String name){
+ this.name = name;
+ }
+
+ public String getName(){
+ return this.name;
+ }
+
+ public void setDesc(String desc){
+ description = desc;
+ }
+
+ public String getDesc(){
+ return this.description;
+ }
+
+ public void setStatus(String status){
+ this.status = status;
+ }
+
+ public String getStatus(){
+ return this.status;
+ }
+
+ // Object overrides ----------------------------------------------
+
+ public String toString()
+ {
+ StringBuffer sbuf = new StringBuffer(256);
+
+ sbuf.append('[')
+ .append("notificationType=").append(notificationType)
+ .append(", generic=").append(generic)
+ .append(", specific=").append(specific)
+ .append(", enterprise=").append(enterprise)
+ .append(", inform=").append(inform)
+ .append(", securityName=").append(securityName)
+ .append(", varBindList=").append(varBindList)
+ .append(']');
+
+ return sbuf.toString();
+ }
+}
Added: trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/generator/metrics/VarBind.java
===================================================================
--- trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/generator/metrics/VarBind.java (rev 0)
+++ trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/generator/metrics/VarBind.java 2011-08-19 14:58:49 UTC (rev 112095)
@@ -0,0 +1,100 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.jmx.adaptor.snmp.generator.metrics;
+
+import javax.xml.bind.annotation.XmlAttribute;
+
+/**
+ * Simple POJO class to model XML data
+ *
+ * @author <a href="mailto:dimitris at jboss.org">Dimitris Andreadis</a>
+ *
+ * @version $Revision: 111649 $
+ */
+public class VarBind {
+ // Private Data --------------------------------------------------
+
+ private String tag;
+ private String oid;
+ private String type;
+ private String description;
+
+ // Constructors -------------------------------------------------
+
+ /**
+ * Default CTOR
+ */
+ public VarBind() {
+ // empty
+ }
+
+ // Accessors/Modifiers -------------------------------------------
+
+ public String getOid() {
+ return oid;
+ }
+
+ public String getTag() {
+ return tag;
+ }
+
+ @XmlAttribute(name = "oid")
+ public void setOid(String oid) {
+ this.oid = oid;
+ }
+
+ @XmlAttribute(name = "tag")
+ public void setTag(String tag) {
+ this.tag = tag;
+ }
+
+ @XmlAttribute(name = "type")
+ public void setType(String type) {
+ this.type = type;
+ }
+
+ /**
+ * @return the type
+ */
+ public String getType() {
+ return type;
+ }
+
+ public String getDesc(){
+ return this.description;
+ }
+
+ public void setDesc(String desc){
+ this.description = desc;
+ }
+ // Object overrides ----------------------------------------------
+
+ public String toString() {
+ StringBuffer sbuf = new StringBuffer(256);
+
+ sbuf.append('[').append("tag=").append(tag).append(", oid=")
+ .append(oid).append(", type=")
+ .append(type).append(']');
+
+ return sbuf.toString();
+ }
+}
Added: trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/generator/metrics/VarBindList.java
===================================================================
--- trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/generator/metrics/VarBindList.java (rev 0)
+++ trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/generator/metrics/VarBindList.java 2011-08-19 14:58:49 UTC (rev 112095)
@@ -0,0 +1,86 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.jmx.adaptor.snmp.generator.metrics;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.xml.bind.annotation.XmlAttribute;
+import javax.xml.bind.annotation.XmlElement;
+
+/**
+ * Simple POJO class to model XML data
+ *
+ * @author <a href="mailto:dimitris at jboss.org">Dimitris Andreadis</a>
+ *
+ * @version $Revision: 111649 $
+ */
+public class VarBindList {
+ // Private Data --------------------------------------------------
+
+ private String wrapperClass = "org.jboss.jmx.adaptor.snmp.agent.NotificationWrapperSupport";
+ private List<VarBind> varBindList = new ArrayList<VarBind>();
+
+ // Constructors -------------------------------------------------
+
+ /**
+ * Default CTOR
+ */
+ public VarBindList() {
+ // empty
+ }
+
+ // Accessors/Modifiers -------------------------------------------
+
+ public String getWrapperClass() {
+ return wrapperClass;
+ }
+
+ public List<VarBind> getVarBindList() {
+ return varBindList;
+ }
+
+ @XmlAttribute(name = "wrapper-class")
+ public void setWrapperClass(String wrapperClass) {
+ this.wrapperClass = wrapperClass;
+ }
+
+ @XmlElement(name = "var-bind")
+ public void setVarBindList(List<VarBind> varBindList) {
+ this.varBindList = varBindList;
+ }
+
+ public void addVarBind(VarBind child) {
+ this.varBindList.add(child);
+ }
+
+ // Object overrides ----------------------------------------------
+
+ public String toString() {
+ StringBuffer sbuf = new StringBuffer(256);
+
+ sbuf.append('[').append("wrapperClass=").append(wrapperClass)
+ .append(", varBindList=").append(varBindList).append(']');
+
+ return sbuf.toString();
+ }
+}
Added: trunk/varia/src/resources/services/snmp/config/Attributes.xsd
===================================================================
--- trunk/varia/src/resources/services/snmp/config/Attributes.xsd (rev 0)
+++ trunk/varia/src/resources/services/snmp/config/Attributes.xsd 2011-08-19 14:58:49 UTC (rev 112095)
@@ -0,0 +1,50 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ Schema used by the SnmpAgent to define the attributes we want to be monitored.
+
+ Authors
+ <a href="mailto:tom.hauser at gmail.com">Tom Hauser</a>
+-->
+<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://www.w3.org/2001/XMLSchema">
+
+<xsd:annotation>
+ <xsd:documentation xml:lang="en">
+ Schema for attributes.xml used by applications.
+ </xsd:documentation>
+</xsd:annotation>
+
+<xsd:element name="attribute-mappings">
+ <xsd:complexType>
+ <xsd:sequence>
+ <xsd:element name="mbean" maxOccurs="unbounded">
+ <xsd:complexType>
+ <xsd:sequence>
+ <xsd:element name="attribute" maxOccurs="unbounded">
+ <xsd:complexType>
+ <xsd:all/>
+ <xsd:attribute name="name"/>
+ <xsd:attribute name="oid" use="required" type="xsd:string"/>
+ <xsd:attribute name="mode" use="optional" type="xsd:string"/>
+ <xsd:attribute name="snmp-type" use="optional" type="xsd:string"/>
+ <xsd:attribute name="max-access" use="optional" type="xsd:string"/>
+ <xsd:attribute name="description" use="optional" type="xsd:string"/>
+ <xsd:attribute name="status" use="optional" type="xsd:string"/>
+ <xsd:attribute name="table" use="optional" type="xsd:string"/>
+ </xsd:complexType>
+ </xsd:element>
+ </xsd:sequence>
+ <xsd:attribute name="name" type="xsd:string" use="required"/>
+ <xsd:attribute name="oid-prefix" use="optional" type="xsd:string"/>
+ <xsd:attribute name="definition-name" use="optional" type="xsd:string"/>
+ <xsd:attribute name="table-name" use="optional" type="xsd:string"/>
+ <xsd:attribute name="description" use="optional" type="xsd:string"/>
+ <xsd:attribute name="status" use="optional" type="xsd:string"/>
+ </xsd:complexType>
+ </xsd:element>
+ </xsd:sequence>
+ </xsd:complexType>
+</xsd:element>
+
+</xsd:schema>
+
+
Added: trunk/varia/src/resources/services/snmp/config/Users.xsd
===================================================================
--- trunk/varia/src/resources/services/snmp/config/Users.xsd (rev 0)
+++ trunk/varia/src/resources/services/snmp/config/Users.xsd 2011-08-19 14:58:49 UTC (rev 112095)
@@ -0,0 +1,33 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ XML Schema used by the SnmpAgent to configure users for SNMP v3
+
+ Authors
+ <a href="mailto:jean.deruelle at gmail.com">Jean Deruelle</a>
+-->
+<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://www.w3.org/2001/XMLSchema">
+
+ <xsd:annotation>
+ <xsd:documentation xml:lang="en">
+ Schema describes the users for the SNMP v3 protocol.
+ </xsd:documentation>
+ </xsd:annotation>
+
+ <xsd:element name="user-list">
+ <xsd:complexType>
+ <xsd:sequence>
+ <xsd:element name="user" maxOccurs="unbounded">
+ <xsd:complexType>
+ <xsd:sequence>
+ <xsd:element name="securityName" type="xsd:string" />
+ <xsd:element name="authenticationProtocol" type="xsd:string" />
+ <xsd:element name="authenticationPassphrase" type="xsd:string" />
+ <xsd:element name="privacyProtocol" type="xsd:string" />
+ <xsd:element name="privacyPassphrase" type="xsd:string" />
+ </xsd:sequence>
+ </xsd:complexType>
+ </xsd:element>
+ </xsd:sequence>
+ </xsd:complexType>
+ </xsd:element>
+</xsd:schema>
\ No newline at end of file
Added: trunk/varia/src/resources/services/snmp/deploy/users.xml
===================================================================
--- trunk/varia/src/resources/services/snmp/deploy/users.xml (rev 0)
+++ trunk/varia/src/resources/services/snmp/deploy/users.xml 2011-08-19 14:58:49 UTC (rev 112095)
@@ -0,0 +1,34 @@
+<?xml version="1.0"?>
+<!--
+ This file is used to configure the SNMP users for v3 of the protocol
+
+ Each entry must specify:
+ - the security name of the user (typically the user name).
+ - the authentication Protocol : the authentication protcol to be associated with this user (MD5 or SHA). If not set, this user only supports unauthenticated messages.
+ - the authentication Passphrase : If present, the authentication Protocol must also be present. RFC3414 §11.2 requires passphrases to have a minimum length of 8 bytes.
+ If the length of <code>authenticationPassphrase</code> is less than 8 bytes an IllegalArgumentException will be thrown.
+ - the privacy Protocol : the privacy protcol ID to be associated with this user (DES, 3DES, AES128, AES192, AES256). If not set, this user only supports unencrypted messages.
+ - the privacy Passphrase : If present, the privacy Protocol must also be set. RFC3414 §11.2 requires passphrases to have a minimum length of 8 bytes.
+ If the length of <code>authenticationPassphrase</code> is less than 8 bytes an IllegalArgumentException will be thrown.
+
+ More than one user may be specified.
+-->
+<user-list>
+ <!--
+ A default user.
+ -->
+ <user>
+ <securityName>TEST</securityName>
+ <authenticationProtocol>MD5</authenticationProtocol>
+ <authenticationPassphrase>maplesyrup</authenticationPassphrase>
+ <privacyProtocol>DES</privacyProtocol>
+ <privacyPassphrase>maplesyrup</privacyPassphrase>
+ </user>
+ <user>
+ <securityName>myuser</securityName>
+ <authenticationProtocol>MD5</authenticationProtocol>
+ <authenticationPassphrase>password</authenticationPassphrase>
+ <privacyProtocol>DES</privacyProtocol>
+ <privacyPassphrase>password</privacyPassphrase>
+ </user>
+</user-list>
More information about the jboss-cvs-commits
mailing list