org.snmp4j.smi.OID Java Examples

The following examples show how to use org.snmp4j.smi.OID. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SNMPClient.java    From mysql_perf_analyzer with Apache License 2.0 8 votes vote down vote up
public List<SNMPTriple> querySingleSNMPTableByOID(String oid) throws IOException
{
 if(oid == null || oid.isEmpty())return null;
 if(!oid.startsWith("."))oid = "."+oid;
    TableUtils tUtils = new TableUtils(snmp, new DefaultPDUFactory());
    List<TableEvent> events = tUtils.getTable(getTarget(), new OID[]{new OID(oid)}, null, null);

 List<SNMPTriple> snmpList = new ArrayList<SNMPTriple>();
    
    for (TableEvent event : events) {
      if(event.isError()) {
     	 logger.warning(this.address + ": SNMP event error: "+event.getErrorMessage());
     	 continue;
           //throw new RuntimeException(event.getErrorMessage());
      }
      for(VariableBinding vb: event.getColumns()) {
   	   String key = vb.getOid().toString();
   	   String value = vb.getVariable().toString();
   	 snmpList.add(new SNMPTriple(key, "", value));
      }
    }
 return snmpList;
}
 
Example #2
Source File: SnmpmanTest.java    From snmpman with Apache License 2.0 6 votes vote down vote up
@Test
public void testWithCommunityIndex() throws Exception {
    assertEquals(snmpman.getAgents().size(), 11);

    final String oid = "1.3.6.1.2.1.17.2.4";
    List<TableEvent> responses1 = getResponse(new OID(oid), PORT, "public@42");
    assertEquals(responses1.size(), 1);
    assertTrue(containsColumn(responses1, oid, "150"));

    List<TableEvent> responses2 = getResponse(new OID(oid), PORT, "public@9");
    assertEquals(responses2.size(), 1);
    assertTrue(containsColumn(responses2, oid, "120"));

    List<TableEvent> responses3 = getResponse(new OID(oid), PORT, COMMUNITY);
    assertEquals(responses3.size(), 1);
    assertTrue(containsColumn(responses3, oid, "0"));
}
 
Example #3
Source File: SNMPClient.java    From mysql_perf_analyzer with Apache License 2.0 6 votes vote down vote up
/**
 * This method is capable of handling multiple OIDs
 * @param oids
 * @return
 * @throws IOException
 */
public Map<OID, String> get(OID oids[]) throws IOException 
{
	PDU pdu = createPDU();
	for (OID oid : oids) {
		pdu.add(new VariableBinding(oid));
	}
	pdu.setType(PDU.GET);
	ResponseEvent event = snmp.send(pdu, getTarget(), null);
	if(event != null) {
		PDU pdu2 = event.getResponse();
		VariableBinding[] binds = pdu2!=null?event.getResponse().toArray():null;
		if(binds!=null)
		{
			Map<OID, String> res = new LinkedHashMap<OID, String>(binds.length);
			for(VariableBinding b: binds)
				res.put(b.getOid(), b.getVariable().toString());
			return res;
		}else return null;
	}
	throw new RuntimeException("GET timed out");
}
 
Example #4
Source File: SnmpmanTest.java    From snmpman with Apache License 2.0 6 votes vote down vote up
@Test
public void testSnmpGetBulk() throws Exception {
    assertEquals(snmpman.getAgents().size(), 11);

    List<TableEvent> responses = getResponse(new OID("1.3.6.1.2.1"), 10000);
    assertEquals(responses.size(), 19);

    responses = getResponse(new OID("1.3.6.1.2.1.31"), 10000);
    assertEquals(responses.size(), 10);

    responses = getResponse(new OID(".1.3.6.1.2.1.2"), 10000);
    assertEquals(responses.size(), 7);

    responses = getResponse(new OID(".1.3"), 10010);
    assertEquals(responses.size(), 30);

    responses = getResponse(new OID(".1.0"), 10010);
    assertEquals(responses.size(), 8);
}
 
Example #5
Source File: SNMPClient.java    From mysql_perf_analyzer with Apache License 2.0 6 votes vote down vote up
/**
 * 
 * @return
 * @throws IOException
 */
