org.snmp4j.event.ResponseEvent Java Examples

The following examples show how to use org.snmp4j.event.ResponseEvent. 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: SnmpH3C.java    From yuzhouwan with Apache License 2.0 7 votes vote down vote up
/**
 * Send PDU to H3C, then waiting response event will be caught by listener.
 *
 * @param snmp
 * @param userTarget
 * @param pdu
 * @throws IOException
 * @throws InterruptedException
 */
private void sendGetPDU(Snmp snmp, UserTarget userTarget, ScopedPDU pdu)
        throws IOException, InterruptedException {

    final CountDownLatch latch = new CountDownLatch(1);
    ResponseListener listener = new ResponseListener() {

        @Override
        public void onResponse(ResponseEvent event) {
            ((Snmp) event.getSource()).cancel(event.getRequest(), this);
            PDU response = event.getResponse();
            PDU request = event.getRequest();
            LOG.debug("[request]: {}", request);

            if (response == null) {
                LOG.error("[ERROR]: response is null");

            } else if (response.getErrorStatus() != 0) {
                LOG.error(String.format("[ERROR]: response status %s, Text: %s",
                        response.getErrorStatus(),
                        response.getErrorStatusText()));
            } else {
                LOG.debug("Received response Success!");
                for (int i = 0; i < response.size(); i++) {
                    VariableBinding vb = response.get(i);
                    LOG.info("{} = {}",
                            vb.getOid(),
                            vb.getVariable());
                }
                LOG.debug("SNMP Async GetList OID finished. ");
                latch.countDown();
            }
        }
    };
    snmp.send(pdu, userTarget, null, listener);
    LOG.debug("async send pdu wait for response...");

    boolean wait = latch.await(3, TimeUnit.SECONDS);
    LOG.debug("latch.await =:" + wait);
}
 
Example #2
Source File: SnmpUtil.java    From yuzhouwan with Apache License 2.0 6 votes vote down vote up
private static PDU walk(PDU request, Target target)
        throws IOException {
    request.setNonRepeaters(0);
    OID rootOID = request.get(0).getOid();
    PDU response;
    int objects = 0;
    int requests = 0;
    long startTime = System.currentTimeMillis();
    do {
        requests++;
        ResponseEvent responseEvent = SnmpUtil.snmp.send(request, target);
        response = responseEvent.getResponse();
        if (response != null) {
            objects += response.size();
        }
    }
    while (!processWalk(response, request, rootOID));

    System.out.println();
    System.out.println("Total requests sent:    " + requests);
    System.out.println("Total objects received: " + objects);
    System.out.println("Total walk time:        "
            + (System.currentTimeMillis() - startTime) + " milliseconds");
    return response;
}
 
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: SNMPHelper.java    From SuitAgent with Apache License 2.0 5 votes vote down vote up
/**
 * 获取指定OID的 get
 *
 * @param snmp
 * @param target
 * @param oid
 * @return
 * @throws IOException
 */
public static PDU snmpGet(Snmp snmp, Target target, String oid) throws IOException {
    ScopedPDU pdu = new ScopedPDU();
    pdu.setType(PDU.GET);
    pdu.add(new VariableBinding(new OID(oid)));

    ResponseEvent responseEvent = snmp.send(pdu, target);
    PDU response = responseEvent.getResponse();
    if(response == null){
        log.warn("response null - error:{} peerAddress:{} source:{} request:{}",
                responseEvent.getError(),
                responseEvent.getPeerAddress(),
                responseEvent.getSource(),
                responseEvent.getRequest());
    }
    return response;
}
 
Example #5
Source File: SnmpmanSetTest.java    From snmpman with Apache License 2.0 5 votes vote down vote up
@Test
public void testSetterForInvalidValue() throws Exception {
    Integer newValue = 9999;
    ResponseEvent responseEvent = setVariableToOID(new OID(OID_OCTETSTRING).append(OID_ROW_INDEX), new Integer32(newValue));
    assertEquals(SnmpConstants.SNMP_ERROR_INCONSISTENT_VALUE, responseEvent.getResponse().getErrorStatus());
    assertThatOidHasValue(OID_OCTETSTRING, PRIMAL_OCTECT_VALUE);
}
 
Example #6
Source File: SnmpmanSetTest.java    From snmpman with Apache License 2.0 5 votes vote down vote up
@Test
public void testSetterForValidValue() throws Exception {
    String newValue = "New interface";
    ResponseEvent responseEvent = setVariableToOID(new OID(OID_OCTETSTRING).append(OID_ROW_INDEX), new OctetString(newValue));
    assertEquals(SnmpConstants.SNMP_ERROR_SUCCESS, responseEvent.getResponse().getErrorStatus());
    assertThatOidHasValue(OID_OCTETSTRING, newValue);
}
 
