org.snmp4j.smi.Variable Java Examples

The following examples show how to use org.snmp4j.smi.Variable. 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: SetSNMP.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
/**
 * Method to create the variable from the attribute value and the given SMI syntax value
 * @param value attribute value
 * @param smiSyntax attribute SMI Syntax
 * @return variable
 */
private Variable stringToVariable(String value, int smiSyntax) {
    Variable var = AbstractVariable.createFromSyntax(smiSyntax);
    try {
        if (var instanceof AssignableFromString) {
            ((AssignableFromString) var).setValue(value);
        } else if (var instanceof AssignableFromInteger) {
            ((AssignableFromInteger) var).setValue(Integer.valueOf(value));
        } else if (var instanceof AssignableFromLong) {
            ((AssignableFromLong) var).setValue(Long.valueOf(value));
        } else {
            this.getLogger().error("Unsupported conversion of [" + value +"] to " + var.getSyntaxString());
            var = null;
        }
    } catch (IllegalArgumentException e) {
        this.getLogger().error("Unsupported conversion of [" + value +"] to " + var.getSyntaxString(), e);
        var = null;
    }
    return var;
}
 
Example #2
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 #3
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 #4
Source File: SetSNMP.java    From nifi with Apache License 2.0 6 votes vote down vote up
/**
 * Method to create the variable from the attribute value and the given SMI syntax value
 * @param value attribute value
 * @param smiSyntax attribute SMI Syntax
 * @return variable
 */
private Variable stringToVariable(String value, int smiSyntax) {
    Variable var = AbstractVariable.createFromSyntax(smiSyntax);
    try {
        if (var instanceof AssignableFromString) {
            ((AssignableFromString) var).setValue(value);
        } else if (var instanceof AssignableFromInteger) {
            ((AssignableFromInteger) var).setValue(Integer.valueOf(value));
        } else if (var instanceof AssignableFromLong) {
            ((AssignableFromLong) var).setValue(Long.valueOf(value));
        } else {
            this.getLogger().error("Unsupported conversion of [" + value +"] to " + var.getSyntaxString());
            var = null;
        }
    } catch (IllegalArgumentException e) {
        this.getLogger().error("Unsupported conversion of [" + value +"] to " + var.getSyntaxString(), e);
        var = null;
    }
    return var;
}
 
Example #5
Source File: ModifierTest.java    From snmpman with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testModify() {
    final ModifierProperties modifierProperties = new ModifierProperties();
    modifierProperties.put("minimum", 0L);
    modifierProperties.put("maximum", 3000L);
    modifierProperties.put("minimumStep", 1L);
    modifierProperties.put("maximumStep", 10L);

    final Modifier modifier = new Modifier(".1.3.6.*", "com.oneandone.snmpman.configuration.modifier.Counter32Modifier", modifierProperties);

    final Counter32 counter32 = new Counter32(0L);
    assertEquals(counter32.getValue(), 0L);

    final Variable modifiedVariable = modifier.modify(counter32);
    assertTrue(modifiedVariable instanceof Counter32);
    assertNotEquals(((Counter32) modifiedVariable).getValue(), 0L);
}
 
Example #6
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 #7
Source File: CommunityIndexCounter32Modifier.java    From snmpman with Apache License 2.0 5 votes vote down vote up
@Override
public Map<OID, Variable> getVariableBindings(final OctetString context, final OID queryOID) {
    if (queryOID != null && context != null && context.getValue().length != 0) {
        if (!queryOID.toString().isEmpty() && !context.toString().isEmpty() && communityContextMapping.containsKey(Long.parseLong(context.toString()))) {
            return Collections.singletonMap(queryOID, new Counter32(communityContextMapping.get(Long.parseLong(context.toString()))));
        }
    } else if (queryOID != null) {
        return Collections.singletonMap(queryOID, modify(null));

    }
    return new TreeMap<>();
}
 
Example #8
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");
}
 
Example #9
Source File: MOGroup.java    From snmpman with Apache License 2.0 5 votes vote down vote up
/**
 * If any ErrorStatus, except the implicit {@link org.snmp4j.PDU#noError PDU.noError},
 * has occurred during commit then the old values are written.
 *
 * @param request The SubRequest to handle.
 */
@Override
public void undo(final SubRequest request) {
    if (request.getUndoValue() instanceof Variable) {
        variableBindings.put(request.getVariableBinding().getOid(), (Variable) request.getUndoValue());
    } else {
        variableBindings.remove(request.getVariableBinding().getOid());
    }
    request.getStatus().setPhaseComplete(true);
}
 
Example #10
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 #11
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 #12
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 #13
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 #14
Source File: SNMPUtils.java    From ingestion with Apache License 2.0 4 votes vote down vote up
public static void sendTrapV1(String port) throws IOException {

        TransportMapping<?> transport = new DefaultUdpTransportMapping();
        transport.listen();

        CommunityTarget comtarget = new CommunityTarget();
        comtarget.setCommunity(new OctetString(new OctetString("public")));
        comtarget.setVersion(SnmpConstants.version1);
        comtarget.setAddress(new UdpAddress("127.0.0.1/" + port));
        comtarget.setRetries(2);
        comtarget.setTimeout(5000);

        PDU trap = new PDUv1();
        trap.setType(PDU.V1TRAP);

        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));

        // Send
        Snmp snmp = new Snmp(transport);
        snmp.send(trap, comtarget);
        transport.close();
        snmp.close();

    }
 