public List<SNMPTriple> querySysData3() throws IOException 
{
	logger.fine("Query snmp system data for "+address);
	List<SNMPTriple> snmpList = new ArrayList<SNMPTriple>();
	 Map<OID, String> res = get(COMMON_SYS_OIDS);
	 if(res!=null)
	 {
		 for(Map.Entry<OID, String> e: res.entrySet())
		 {
			 if("noSuchObject".equalsIgnoreCase(e.getValue()))continue;
			 snmpList.add(new SNMPTriple(e.getKey().toString(), OID_NAME_MAP.get("."+e.getKey().toString()), e.getValue()));
		 }
	 }
	 return snmpList;
}
 
Example #6
Source File: SNMPClient.java    From mysql_perf_analyzer with Apache License 2.0 6 votes vote down vote up
/**
 * Retrieve common system SNMP data
 * @return
 * @throws IOException
 */
public Map<String, String> querySysData() throws IOException 
{
	logger.fine("Query snmp for "+address);
	Map<String, String> resMap = null;
	 resMap = new java.util.LinkedHashMap<String, String>();
	 Map<OID, String> res = get(COMMON_SYS_OIDS);
	 if(res!=null)
	 {
		 for(Map.Entry<OID, String> e: res.entrySet())
		 {
			 if("noSuchObject".equalsIgnoreCase(e.getValue()))continue;
			 resMap.put(OID_NAME_MAP.get("."+e.getKey().toString()), e.getValue());
		 }
	 }
	 return resMap;
}
 
Example #7
Source File: PolatisOpticalUtility.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Transforms a flow FlowRule object to a variable binding.
 * @param rule FlowRule object
 * @param delete whether it is a delete or edit request
 * @return variable binding
 */
public static VariableBinding fromFlowRule(FlowRule rule, boolean delete) {
    Set<Criterion> criterions = rule.selector().criteria();
    PortNumber inPort = criterions.stream()
            .filter(c -> c instanceof PortCriterion)
            .map(c -> ((PortCriterion) c).port())
            .findAny()
            .orElse(null);
    long input = inPort.toLong();
    List<Instruction> instructions = rule.treatment().immediate();
    PortNumber outPort = instructions.stream()
            .filter(c -> c instanceof Instructions.OutputInstruction)
            .map(c -> ((Instructions.OutputInstruction) c).port())
            .findAny()
            .orElse(null);
    long output = outPort.toLong();
    OID oid = new OID(PORT_PATCH_OID + "." + input);
    Variable var = new UnsignedInteger32(delete ? 0 : output);
    return new VariableBinding(oid, var);
}
 
Example #8
Source File: SNMPClient.java    From mysql_perf_analyzer with Apache License 2.0 6 votes vote down vote up
private Target getTargetV3() {
	//logger.info("Use SNMP v3, "+this.privacyprotocol +"="+this.password+", "+this.privacyprotocol+"="+this.privacypassphrase);
	OID authOID = AuthMD5.ID;
	if("SHA".equals(this.authprotocol))
		authOID = AuthSHA.ID;
	OID privOID = PrivDES.ID;
	if(this.privacyprotocol == null || this.privacyprotocol.isEmpty())
		privOID = null;
	UsmUser user = new UsmUser(new OctetString(this.username),  
			authOID, new OctetString(this.password),  //auth
			privOID, this.privacypassphrase!=null?new OctetString(this.privacypassphrase):null); //enc
	snmp.getUSM().addUser(new OctetString(this.username), user);  
	Address targetAddress = GenericAddress.parse(address);
	UserTarget target = new UserTarget();
	target.setAddress(targetAddress);
	target.setRetries(2);
	target.setTimeout(1500);
	target.setVersion(this.getVersionInt());
	if(privOID != null)
		target.setSecurityLevel(SecurityLevel.AUTH_PRIV);  
	else
		target.setSecurityLevel(SecurityLevel.AUTH_NOPRIV); 
	target.setSecurityName(new OctetString(this.username));
	return target;
}
 
