在找資料時剛好看到有文章整理了 CommandResponderEvent的幾個範例,覺得不錯趕緊筆記下來XD

本篇文章內容轉載自 : 

http://www.programcreek.com/java-api-examples/index.php?api=org.snmp4j.CommandResponderEvent

Example 1
Project: apmrouter   File: TrapPrinter.java View source code Vote up 6 votes
@Override
public void processPdu(CommandResponderEvent event) {
	StringBuilder b = new StringBuilder("Received PDU:");
	PDU pdu = event.getPDU();
	event.getPeerAddress();
	b.append("\n\tReceived From: [" + event.getPeerAddress() + "]");
	b.append("\n\tType Code: [" + PDU_DECODES.get(pdu.getType()) + "]");
	b.append("\n\tRequest ID: [" + pdu.getRequestID() + "]");
	b.append("\n\tStatus: [" + pdu.getErrorStatusText() + "]");
	processV2(pdu, b);
	if(pdu instanceof PDUv1) {
		processV1((PDUv1)pdu, b);
	}
	log(b);
	
}
 
Example 2
Project: opennms_dashboard   File: MockProxy.java View source code Vote up 6 votes
public void processPdu(CommandResponderEvent e) {
    PDU command = e.getPDU();
    if (command == null) return;
 
    PDU response = processRequest(command);
      if (response == null) return;
      
      StatusInformation statusInformation = new StatusInformation();
      StateReference ref = e.getStateReference();
      try {
          Logger.getLogger(MockProxy.class).debug("Replying with: "+command);
          e.setProcessed(true);
          e.getMessageDispatcher().returnResponsePdu(e.getMessageProcessingModel(),
                                                     e.getSecurityModel(),
                                                     e.getSecurityName(),
                                                     e.getSecurityLevel(),
                                                     command,
                                                     e.getMaxSizeResponsePDU(),
                                                     ref,
                                                     statusInformation);
      }
      catch (MessageException ex) {
          System.err.println("Error while sending response: "+ex.getMessage());
          Logger.getLogger(MockProxy.class).error(ex);
      }
      
    
}
 
Example 3
Project: opennms_dashboard   File: Snmp4jTrapReceiverTest.java View source code Vote up 6 votes
public synchronized void processPdu(CommandResponderEvent cmdRespEvent) {
    PDU pdu = cmdRespEvent.getPDU();
    System.out.println("Received PDU... " + pdu);
    if (pdu != null) {
        System.out.println(pdu.getClass().getName());
        System.out.println("trapType = " + pdu.getType());
        System.out.println("isPDUv1 = " + (pdu instanceof PDUv1));
        System.out.println("isTrap = " + (pdu.getType() == PDU.TRAP));
        System.out.println("isInform = " + (pdu.getType() == PDU.INFORM));
        System.out.println("variableBindings = " + pdu.getVariableBindings());
        trapCount++;
    } else {
        System.err.println("ERROR: Can't create PDU");
    }
}
 
Example 4
Project: rhq   File: SnmpTrapSender.java View source code Vote up 6 votes
/**
 * processPdu
 *
 * @param e CommandResponderEvent
 */
public synchronized void processPdu(CommandResponderEvent e) {
    PDU command = e.getPDU();
    if (command != null) {
        if (log.isDebugEnabled())
            log.debug(command.toString());
        if ((command.getType() != PDU.TRAP) && (command.getType() != PDU.V1TRAP)
            && (command.getType() != PDU.REPORT) && (command.getType() != PDU.RESPONSE)) {
            command.setErrorIndex(0);
            command.setErrorStatus(0);
            command.setType(PDU.RESPONSE);
            StatusInformation statusInformation = new StatusInformation();
            StateReference ref = e.getStateReference();
            try {
                e.getMessageDispatcher().returnResponsePdu(e.getMessageProcessingModel(), e.getSecurityModel(),
                    e.getSecurityName(), e.getSecurityLevel(), command, e.getMaxSizeResponsePDU(), ref,
                    statusInformation);
            } catch (MessageException ex) {
                log.error("Error while sending response: " + ex.getMessage());
            }
        }
    }
}
 
Example 5
Project: flume-snmp-source   File: testSNMPTrap.java View source code Vote up 6 votes
/**
 * This method will be called whenever a pdu is received on the given port specified in the listen() method
 */
public synchronized void processPdu(CommandResponderEvent cmdRespEvent)
{
  System.out.println("Received PDU...");
  PDU pdu = cmdRespEvent.getPDU();
  if (pdu != null)
  {

    System.out.println("Trap Type = " + pdu.getType());
    System.out.println("Variable Bindings = " + pdu.getVariableBindings());
    int pduType = pdu.getType();
    if ((pduType != PDU.TRAP) && (pduType != PDU.V1TRAP) && (pduType != PDU.REPORT)
    && (pduType != PDU.RESPONSE))
    {
      pdu.setErrorIndex(0);
      pdu.setErrorStatus(0);
      pdu.setType(PDU.RESPONSE);
      StatusInformation statusInformation = new StatusInformation();
      StateReference ref = cmdRespEvent.getStateReference();
      try
      {
        System.out.println(cmdRespEvent.getPDU());
        cmdRespEvent.getMessageDispatcher().returnResponsePdu(cmdRespEvent.getMessageProcessingModel(),
        cmdRespEvent.getSecurityModel(), cmdRespEvent.getSecurityName(), cmdRespEvent.getSecurityLevel(),
        pdu, cmdRespEvent.getMaxSizeResponsePDU(), ref, statusInformation);
      }
      catch (MessageException ex)
      {
        System.err.println("Error while sending response: " + ex.getMessage());
        LogFactory.getLogger(SnmpRequest.class).error(ex);
      }
    }
  }
}
 
