Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  import  lombok.extern.slf4j.Slf4j;
  import  org.snmp4j.TransportMapping;
 import  org.snmp4j.agent.*;
 import  org.snmp4j.smi.*;
 import  org.snmp4j.transport.TransportMappings;
 import  org.snmp4j.util.ThreadPool;
 import java.util.*;
This is the core class of the Snmpman. The agent simulates the SNMP-capable devices.

This class can be instantiated via the constructor SnmpmanAgent(, which requires an instance of the

 public class SnmpmanAgent extends BaseAgent {

The pattern of variable bindings in a walk file.
     private static final Pattern VARIABLE_BINDING_PATTERN = Pattern.compile("(((iso)?\\.[0-9]+)+) = ((([a-zA-Z0-9-]+): (.*)$)|(\"\"$))");

The configuration of this agent.
     private final AgentConfiguration configuration;
The list of managed object groups.
     private final List<ManagedObject> groups = new ArrayList<>(0);

Initializes a new instance of an SNMP agent.

configuration the configuration for this agent
     public SnmpmanAgent(final AgentConfiguration configuration) {
         super(SnmpmanAgent.getBootCounterFile(configuration), SnmpmanAgent.getConfigurationFile(configuration), new CommandProcessor(new OctetString(MPv3.createLocalEngineID())));
         this..setWorkerPool(ThreadPool.create("RequestPool", 3));
         this. = configuration;

Returns the name of this agent.

See for more information on the return value.

the name of this agent.
     public String getName() {
         return .getName();
Returns the boot-counter file for the specified agent.

This file will be created in the same directory as the file.

the boot-counter file
     private static File getBootCounterFile(final AgentConfiguration configuration) {
         return new File(configuration.getWalk().getParentFile(), SnmpmanAgent.encode(configuration.getName() + ".BC.cfg"));

Returns the configuration file for the specified agent.

This file will be created in the same directory as the file.

the configuration file
     private static File getConfigurationFile(final AgentConfiguration configuration) {
         return new File(configuration.getWalk().getParentFile(), SnmpmanAgent.encode(configuration.getName() + ".Config.cfg"));

Translates a string into x-www-form-urlencoded format. The method uses the UTF-8 encoding scheme.

string String to be translated
the translated String
     private static String encode(final String string) {
         try {
            return URLEncoder.encode(string"UTF-8");
        } catch (final UnsupportedEncodingException e) {
            log.error("UTF-8 encoding is unsupported");
            return string;

Returns the root OIDs of the bindings.

bindings the variable bindings
the roots of the specified variable bindings
    private static List<OID> getRoots(final SortedMap<OID, Variable> bindings) {
        final List<OID> potentialRoots = new ArrayList<>(bindings.size());
        OID last = null;
        for (final OID oid : bindings.keySet()) {
            if (last != null) {
                int min = Math.min(oid.size(), last.size());
                while (min > 0) {
                    if (oid.leftMostCompare(minlast) == 0) {
                        OID root = new OID(last.getValue(), 0, min);
            last = oid;
        final List<OID> roots = new ArrayList<>(potentialRoots.size());
        for (final OID potentialRoot : potentialRoots) {
            if (potentialRoot.size() > 0) {
                OID trimmedPotentialRoot = new OID(potentialRoot.getValue(), 0, potentialRoot.size() - 1);
                while (trimmedPotentialRoot.size() > 0 && Collections.binarySearch(potentialRootstrimmedPotentialRoot) < 0) {
                if (trimmedPotentialRoot.size() == 0 && !roots.contains(potentialRoot)) {
        log.trace("identified roots {}"roots);
        return roots;

Returns a Variable instance for the specified parameters.

type the type of the variable
value the value of this variable
a a Variable instance with the specified type and value
IllegalArgumentException if the type could not be mapped to a Variable implementation
    private static Variable getVariable(final String typefinal String value) {
        switch (type) {
            case "STRING":
                return new OctetString(value.substring(1, value.length() - 1));
            case "OID":
                return new OID(value);
            case "Gauge32":
                return new Gauge32(Long.parseLong(value));
            case "Timeticks":
                final int openBracket = value.indexOf("(") + 1;
                final int closeBracket = value.indexOf(")");
                if (openBracket < 0 || closeBracket < 0) {
                    throw new IllegalArgumentException("could not parse time tick value in " + value);
                return new TimeTicks(Long.parseLong(value.substring(openBracketcloseBracket)));
            case "Counter32":
                return new Counter32(Long.parseLong(value));
            case "Counter64":
                // Parse unsigned long
                return new Counter64(UnsignedLong.valueOf(value).longValue());
            case "INTEGER":
                return new Integer32(Integer.valueOf(value));
            case "Hex-STRING":
                return OctetString.fromHexString(value' ');
            case "IpAddress":
                return new IpAddress(value);
                throw new IllegalArgumentException("illegal type \"" + type + "\" in walk detected");

Starts this agent instance.

IOException signals that this agent could not be initialized by the init() method
    public void execute() throws IOException {
        this.getServer().addContext(new OctetString("public"));
    protected void initTransportMappings() throws IOException {
        log.trace("starting to initialize transport mappings for agent \"{}\"".getName());
        transportMappings = new TransportMapping[1];
        TransportMapping tm = TransportMappings.getInstance().createTransportMapping(.getAddress());
        transportMappings[0] = tm;
    protected void registerManagedObjects() {
        log.trace("registering managed objects for agent \"{}\"".getName());
        try (final FileReader fileReader = new FileReader(.getWalk());
             final BufferedReader reader = new BufferedReader(fileReader)) {
            final Map<OID, Variable> bindings = new HashMap<>();
            String line;
            while ((line = reader.readLine()) != null) {
                final Matcher matcher = .matcher(line);
                if (matcher.matches()) {
                    final OID oid = new OID("iso"".1"));
                    final String type;
                    final String value;
                    if ( == null) {
                        type = "STRING";
                        value = "\"\"";
                    } else {
                        type =;
                        value =;
                    final Variable variable = SnmpmanAgent.getVariable(typevalue);
                    log.trace("added binding with oid \"{}\" and variable \"{}\""oidvariable);
                } else {
                    log.warn("could not parse line \"{}\" of walk file {}"line.getWalk().getAbsolutePath());
            final SortedMap<OID, Variable> variableBindings = this.getVariableBindings(.getDevice(), bindings);
            final OctetString ctx = new OctetString();
            final List<OID> roots = SnmpmanAgent.getRoots(variableBindings);
            for (final OID root : roots) {
                final ArrayList<VariableBinding> subtree = new ArrayList<>();
                for (final Map.Entry<OID, Variable> binding : variableBindings.entrySet()) {
                    if (binding.getKey().size() >= root.size()) {
                        if (binding.getKey().leftMostCompare(root.size(), root) == 0) {
                            subtree.add(new VariableBinding(binding.getKey(), binding.getValue()));
                StaticMOGroup group = new StaticMOGroup(rootsubtree.toArray(new VariableBinding[subtree.size()]));
                DefaultMOContextScope scope = new DefaultMOContextScope(ctxroottrueroot.nextPeer(), false);
                ManagedObject mo = server.lookup(new DefaultMOQuery(scopefalse));
                if (mo != null) {
                    for (final VariableBinding variableBinding : subtree) {
                        group = new StaticMOGroup(variableBinding.getOid(), new VariableBinding[]{ variableBinding });
                        scope = new DefaultMOContextScope(ctxvariableBinding.getOid(), truevariableBinding.getOid().nextPeer(), false);
                        mo = server.lookup(new DefaultMOQuery(scopefalse));
                        if (mo != null) {
                            log.warn("could not register single OID at {} because ManagedObject {} is already registered."variableBinding.getOid(), mo);
                        } else {
                } else {
        } catch (final FileNotFoundException e) {
            log.error("walk file {} not found".getWalk().getAbsolutePath());
        } catch (final IOException e) {
            log.error("could not read walk file " + .getWalk().getAbsolutePath(), e);
        } catch (final DuplicateRegistrationException e) {
            log.error("duplicate registrations are not allowed"e);

Unregisters all default managed objects in the specified context ctx.

ctx the context from which all default managed objects should be unregistred
    private void unregisterDefaultManagedObjects(final OctetString ctx) {
        final OID startOID = new OID(".1");
        final DefaultMOContextScope hackScope = new DefaultMOContextScope(ctxstartOIDtruestartOID.nextPeer(), false);
        ManagedObject query;
        while ((query = server.lookup(new DefaultMOQuery(hackScopefalse))) != null) {

Returns the variable bindings for a device configuration and a list of bindings.

In this step the ModifiedVariable instances will be created as a wrapper for dynamic variables.

device the device configuration
bindings the bindings as the base
the variable bindings for the specified device configuration
    private SortedMap<OID, Variable> getVariableBindings(final Device devicefinal Map<OID, Variable> bindings) {
        log.trace("get variable bindings for agent \"{}\"".getName());
        final SortedMap<OID, Variable> result = new TreeMap<>();
        for (final Map.Entry<OID, Variable> binding : bindings.entrySet()) {
            final List<VariableModifiermodifiers = new ArrayList<>(0);
            modifiers.addAll(device.getModifiers().stream().filter(modifier -> modifier.isApplicable(binding.getKey())).collect(Collectors.toList()));
            if (modifiers.isEmpty()) {
                result.put(binding.getKey(), binding.getValue());
            } else {
                log.trace("created modified variable for OID {}"binding.getKey());
                try {
                    result.put(binding.getKey(), new ModifiedVariable(binding.getValue(), modifiers));
                } catch (final ClassCastException e) {
                    log.error("could not create variable binding for " + binding.getKey().toString() + " and file " + .getWalk().getAbsolutePath(), e);
        return result;
    protected void unregisterManagedObjects() {
        log.trace("unregistered managed objects for agent \"{}\"", agent);
        for (final ManagedObject mo : ) {
    protected void addUsmUser(final USM usm) {
        log.trace("adding usm user {} for agent \"{}\""usm.toString(), .getName());
        // do nothing here
    protected void addNotificationTargets(final SnmpTargetMIB snmpTargetMIBfinal SnmpNotificationMIB snmpNotificationMIB) {
        log.trace("adding notification targets {}, {} for agent \"{}\""snmpTargetMIB.toString(), snmpNotificationMIB.toString(), .getName());
        // do nothing here
    protected void addViews(final VacmMIB vacmMIB) {
        log.trace("adding views in the vacm MIB {} for agent \"{}\""vacmMIB.toString(), .getName());
        vacmMIB.addGroup(SecurityModel.SECURITY_MODEL_SNMPv1, new OctetString(.getCommunity()), new OctetString("v1v2group"), StorageType.nonVolatile);
        vacmMIB.addGroup(SecurityModel.SECURITY_MODEL_SNMPv2c, new OctetString(.getCommunity()), new OctetString("v1v2group"), StorageType.nonVolatile);
        vacmMIB.addGroup(SecurityModel.SECURITY_MODEL_USM, new OctetString("SHADES"), new OctetString("v3group"), StorageType.nonVolatile);
        vacmMIB.addGroup(SecurityModel.SECURITY_MODEL_USM, new OctetString("TEST"), new OctetString("v3test"), StorageType.nonVolatile);
        vacmMIB.addGroup(SecurityModel.SECURITY_MODEL_USM, new OctetString("SHA"), new OctetString("v3restricted"), StorageType.nonVolatile);
        vacmMIB.addGroup(SecurityModel.SECURITY_MODEL_USM, new OctetString("v3notify"), new OctetString("v3restricted"), StorageType.nonVolatile);
        vacmMIB.addAccess(new OctetString("v1v2group"), new OctetString(), SecurityModel.SECURITY_MODEL_ANY, SecurityLevel.NOAUTH_NOPRIV, MutableVACM.VACM_MATCH_EXACT, new OctetString("fullReadView"), new OctetString("fullWriteView"), new OctetString("fullNotifyView"), StorageType.nonVolatile);
        vacmMIB.addAccess(new OctetString("v3group"), new OctetString(), SecurityModel.SECURITY_MODEL_USM, SecurityLevel.AUTH_PRIV, MutableVACM.VACM_MATCH_EXACT, new OctetString("fullReadView"), new OctetString("fullWriteView"), new OctetString("fullNotifyView"), StorageType.nonVolatile);
        vacmMIB.addAccess(new OctetString("v3restricted"), new OctetString(), SecurityModel.SECURITY_MODEL_USM, SecurityLevel.NOAUTH_NOPRIV, MutableVACM.VACM_MATCH_EXACT, new OctetString("restrictedReadView"), new OctetString("restrictedWriteView"), new OctetString("restrictedNotifyView"), StorageType.nonVolatile);
        vacmMIB.addAccess(new OctetString("v3test"), new OctetString(), SecurityModel.SECURITY_MODEL_USM, SecurityLevel.AUTH_PRIV, MutableVACM.VACM_MATCH_EXACT, new OctetString("testReadView"), new OctetString("testWriteView"), new OctetString("testNotifyView"), StorageType.nonVolatile);
        vacmMIB.addViewTreeFamily(new OctetString("fullReadView"), new OID("1.3"), new OctetString(), VacmMIB.vacmViewIncluded, StorageType.nonVolatile);
        vacmMIB.addViewTreeFamily(new OctetString("fullWriteView"), new OID("1.3"), new OctetString(), VacmMIB.vacmViewIncluded, StorageType.nonVolatile);
        vacmMIB.addViewTreeFamily(new OctetString("fullNotifyView"), new OID("1.3"), new OctetString(), VacmMIB.vacmViewIncluded, StorageType.nonVolatile);
        vacmMIB.addViewTreeFamily(new OctetString("restrictedReadView"), new OID(""), new OctetString(), VacmMIB.vacmViewIncluded, StorageType.nonVolatile);
        vacmMIB.addViewTreeFamily(new OctetString("restrictedWriteView"), new OID(""), new OctetString(), VacmMIB.vacmViewIncluded, StorageType.nonVolatile);
        vacmMIB.addViewTreeFamily(new OctetString("restrictedNotifyView"), new OID(""), new OctetString(), VacmMIB.vacmViewIncluded, StorageType.nonVolatile);
        vacmMIB.addViewTreeFamily(new OctetString("restrictedNotifyView"), new OID(""), new OctetString(), VacmMIB.vacmViewIncluded, StorageType.nonVolatile);
        vacmMIB.addViewTreeFamily(new OctetString("testReadView"), new OID(""), new OctetString(), VacmMIB.vacmViewIncluded, StorageType.nonVolatile);
        vacmMIB.addViewTreeFamily(new OctetString("testReadView"), new OID(""), new OctetString(), VacmMIB.vacmViewExcluded, StorageType.nonVolatile);
        vacmMIB.addViewTreeFamily(new OctetString("testWriteView"), new OID(""), new OctetString(), VacmMIB.vacmViewIncluded, StorageType.nonVolatile);
        vacmMIB.addViewTreeFamily(new OctetString("testNotifyView"), new OID(""), new OctetString(), VacmMIB.vacmViewIncluded, StorageType.nonVolatile);
    protected void addCommunities(final SnmpCommunityMIB snmpCommunityMIB) {
        log.trace("adding communities {} for agent \"{}\""snmpCommunityMIB.toString(), .getName());
        final Variable[] com2sec = new Variable[]{
                new OctetString(.getCommunity()),                 // community name
                new OctetString(.getCommunity()),                 // security name
                getAgent().getContextEngineID(),                               // local engine ID
                new OctetString(),                                             // default context name
                new OctetString(),                                             // transport tag
                new Integer32(StorageType.readOnly),                           // storage type
                new Integer32(                                // row status
        final SnmpCommunityMIB.SnmpCommunityEntryRow row = snmpCommunityMIB.getSnmpCommunityEntry().createRow(new OctetString("public2public").toSubIndex(true), com2sec);
New to GrepCode? Check out our FAQ X