Example #9
Source File: SNMPHelper.java    From OpenFalcon-SuitAgent with Apache License 2.0 6 votes vote down vote up
private static boolean checkWalkFinished(OID targetOID, PDU pdu, VariableBinding vb) {
    boolean finished = false;
    if (pdu.getErrorStatus() != 0) {
        finished = true;
    } else if (vb.getOid() == null) {
        finished = true;
    } else if (vb.getOid().size() < targetOID.size()) {
        finished = true;
    } else if (targetOID.leftMostCompare(targetOID.size(), vb.getOid()) != 0) {
        finished = true;
    } else if (Null.isExceptionSyntax(vb.getVariable().getSyntax())) {
        finished = true;
    } else if (vb.getOid().compareTo(targetOID) <= 0) {
        finished = true;
    }
    return finished;

}
 
Example #10
Source File: PolatisPowerConfig.java    From onos with Apache License 2.0 6 votes vote down vote up
private boolean setPortTargetPower(PortNumber port, long power) {
    log.debug("Set port{} target power...", port);
    List<VariableBinding> vbs = new ArrayList<>();

    OID voaStateOid = new OID(VOA_STATE_OID + "." + port.toLong());
    Variable voaStateVar = new UnsignedInteger32(VOA_STATE_ABSOLUTE);
    VariableBinding voaStateVb = new VariableBinding(voaStateOid, voaStateVar);
    vbs.add(voaStateVb);

    OID voaLevelOid = new OID(VOA_LEVEL_OID + "." + port.toLong());
    Variable voaLevelVar = new UnsignedInteger32(power);
    VariableBinding voaLevelVb = new VariableBinding(voaLevelOid, voaLevelVar);
    vbs.add(voaLevelVb);

    DeviceId deviceId = handler().data().deviceId();
    try {
        set(handler(), vbs);
    } catch (IOException e) {
        log.error("Error writing ports table for device {} exception {}", deviceId, e);
        return false;
    }
    return true;
}
 
Example #11
Source File: ModifierPropertiesTest.java    From snmpman with Apache License 2.0 6 votes vote down vote up
@Test
public void testParsing() throws Exception {
    final AgentConfiguration.DeviceFactory deviceFactory = new AgentConfiguration.DeviceFactory();
    final Device device = deviceFactory.getDevice(new File("src/test/resources/configuration/cisco.yaml"));

    assertFalse(device.getModifiers().isEmpty());

    boolean counter64found = false;
    for (final Modifier modifier : device.getModifiers()) {
        // counter64
        if (modifier.isApplicable(new OID(".1.3.6.1.2.1.31.1.1.1.11.1"))) {
            final Field variableModifierField = Modifier.class.getDeclaredField("modifier");
            variableModifierField.setAccessible(true);

            final Counter64Modifier counter64Modifier = (Counter64Modifier) variableModifierField.get(modifier);
            assertEquals(counter64Modifier.getMaximum(), UnsignedLong.valueOf(new BigInteger("1844674407370955161")));
            counter64found = true;
        }
    }
    
    if (!counter64found) {
        fail("no modifier for unsigned long found");
    }
}
 
Example #12
Source File: SNMPUtils.java    From nifi with Apache License 2.0 6 votes vote down vote up
/**
 * Method to return the private protocol given the property
 * @param privProtocol property
 * @return protocol
 */
public static OID getPriv(String privProtocol) {
    switch (privProtocol) {
    case "DES":
        return PrivDES.ID;
    case "3DES":
        return Priv3DES.ID;
    case "AES128":
        return PrivAES128.ID;
    case "AES192":
        return PrivAES192.ID;
    case "AES256":
        return PrivAES256.ID;
    default:
        return null;
    }
}
 
Example #13
Source File: SNMPHelper.java    From SuitAgent with Apache License 2.0 6 votes vote down vote up
private static boolean checkWalkFinished(OID targetOID, PDU pdu, VariableBinding vb) {
    boolean finished = false;
    if (pdu.getErrorStatus() != 0) {
        finished = true;
    } else if (vb.getOid() == null) {
        finished = true;
    } else if (vb.getOid().size() < targetOID.size()) {
        finished = true;
    } else if (targetOID.leftMostCompare(targetOID.size(), vb.getOid()) != 0) {
        finished = true;
    } else if (Null.isExceptionSyntax(vb.getVariable().getSyntax())) {
        finished = true;
    } else if (vb.getOid().compareTo(targetOID) <= 0) {
        finished = true;
    }
    return finished;

}
 