Example 6
Project: ismp_manager   File: Snmp4JTrapNotifier.java View source code Vote up 6 votes
@Override
public void processPdu(CommandResponderEvent e) {
	PDU command = new PDU(e.getPDU());
	IpAddress addr = ((IpAddress) e.getPeerAddress());

	if (command != null) {
		if (command.getType() == PDU.INFORM) {
			PDU response = new PDU(command);
			response.setErrorIndex(0);
			response.setErrorStatus(0);
			response.setType(PDU.RESPONSE);
			StatusInformation statusInformation = new StatusInformation();
			StateReference ref = e.getStateReference();
			try {
				e.getMessageDispatcher().returnResponsePdu(
						e.getMessageProcessingModel(),
						e.getSecurityModel(), e.getSecurityName(),
						e.getSecurityLevel(), response,
						e.getMaxSizeResponsePDU(), ref, statusInformation);
				if (log().isDebugEnabled()) {
					log().debug(
							"Sent RESPONSE PDU to peer "
									+ addr
									+ " acknowledging receipt of INFORM (reqId="
									+ command.getRequestID() + ")");
				}
			} catch (MessageException ex) {
				log().error(
						"Error while sending RESPONSE PDU to peer " + addr
								+ ": " + ex.getMessage()
								+ "acknowledging receipt of INFORM (reqId="
								+ command.getRequestID() + ")");
			}
		}
	}

	if (e.getPDU() instanceof PDUv1) {
		m_listener.trapReceived(new Snmp4JV1TrapInformation(addr
				.getInetAddress(), new String(e.getSecurityName()),
				(PDUv1) e.getPDU(), m_trapProcessorFactory
						.createTrapProcessor()));
	} else {
		m_listener.trapReceived(new Snmp4JV2TrapInformation(addr
				.getInetAddress(), new String(e.getSecurityName()), e
				.getPDU(), m_trapProcessorFactory.createTrapProcessor()));
	}
}
 
Example 7
Project: rhq   File: SnmpTrapEventPoller.java View source code Vote up 5 votes
/**
 * Callback from the Snmp lib. Will be called on each incoming trap
 */
public void processPdu(CommandResponderEvent cre) {

    if (log.isDebugEnabled())
        log.debug("recv: " + cre);
    PDU pdu = cre.getPDU();
    String sourceAddr;
    Address addr = cre.getPeerAddress();
    if (addr instanceof IpAddress) {
        sourceAddr = ((IpAddress) addr).getInetAddress().toString();
        if (sourceAddr.startsWith("/"))
            sourceAddr = sourceAddr.substring(1);
    } else {
        // Don't use addr.toString() as this would contain the port and generate too many
        // EventSources
        sourceAddr = "snmp-agent";
    }
    if (pdu != null) {
        StringBuffer payload = new StringBuffer();
        // SNMP v1
        if (pdu instanceof PDUv1) {
            PDUv1 v1pdu = (PDUv1) pdu;
            long timeTicks = v1pdu.getTimestamp();
            payload.append("Traptype (generic, specific): ");
            payload.append(v1pdu.getGenericTrap()).append(", ").append(v1pdu.getSpecificTrap()).append("\n");
            payload.append("Timestamp: " + new TimeTicks(timeTicks).toString());
            payload.append("\n");
        }

        SnmpTrapdComponent.trapCount++;
        EventSeverity severity = EventSeverity.INFO;

        Vector<VariableBinding> vbs = pdu.getVariableBindings();
        for (VariableBinding vb : vbs) {
            OID oid = vb.getOid();
            Variable var = vb.getVariable();
            int syntax = vb.getSyntax();

            // Try to translate the oid string (1.2.3....) into a readable name
            String oids = oid.toString();
            if (translation.getProperty(oids) != null) {
                oids = translation.getProperty(oids);
            }

            payload.append(oids);
            payload.append(": ");
            payload.append(var.toString()); // TODO change depending on syntax !
            payload.append("\n");

            /*
             * This corresponds with the values from AlertPriority
             */
            if (severityOid != null && oid.compareTo(severityOid) == 0) {
                String sev = var.toString();
                if (sev.toLowerCase().contains("high"))
                    severity = EventSeverity.ERROR;
                else if (sev.toLowerCase().contains("medium"))
                    severity = EventSeverity.WARN;
                else
                    severity = EventSeverity.INFO;
            }
        }

        Event event = new Event(getEventType(), sourceAddr, System.currentTimeMillis(), severity, payload
            .toString());
        if (log.isDebugEnabled())
            log.debug("queue event " + event);

        synchronized (events) {
            events.add(event);
        }

    }
}

 

arrow
arrow
    文章標籤
    JAVA SNMP SNMP4J
    全站熱搜

    allen0818 發表在 痞客邦 留言(0) 人氣()