public class SNMP4JParser implements Callable {
/**
* The following objects are all necessary in order to use SNMP4j as a parser for raw messages.
* This was all inspired by SNMP4j source code, in particular MessageDispatcherImpl.java
*/
private MessageProcessingModel model = null;
private MessageDispatcher dispatcher = null;
private Address listenAddress = null;
private Integer32 messageProcessingModel = null;
private Integer32 securityModel = null;
private OctetString securityName = null;
private Integer32 securityLevel = null;
private PduHandle handle = null;
private StatusInformation statusInfo = null;
private MutableStateReference mutableStateReference = null;
/**
* Taken from org.snmp4j.transport.AbstractTransportMapping class
*/
protected Integer32 maxInboundMessageSize = new Integer32 ( (1 << 16) - 1 );
/**
* Taken from org.snmp4j.MessageDispatcherImpl class
*/
private int transactionID = new Random().nextInt(Integer.MAX_VALUE - 2) + 1;
/**
* Create all objects that SNMP4j needs to parse a raw SNMP message
*/
public SNMP4JParser()
{
model = new MPv1();
dispatcher = new MessageDispatcherImpl();
listenAddress = GenericAddress.parse("udp:0.0.0.0/2001");
messageProcessingModel = new Integer32();
securityModel = new Integer32();
securityName = new OctetString();
securityLevel = new Integer32();
handle = new PduHandle(transactionID);
statusInfo = new StatusInformation();
mutableStateReference = new MutableStateReference();
}
/**
* @see org.mule.api.lifecycle.Callable#onCall(org.mule.api.MuleEventContext)
*/
@Override
public Object onCall(MuleEventContext eventContext) throws Exception
{
byte[] payloadBytes = eventContext.getMessage().getPayloadAsBytes();
ByteBuffer buffer = ByteBuffer.wrap(payloadBytes);
BERInputStream wholeMessage = new BERInputStream(buffer);
MutablePDU mutablePdu = new MutablePDU();
int status = model.prepareDataElements(
dispatcher,
listenAddress,
wholeMessage,
messageProcessingModel,
securityModel,
securityName,
securityLevel,
mutablePdu,
handle,
maxInboundMessageSize,
statusInfo,
mutableStateReference);
if ( status != SnmpConstants.SNMP_MP_OK )
throw new RuntimeException(
"Couldn't parse SNMP message. model.prepareDataElements() returned " + status);
return mutablePdu.getPdu();
}
}
我已经用这样的流程对其进行了测试(我使用了snmp4j-1.11.5和mule-standalone-3.4.0)
<udp:connector name="connector" doc:name="UDP"/>
<flow name="snmp-demo-trapHandlingFlow" doc:name="snmp-demo-trapHandlingFlow">
<udp:inbound-endpoint host="0.0.0.0" port="2001" responseTimeout="10000" doc:name="UDP"/>
<logger message="TRAP RECEIVED - #[System.currentTimeMillis()]" level="DEBUG" doc:name="Inbound timestamp"/>
<component class="com.netboss.flow.demo.SNMP4JParser" doc:name="SNMP4JParser"/>
[...]
它有效。
现在,我意识到还有一些悬而未决的问题:
- 有没有更好/更有效的方法?
- 这仅适用于 SNMP v1,如何修改上述代码以使其也适用于 v2 和 v3?