Example #14
Source File: LumentumSdnRoadmFlowRuleProgrammable.java    From onos with Apache License 2.0 6 votes vote down vote up
private PortNumber getAddDropPort(int channel, boolean isAddPort) {
    OID oid = new OID(CTRL_CHANNEL_ADD_DROP_PORT_INDEX + (isAddPort ? "1" : "2"));

    for (TreeEvent event : snmp.get(oid)) {
        if (event == null) {
            return null;
        }

        VariableBinding[] varBindings = event.getVariableBindings();

        for (VariableBinding varBinding : varBindings) {
            if (varBinding.getOid().last() == channel) {
                int port = varBinding.getVariable().toInt();
                if (!isAddPort) {
                    port += DROP_PORT_OFFSET;
                }
                return PortNumber.portNumber(port);

            }
        }

    }

    return null;
}
 
Example #15
Source File: SNMPClient.java    From mysql_perf_analyzer with Apache License 2.0 6 votes vote down vote up
/**
 * For test SNMP purpose. Used to check if individual SNMP entry is supported
 * @param oid
 * @return
 * @throws IOException 
 */
public List<SNMPTriple> querySingleSNMPEntryByOID(String oid) throws IOException
{
 if(oid == null || oid.isEmpty())return null;
 if(!oid.startsWith("."))oid = "."+oid;
 List<SNMPTriple> snmpList = new ArrayList<SNMPTriple>();
Map<OID, String> res = get(new OID[]{new OID(oid)});
if(res!=null)
{
 for(Map.Entry<OID, String> e: res.entrySet())
 {
	 //if("noSuchObject".equalsIgnoreCase(e.getValue()))continue;
	 snmpList.add(new SNMPTriple(e.getKey().toString(), "", e.getValue()));
 }
}
return snmpList;
}
 
Example #16
Source File: WildcardOID.java    From snmpman with Apache License 2.0 6 votes vote down vote up
/**
 * Constructs a new instance of this class.
 *
 * @param oid the {@code OID} that potentially contains a wildcard
 * @throws NullPointerException     if the specified {@code OID} is null
 * @throws IllegalArgumentException if the specified {@code OID} contains more than one wildcard character
 */
public WildcardOID(final String oid) {
    Preconditions.checkNotNull(oid, "oid may not be null");

    final Matcher matcher = WILDCARD_OID_PATTERN.matcher(oid);
    if (matcher.matches()) {
        this.startsWith = new OID(matcher.group(1));
        if (matcher.group(5).isEmpty()) {
            this.endsWith = null;
        } else {
            this.endsWith = new OID(matcher.group(5));
        }
    } else {
        throw new IllegalArgumentException("specified oid \"" + oid + "\" is not a valid wildcard");
    }
}
 
Example #17
Source File: SNMPUtils.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
/**
 * Method to return the private protocol given the property
 * @param privProtocol property
 * @return protocol
 */
public static OID getPriv(String privProtocol) {
    switch (privProtocol) {
    case "DES":
        return PrivDES.ID;
    case "3DES":
        return Priv3DES.ID;
    case "AES128":
        return PrivAES128.ID;
    case "AES192":
        return PrivAES192.ID;
    case "AES256":
        return PrivAES256.ID;
    default:
        return null;
    }
}
 
Example #18
Source File: MOGroup.java    From snmpman with Apache License 2.0 5 votes vote down vote up
@Override
public void get(final SubRequest request) {
    final OID oid = request.getVariableBinding().getOid();
    final Variable variable = variableBindings.get(oid);
    if (variable == null) {
        request.getVariableBinding().setVariable(Null.noSuchInstance);
    } else {
        request.getVariableBinding().setVariable((Variable) variable.clone());
    }
    request.completed();
}
 
