Implementing 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
NOTE: Custome Error handling need to be implemented, as per the strategy

Hello Ashish,
Thanks for all the tutorials you provided which are quite useful and helped us a lot in understanding Apache MINA along with the examples. Currently we are using Apache MINA in one of our project to develop a proxy server. The communication looks as follows:
Sender(Any http client) -> Proxy (modifies the body of http request) -> Receiver(Http Server) -> Proxy (modifies the response from Receiver) -> Sender
Our implementation works fine but fails when there is LDAP authentication (tested only with basic ldap authentication). The request from Sender will be posted to Proxy but not understanding what happens after that. No error message, no logs and nothing. Do you have any clue how to handle in such scenario? Can you please help us.
Thanks in advance and I look forward for your response. Also please let me know in case if you need more details.
With Regards
Jagdish
Hi Ashish,
Thank you very much.This tutorial is very much helpful.I am facing a small issue while encoding the pdu.when i am encoding i am getting invalid snmp ans.1 type on the receiver side.i tried all the ways but no luck.please kindly provide me SNMP4j encode.
Regards,
nani