Example #7
Source File: SnmpUtil.java    From yuzhouwan with Apache License 2.0 5 votes vote down vote up
public PDU send() throws IOException {
    snmp = createSnmpSession();
    this.target = createTarget();
    target.setVersion(version);
    target.setAddress(address);
    target.setRetries(retries);
    target.setTimeout(timeout);
    snmp.listen();

    PDU request = createPDU(target);
    for (Object vb : vbs) {
        request.add((VariableBinding) vb);
    }

    PDU response = null;
    if (_operation == WALK) {
        response = walk(request, target);
    } else {
        ResponseEvent responseEvent;
        long startTime = System.currentTimeMillis();
        responseEvent = snmp.send(request, target);
        if (responseEvent != null) {
            response = responseEvent.getResponse();
            System.out.println("Received response after "
                    + (System.currentTimeMillis() - startTime) + " millis");
        }
    }
    snmp.close();
    return response;
}
 
Example #8
Source File: SNMPClient.java    From mysql_perf_analyzer with Apache License 2.0 5 votes vote down vote up
public List<SNMPTriple> getDiskData(String device) throws IOException {

int index = this.getDiskIndex(device);
if(index<0)
{
	return new ArrayList<SNMPTriple>();
}
logger.fine("Query disk stats for "+index);
PDU pdu = createPDU();
for ( int i=1; i< DISK_TABLE_ENTRIES.length; i++) {
	if(DISK_TABLE_ENTRIES[i].length()==0)continue;
	pdu.add(new VariableBinding(new OID("."+DISK_TABLE_OID+"."+i+"."+index)));
}
pdu.setType(PDU.GET);
Map<String, String> res = new HashMap<String, String>(13);
ResponseEvent event = snmp.send(pdu, getTarget(), null);
if(event != null) {
	VariableBinding[] binds = event.getResponse().toArray();
	for(VariableBinding b: binds)
		res.put(b.getOid().toString(), b.getVariable().toString());
	//logger.info(res.toString());
}		
      List<SNMPTriple> resList = new ArrayList<SNMPTriple>(res.size());
      for(int i=1;i<DISK_TABLE_ENTRIES.length; i++) {
	if(DISK_TABLE_ENTRIES[i].length()==0)continue;
	resList.add(new SNMPTriple("."+DISK_TABLE_OID+"."+i+"."+index, DISK_TABLE_ENTRIES[i], res.get(DISK_TABLE_OID+"."+i+"."+index)));
      }
       return resList;
 }
 
Example #9
Source File: SNMPClient.java    From mysql_perf_analyzer with Apache License 2.0 5 votes vote down vote up
public ResponseEvent getEvent(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) {
		return event;
	}
	throw new RuntimeException("GET timed out");
}
 
Example #10
Source File: SNMPClient.java    From mysql_perf_analyzer with Apache License 2.0 5 votes vote down vote up
/**
 * Method which takes a single OID and returns the response from the agent as a String.
 * @param oid
 * @return
 * @throws IOException
 */
public String getAsString(OID oid) throws IOException {
	ResponseEvent res = getEvent(new OID[] { oid });
	if(res!=null)
		return res.getResponse().get(0).getVariable().toString();
	return null;
}
 
Example #11
Source File: SNMPHelper.java    From OpenFalcon-SuitAgent with Apache License 2.0 5 votes vote down vote up
/**
 * 获取指定OID的 get
 *
 * @param snmp
 * @param target
 * @param oid
 * @return
 * @throws IOException
 */
public static PDU snmpGet(Snmp snmp, Target target, String oid) throws IOException {
    ScopedPDU pdu = new ScopedPDU();
    pdu.setType(PDU.GET);
    pdu.add(new VariableBinding(new OID(oid)));

    ResponseEvent responseEvent = snmp.send(pdu, target);
    PDU response = responseEvent.getResponse();
    if(response == null){
        log.warn("response null - error:{} peerAddress:{} source:{} request:{}",
                responseEvent.getError(),
                responseEvent.getPeerAddress(),
                responseEvent.getSource(),
                responseEvent.getRequest());
    }
    return response;
}
 
Example #12
Source File: SNMPHelper.java    From OpenFalcon-SuitAgent with Apache License 2.0 4 votes vote down vote up
/**
 * walk方式获取指定的oid value
 *
 * @param snmp
 * @param target
 * @param oid
 * @return
 * @throws IOException
 */