Example #19
Source File: MOGroup.java    From snmpman with Apache License 2.0 5 votes vote down vote up
/**
 * If the prepare method doesn't set {@link org.snmp4j.agent.request.RequestStatus RequestStatus} to
 * {@link  org.snmp4j.mp.SnmpConstants#SNMP_ERROR_SUCCESS SNMP_ERROR_SUCCESS} the new values are written.
 * Otherwise the commit fails and forces an undo operation.
 *
 * @param request The SubRequest to handle.
 */
@Override
public void commit(final SubRequest request) {
    Variable newValue = request.getVariableBinding().getVariable();
    OID oid = request.getVariableBinding().getOid();
    if (variableBindings.getOrDefault(oid, newValue).getSyntax() == newValue.getSyntax()) {
        variableBindings.put(oid, newValue);
    } else {
        request.getStatus().setErrorStatus(SnmpConstants.SNMP_ERROR_INCONSISTENT_VALUE);
    }
    request.getStatus().setPhaseComplete(true);
}
 
Example #20
Source File: MOGroup.java    From snmpman with Apache License 2.0 5 votes vote down vote up
@Override
public boolean next(final SubRequest request) {
    final MOScope scope = request.getQuery().getScope();
    final SortedMap<OID, Variable> tail = variableBindings.tailMap(scope.getLowerBound());
    OID first = tail.firstKey();
    if (scope.getLowerBound().equals(first) && !scope.isLowerIncluded()) {
        if (tail.size() > 1) {
            final Iterator<OID> it = tail.keySet().iterator();
            it.next();
            first = it.next();
        } else {
            return false;
        }
    }
    if (first != null) {
        final Variable variable = variableBindings.get(first);
        // TODO remove try / catch if no more errors occur
        // TODO add configuration check with types though (e.g. UInt32 == UInt32 Modifier?)
        try {
            if (variable == null) {
                request.getVariableBinding().setVariable(Null.noSuchInstance);
            } else {
                request.getVariableBinding().setVariable((Variable) variable.clone());
            }
            request.getVariableBinding().setOid(first);
        } catch (IllegalArgumentException e) {
            if (variable != null) {
                log.error("error occurred on variable class " + variable.getClass().getName() + " with first OID " + first.toDottedString(), e);
            }
        }
        request.completed();
        return true;
    }
    return false;
}
 
Example #21
Source File: LumentumSdnRoadmFlowRuleProgrammable.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public Collection<FlowEntry> getFlowEntries() {
    try {
        snmp = new LumentumSnmpDevice(handler().data().deviceId());
    } catch (IOException e) {
        log.error("Failed to connect to device: ", e);
        return Collections.emptyList();
    }

    // Line in is last but one port, line out is last
    DeviceService deviceService = this.handler().get(DeviceService.class);
    List<Port> ports = deviceService.getPorts(data().deviceId());
    if (ports.size() < 2) {
        return Collections.emptyList();
    }
    PortNumber lineIn = ports.get(ports.size() - 2).number();
    PortNumber lineOut = ports.get(ports.size() - 1).number();

    Collection<FlowEntry> entries = Lists.newLinkedList();

    // Add rules
    OID addOid = new OID(CTRL_CHANNEL_STATE + "1");
    entries.addAll(
            fetchRules(addOid, true, lineOut).stream()
                    .map(fr -> new DefaultFlowEntry(fr, FlowEntry.FlowEntryState.ADDED, 0, 0, 0))
                    .collect(Collectors.toList())
    );

    // Drop rules
    OID dropOid = new OID(CTRL_CHANNEL_STATE + "2");
    entries.addAll(
            fetchRules(dropOid, false, lineIn).stream()
                    .map(fr -> new DefaultFlowEntry(fr, FlowEntry.FlowEntryState.ADDED, 0, 0, 0))
                    .collect(Collectors.toList())
    );

    return entries;
}
 