Example #15
Source File: SnmpBinding.java    From openhab1-addons with Eclipse Public License 2.0 4 votes vote down vote up
private void dispatchPdu(Address address, PDU pdu) {
    if (pdu != null & address != null) {
        logger.debug("Received PDU from '{}' '{}'", address, pdu);
        for (SnmpBindingProvider provider : providers) {
            for (String itemName : provider.getItemNames()) {
                // Check the IP address
                if (!provider.getAddress(itemName).equals(address)) {
                    continue;
                }

                // Check the OID
                OID oid = provider.getOID(itemName);
                Variable variable = pdu.getVariable(oid);
                if (variable != null) {
                    Class<? extends Item> itemType = provider.getItemType(itemName);

                    // Do any transformations
                    String value = variable.toString();
                    try {
                        value = provider.doTransformation(itemName, value);
                    } catch (TransformationException e) {
                        logger.error("Transformation error with item {}: {}", itemName, e);
                    }

                    // Change to a state
                    State state = null;
                    if (itemType.isAssignableFrom(StringItem.class)) {
                        state = StringType.valueOf(value);
                    } else if (itemType.isAssignableFrom(NumberItem.class)) {
                        state = DecimalType.valueOf(value);
                    } else if (itemType.isAssignableFrom(SwitchItem.class)) {
                        state = OnOffType.valueOf(value);
                    }

                    if (state != null) {
                        eventPublisher.postUpdate(itemName, state);
                    } else {
                        logger.debug("'{}' couldn't be parsed to a State. Valid State-Types are String and Number",
                                variable.toString());
                    }
                } else {
                    logger.trace("PDU doesn't contain a variable with OID '{}'", oid.toString());
                }
            }
        }
    }
}
 
Example #16
Source File: ModifiedVariable.java    From snmpman with Apache License 2.0 4 votes vote down vote up
@Override
public int compareTo(final Variable variable) {
    return this.variable.compareTo(variable);
}
 
Example #17
Source File: PolatisSnmpUtility.java    From onos with Apache License 2.0 4 votes vote down vote up
/**
 * Retrieves static object value.
 *
 * @param handler parent driver handler
 * @param oid object identifier
 * @return the variable
 * @throws IOException if unable to retrieve the object value
 */
public static Variable get(DriverHandler handler, String oid) throws IOException {
    List<VariableBinding> vbs = new ArrayList<>();
    vbs.add(new VariableBinding(new OID(oid)));
    PDU pdu = new PDU(PDU.GET, vbs);
    Snmp session = getSession(handler);
    CommunityTarget target = getTarget(handler);
    ResponseEvent event = session.send(pdu, target);
    return event.getResponse().get(0).getVariable();
}
 
Example #18
Source File: MOGroup.java    From snmpman with Apache License 2.0 3 votes vote down vote up
/**
 * Constructs a new instance of this class.
 * <br>
 * The specified {@code OID} and variable will be set as the only data stored
 * in the map of {@link #variableBindings}.
 *
 * @param root     the root {@code OID}
 * @param oid      the {@code OID} for a variable binding
 * @param variable the variable of the variable binding
 */
public MOGroup(final OID root, final OID oid, final Variable variable) {
    this.root = root;
    this.scope = new DefaultMOScope(root, true, root.nextPeer(), false);
    this.variableBindings = new TreeMap<>();
    this.variableBindings.put(oid, variable);
}
 
Example #19
Source File: SnmpmanSetTest.java    From snmpman with Apache License 2.0 3 votes vote down vote up
private ResponseEvent setVariableToOID(OID oid, Variable variable) throws IOException {

        final CommunityTarget target = getCommunityTarget(COMMUNITY, GenericAddress.parse(String.format("127.0.0.1/%d", PORT)));

        PDU pdu = new PDU();
        pdu.setType(PDU.SET);

        VariableBinding variableBinding = new VariableBinding(oid);
        variableBinding.setVariable(variable);

        pdu.add(variableBinding);
        return snmp.set(pdu, target);
    }
 
Example #20
Source File: MOGroup.java    From snmpman with Apache License 2.0 2 votes vote down vote up
/**
 * Constructs a new instance of this class.
 *
 * @param root             the root {@code OID}
 * @param variableBindings the map of variable bindings for this instance
 */
public MOGroup(final OID root, final SortedMap<OID, Variable> variableBindings) {
    this.root = root;
    this.scope = new DefaultMOScope(root, true, root.nextPeer(), false);
    this.variableBindings = variableBindings;
}
 
Example #21
Source File: ModifiedVariable.java    From snmpman with Apache License 2.0 2 votes vote down vote up
/**
 * Constructs a new modified variable.
 * <br>
 * A modified variable will dynamically change it's value on each value call.
 *
 * @param variable  the initial variable to modify
 * @param modifiers the list of modifiers that should modify this variable
 */
public ModifiedVariable(final Variable variable, final List<VariableModifier> modifiers) {
    this.variable = variable;
    this.modifiers = Collections.unmodifiableList(modifiers);
}
 
Example #22
Source File: CommunityContextModifier.java    From snmpman with Apache License 2.0 2 votes vote down vote up
/**
 * Creates a mapping of SNMP OID and a value based on the SNMP community context and the SNMP OID.
 *
 * @param context SNMP community context.
 * @param oid     SNMP OID.
 * @return variable binding of OID to Variable.
 */
Map<OID, Variable> getVariableBindings(final OctetString context, final OID oid);