public static List<PDU> snmpWalk(Snmp snmp, Target target, String oid) throws IOException {
    List<PDU> pduList = new ArrayList<>();

    ScopedPDU pdu = new ScopedPDU();
    OID targetOID = new OID(oid);
    pdu.add(new VariableBinding(targetOID));

    boolean finished = false;
    while (!finished) {
        VariableBinding vb = null;
        ResponseEvent respEvent = snmp.getNext(pdu, target);

        PDU response = respEvent.getResponse();

        if (null == response) {
            break;
        } else {
            vb = response.get(0);
        }
        // check finish
        finished = checkWalkFinished(targetOID, pdu, vb);
        if (!finished) {
            pduList.add(response);

            // Set up the variable binding for the next entry.
            pdu.setRequestID(new Integer32(0));
            pdu.set(0, vb);
        }
    }

    return pduList;
}
 
Example #13
Source File: ProcessMessage.java    From mts with GNU General Public License v3.0 4 votes vote down vote up
public void onResponse(ResponseEvent re) {
       // Always cancel async request when response has been received
       // otherwise a memory leak is created! Not canceling a request
       // immediately can be useful when sending a request to a broadcast
       // address.
       try {
            Object source = re.getSource();

           // test to ignore REPORTS from DISCOVERY messages in SNMPv3
           if (!(source instanceof Snmp)) return;

           ((Snmp) source).cancel(re.getRequest(), this);

           //create the SnmpMsg received
           MsgSnmp msg = new MsgSnmp(listenpoint.getStack());
           msg.setPdu(re.getResponse());
           
           //TODO: how to know the version here to set communityTarget or UserTarget
           Target target = new CommunityTarget();
//           ((CommunityTarget)target).setCommunity(new OctetString(re.getStateReference().getSecurityName()));
           target.setAddress(re.getPeerAddress());
           msg.setTarget((AbstractTarget)target);
           UdpAddress add = (UdpAddress) re.getPeerAddress();
           msg.setRemotePort(add.getPort());
           msg.setRemoteHost(add.getInetAddress().getHostAddress());
           msg.setListenpoint(listenpoint);

           StackFactory.getStack(StackFactory.PROTOCOL_SNMP).receiveMessage(msg);
       } catch (Exception ex) {
       }
    }
 
Example #14
Source File: SNMPHelper.java    From SuitAgent with Apache License 2.0 4 votes vote down vote up
/**
 * walk方式获取指定的oid value
 *
 * @param snmp
 * @param target
 * @param oid
 * @return
 * @throws IOException
 */
public static List<PDU> snmpWalk(Snmp snmp, Target target, String oid) throws IOException {
    List<PDU> pduList = new ArrayList<>();

    ScopedPDU pdu = new ScopedPDU();
    OID targetOID = new OID(oid);
    pdu.add(new VariableBinding(targetOID));

    boolean finished = false;
    while (!finished) {
        VariableBinding vb = null;
        ResponseEvent respEvent = snmp.getNext(pdu, target);

        PDU response = respEvent.getResponse();

        if (null == response) {
            break;
        } else {
            vb = response.get(0);
        }
        // check finish
        finished = checkWalkFinished(targetOID, pdu, vb);
        if (!finished) {
            pduList.add(response);

            // Set up the variable binding for the next entry.
            pdu.setRequestID(new Integer32(0));
            pdu.set(0, vb);
        }
    }

    return pduList;
}
 
Example #15
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 #16
Source File: LumentumSdnRoadmFlowRuleProgrammable.java    From onos with Apache License 2.0 4 votes vote down vote up
private boolean removeCrossConnect(CrossConnectFlowRule xc) {

        int channel = toChannel(xc.ochSignal());

        // Create the PDU object
        PDU pdu = new PDU();
        pdu.setType(PDU.SET);

        // Disable the channel
        OID ctrlChannelState = new OID(CTRL_CHANNEL_STATE + (xc.isAddRule() ? "1." : "2.") + channel);
        pdu.add(new VariableBinding(ctrlChannelState, new Integer32(OUT_OF_SERVICE)));

        // Put cross connect back into default port 1
        OID ctrlChannelAddDropPortIndex = new OID(CTRL_CHANNEL_ADD_DROP_PORT_INDEX +
                (xc.isAddRule() ? "1." : "2.") + channel);
        pdu.add(new VariableBinding(ctrlChannelAddDropPortIndex,
                new UnsignedInteger32(DISABLE_CHANNEL_ADD_DROP_PORT_INDEX)));

        // Put port/channel back to open loop
        OID ctrlChannelMode = new OID(CTRL_CHANNEL_MODE + (xc.isAddRule() ? "1." : "2.") + channel);
        pdu.add(new VariableBinding(ctrlChannelMode, new Integer32(OPEN_LOOP)));

        // Add rules are set to target power, drop rules are attenuated
        if (xc.isAddRule()) {
            OID ctrlChannelTargetPower = new OID(CTRL_CHANNEL_TARGET_POWER + "1." + channel);
            pdu.add(new VariableBinding(ctrlChannelTargetPower, new Integer32(DISABLE_CHANNEL_TARGET_POWER)));
        } else {
            OID ctrlChannelAbsoluteAttenuation = new OID(CTRL_CHANNEL_ABSOLUTE_ATTENUATION + "2." + channel);
            pdu.add(new VariableBinding(
                    ctrlChannelAbsoluteAttenuation, new UnsignedInteger32(DISABLE_CHANNEL_ABSOLUTE_ATTENUATION)));
        }

        try {
            ResponseEvent response = snmp.set(pdu);

            // TODO: parse response
        } catch (IOException e) {
            log.error("Failed to remove cross connect, unable to connect to device: ", e);
            return false;
        }

        return true;
    }
 