Example #22
Source File: SNMPClient.java    From mysql_perf_analyzer with Apache License 2.0 5 votes vote down vote up
private Map<Integer, String> getNetIfIndexes(String device) throws IOException {
  Map<Integer, String> ifMaps = new HashMap<Integer, String> ();
		
     TableUtils tUtils = new TableUtils(snmp, new DefaultPDUFactory());
     
     logger.fine("Query "+this.address+" for network interface, excluding lo");
      @SuppressWarnings("unchecked")
      List<TableEvent> events = tUtils.getTable(getTarget(), new OID[]{new OID("."+IF_TABLE_DEVICE_OID)}, null, null);

      for (TableEvent event : events) {
        if(event.isError()) {
       	 logger.warning(this.address + ": SNMP event error: "+event.getErrorMessage());
       	 continue;
             //throw new RuntimeException(event.getErrorMessage());
        }
        for(VariableBinding vb: event.getColumns()) {
     	   String key = vb.getOid().toString();
     	   String value = vb.getVariable().toString();
     	   if(device!=null && !device.isEmpty() && !value.equalsIgnoreCase(device))
     		   continue;
     	   if(value!=null && !value.equalsIgnoreCase("lo"))
     	   {
     	       logger.fine("Find device OID entry: "+key);
     	         int index = -1;
     	         String[] strs = key.split("\\.");
     	         try
     	         {
     	        	 index = Integer.parseInt(strs[strs.length-1]);
     	        	 ifMaps.put(index, value);
     	         }catch(Exception ex){}
     	   }
        }
      }
      return ifMaps;
}
 
Example #23
Source File: SnmpmanIntegrationTest.java    From snmpman with Apache License 2.0 5 votes vote down vote up
@Test
public void testWithCommunityIndex() throws Exception {
    final String oid = "1.3.6.1.2.1.17.2.4";
    List<TableEvent> responses1 = SnmpmanTest.getResponse(new OID(oid), PORT, "public@42");
    assertEquals(responses1.size(), 1);
    assertTrue(SnmpmanTest.containsColumn(responses1, oid, "150"));

    List<TableEvent> responses2 = SnmpmanTest.getResponse(new OID(oid), PORT, "public@9");
    assertEquals(responses2.size(), 1);
    assertTrue(SnmpmanTest.containsColumn(responses2, oid, "120"));

    List<TableEvent> responses3 = SnmpmanTest.getResponse(new OID(oid), PORT, COMMUNITY);
    assertEquals(responses3.size(), 1);
    assertTrue(SnmpmanTest.containsColumn(responses3, oid, "0"));
}
 
Example #24
Source File: SnmpmanIntegrationTest.java    From snmpman with Apache License 2.0 5 votes vote down vote up
@Test
public void testSnmpGetBulk() throws Exception {
    List<TableEvent> responses = SnmpmanTest.getResponse(new OID("1.3.6.1.2.1"), 10000);
    assertEquals(responses.size(), 19);

    responses = SnmpmanTest.getResponse(new OID("1.3.6.1.2.1.31"), 10000);
    assertEquals(responses.size(), 10);

    responses = SnmpmanTest.getResponse(new OID(".1.3.6.1.2.1.2"), 10000);
    assertEquals(responses.size(), 7);
}
 
Example #25
Source File: MOGroup.java    From snmpman with Apache License 2.0 5 votes vote down vote up
@Override
public OID find(final MOScope range) {
    final SortedMap<OID, Variable> tail = variableBindings.tailMap(range.getLowerBound());
    final OID first = tail.firstKey();
    if (range.getLowerBound().equals(first) && !range.isLowerIncluded()) {
        if (tail.size() > 1) {
            final Iterator<OID> it = tail.keySet().iterator();
            it.next();
            return it.next();
        }
    } else {
        return first;
    }
    return null;
}
 
Example #26
Source File: SNMPUtils.java    From nifi with Apache License 2.0 5 votes vote down vote up
/**
 * Method to return the authentication protocol given the property
 * @param authProtocol property
 * @return protocol
 */
public static OID getAuth(String authProtocol) {
    switch (authProtocol) {
    case "SHA":
        return AuthSHA.ID;
    case "MD5":
        return AuthMD5.ID;
    default:
        return null;
    }
}
 
