Thursday, September 11, 2008

SNMP4J Decoder for Apache MINA

Recently started evaluating Apache MINA. So thought about building a Trap Receiver using Apache MINA. Refer to one of my posting on What is Apache MINA?


Design



In this post we shall concentrate on just writing the ProtocolDecoder

The code snippet using SNMP4J library is

public class SNMP4JCodec extends ProtocolDecoderAdapter {

static Logger logger = LoggerFactory.getLogger(SNMP4JCodec.class);

public void decode(IoSession ioSession, IoBuffer ioBuffer,
ProtocolDecoderOutput protocolDecoderOutput) throws Exception {
ByteBuffer pduBuffer = ioBuffer.buf();
// Decode the bytes using SNMP4J API's
PDU pdu = new PDU();
try {
BERInputStream berStream = new BERInputStream(pduBuffer);
BER.MutableByte mutableByte = new BER.MutableByte();
int length = BER.decodeHeader(berStream, mutableByte);
int startPos = (int)berStream.getPosition();

if (mutableByte.getValue() != BER.SEQUENCE) {
String txt = "SNMPv2c PDU must start with a SEQUENCE";
throw new IOException(txt);
}
Integer32 version = new Integer32();
version.decodeBER(berStream);

// decode community string
OctetString securityName = new OctetString();
securityName.decodeBER(berStream);

// decode the remaining PDU
pdu.decodeBER(berStream);
logger.debug("PDU - "+pdu);
} catch (Exception ex) {
ex.printStackTrace();
}
protocolDecoderOutput.write(pdu);
}
}

The code converts ByteBuffer into an SNMP PDU using SNMP4J  library. Similarly, we can use Adventnet or joesnmp to convert the byte stream into SNMP PDU's

Labels: , , , ,

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home