Example #17
Source File: LumentumSnmpDevice.java    From onos with Apache License 2.0 4 votes vote down vote up
public ResponseEvent set(PDU pdu) throws IOException {
    return snmp.set(pdu, target);
}
 
Example #18
Source File: SnmpBinding.java    From openhab1-addons with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Called when a response from a GET is received
 *
 * @see org.snmp4j.event.ResponseListener#onResponse(org.snmp4j.event.ResponseEvent )
 */
@Override
public void onResponse(ResponseEvent event) {
    // Always cancel async request when response has been received
    // otherwise a memory leak is created! Not canceling a request
    // immediately can be useful when sending a request to a broadcast
    // address.
    ((Snmp) event.getSource()).cancel(event.getRequest(), this);

    dispatchPdu(event.getPeerAddress(), event.getResponse());
}
 
Example #19
Source File: PolatisSnmpUtility.java    From onos with Apache License 2.0 3 votes vote down vote up
/**
 * Sends a synchronous SET request to the supplied target.
 *
 * @param handler parent driver handler
 * @param vbs a list of variable bindings
 * @return the response event
 * @throws IOException if unable to set the target
 */
public static ResponseEvent set(DriverHandler handler, List<? extends VariableBinding> vbs) throws IOException {
    Snmp session = getSession(handler);
    CommunityTarget target = getTarget(handler);
    PDU pdu = new PDU(PDU.SET, vbs);
    return session.set(pdu, target);
}
 
Example #20
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 #21
Source File: SNMPHelper.java    From OpenFalcon-SuitAgent with Apache License 2.0 2 votes vote down vote up
/**
 * 获取指定OID的 getNext
 *
 * @param snmp
 * @param target
 * @param oid
 * @return
 * @throws IOException
 */
public static PDU snmpGetNext(Snmp snmp, Target target, String oid) throws IOException {
    ScopedPDU pdu = new ScopedPDU();
    pdu.setType(PDU.GETNEXT);
    pdu.add(new VariableBinding(new OID(oid)));

    ResponseEvent responseEvent = snmp.send(pdu, target);
    return responseEvent.getResponse();
}
 
Example #22
Source File: PolatisSnmpUtility.java    From onos with Apache License 2.0 2 votes vote down vote up
/**
 * Sends a SET request.
 *
 * @param handler parent driver handler
 * @param pdu SNMP protocol data unit
 * @return the response event
 * @throws IOException if unable to send a set request
 */
public static ResponseEvent set(DriverHandler handler, PDU pdu) throws IOException {
    Snmp session = getSession(handler);
    CommunityTarget target = getTarget(handler);
    return session.set(pdu, target);
}
 
Example #23
Source File: SNMPHelper.java    From SuitAgent with Apache License 2.0 2 votes vote down vote up
/**
 * 获取指定OID的 getNext
 *
 * @param snmp
 * @param target
 * @param oid
 * @return
 * @throws IOException
 */
public static PDU snmpGetNext(Snmp snmp, Target target, String oid) throws IOException {
    ScopedPDU pdu = new ScopedPDU();
    pdu.setType(PDU.GETNEXT);
    pdu.add(new VariableBinding(new OID(oid)));

    ResponseEvent responseEvent = snmp.send(pdu, target);
    return responseEvent.getResponse();
}
 
Example #24
Source File: SNMPSetter.java    From localization_nifi with Apache License 2.0 2 votes vote down vote up
/**
 * Executes the SNMP set request and returns the response
 * @param pdu PDU to send
 * @return Response event
 * @throws IOException IO Exception
 */
public ResponseEvent set(PDU pdu) throws IOException {
    return this.snmp.set(pdu, this.target);
}
 
Example #25
Source File: SNMPSetter.java    From nifi with Apache License 2.0 2 votes vote down vote up
/**
 * Executes the SNMP set request and returns the response
 * @param pdu PDU to send
 * @return Response event
 * @throws IOException IO Exception
 */
public ResponseEvent set(PDU pdu) throws IOException {
    return this.snmp.set(pdu, this.target);
}