Example #27
Source File: MOGroup.java    From snmpman with Apache License 2.0 5 votes vote down vote up
/**
 * Sets UnDo-Value for the OID to SubRequest which is replaced when commit fails.
 *
 * @param request The SubRequest to handle.
 */
@Override
public void prepare(SubRequest request) {
    OID oid = request.getVariableBinding().getOid();
    request.setUndoValue(variableBindings.get(oid));
    request.getStatus().setPhaseComplete(true);
}
 
Example #28
Source File: SnmpmanTest.java    From snmpman with Apache License 2.0 5 votes vote down vote up
@Test
public void testModifier() throws Exception {
    final String oid = "1.3.6.1.2.1.2.2.1.13";
    List<TableEvent> responses1 = SnmpmanTest.getResponse(new OID(oid), PORT, COMMUNITY);
    List<TableEvent> responses2 = SnmpmanTest.getResponse(new OID(oid), PORT, COMMUNITY);

    assertNotEquals(responses1.get(0).getColumns(), responses2.get(0).getColumns(),
            "repeated call should return a different result");
}
 
Example #29
Source File: SNMPUtils.java    From ingestion with Apache License 2.0 5 votes vote down vote up
public static void sendTrapV2(String port) throws IOException {
    PDU trap = new PDU();
    trap.setType(PDU.TRAP);

    OID oid = new OID("1.2.3.4.5");
    trap.add(new VariableBinding(SnmpConstants.snmpTrapOID, oid));
    trap.add(new VariableBinding(SnmpConstants.sysUpTime, new TimeTicks(5000)));
    trap.add(new VariableBinding(SnmpConstants.sysDescr, new OctetString("System Description")));

    // Add Payload
    Variable var = new OctetString("some string");
    trap.add(new VariableBinding(oid, var));

    // Specify receiver
    Address targetaddress = new UdpAddress("127.0.0.1/" + port);
    CommunityTarget target = new CommunityTarget();
    target.setCommunity(new OctetString("public"));
    target.setVersion(SnmpConstants.version2c);
    target.setAddress(targetaddress);

    // Send
    Snmp snmp = new Snmp(new DefaultUdpTransportMapping());
    snmp.send(trap, target, null, null);

    snmp.close();
}
 
Example #30
Source File: CommunityIndexCounter32ModifierTest.java    From snmpman with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetVariableBindings() {
    final CommunityIndexCounter32Modifier modifier = new CommunityIndexCounter32Modifier();
    modifier.init(modifierProperties);

    final OctetString context1 = new OctetString("20");
    final OID queryOID1 = new OID(OID);
    final Map<OID, Variable> variableBindings1 = modifier.getVariableBindings(context1, queryOID1);

    assertEquals(variableBindings1.size(), 1);
    assertEquals(variableBindings1.get(queryOID1), new Counter32(150L));

    final OctetString context2 = new OctetString("23");
    final OID queryOID2 = new OID("1.3.6");
    final Map<OID, Variable> variableBindings2 = modifier.getVariableBindings(context2, queryOID2);

    assertEquals(variableBindings2.size(), 0, "bindings with not initialized context should be empty");

    final OctetString context3 = null;
    final OID queryOID3 = new OID("1.3.6");
    final Map<OID, Variable> variableBindings3 = modifier.getVariableBindings(context3, queryOID3);

    assertEquals(variableBindings3.size(), 1);
    assertEquals(variableBindings3.get(queryOID3), new Counter32(0L), "bindings with null context should be 0");

    final OctetString context4 = new OctetString();
    final OID queryOID4 = new OID("1.3.6");
    final Map<OID, Variable> variableBindings4 = modifier.getVariableBindings(context4, queryOID4);

    assertEquals(variableBindings4.size(), 1);
    assertEquals(variableBindings4.get(queryOID4), new Counter32(0L), "bindings with empty context should be 0");

    final OctetString context5 = new OctetString("20");
    final OID queryOID5 = null;
    final Map<OID, Variable> variableBindings5 = modifier.getVariableBindings(context5, queryOID5);

    assertEquals(variableBindings5.size(), 0, "bindings with null query OID should be empty");
}