Package org.saf.snmp

Source Code of org.saf.snmp.SNMPHelper

package org.saf.snmp;

import java.io.IOException;
import org.apache.log4j.Logger;
import org.snmp4j.CommunityTarget;
import org.snmp4j.PDU;
import org.snmp4j.PDUv1;
import org.snmp4j.Snmp;
import org.snmp4j.TransportMapping;
import org.snmp4j.event.ResponseEvent;
import org.snmp4j.event.ResponseListener;
import org.snmp4j.mp.SnmpConstants;
import org.snmp4j.smi.Address;
import org.snmp4j.smi.GenericAddress;
import org.snmp4j.smi.Integer32;
import org.snmp4j.smi.OID;
import org.snmp4j.smi.OctetString;
import org.snmp4j.smi.UdpAddress;
import org.snmp4j.smi.VariableBinding;
import org.snmp4j.transport.DefaultUdpTransportMapping;

public class SNMPHelper {
 
  private static final Logger logger = Logger.getLogger(SNMPHelper.class);
 
  public static final int WARNING_TRAP = 0;
  public static final int CRITICAL_TRAP = 1;
 
  private static final int MAX_ALARM_MESSAGE_SIZE = 510;
  private static final String ALARM_MESSAGE_OID = "1.3.6.1.4.1.18890.1.1";
  private static final String TRAP_OID = "1.3.6.1.4.1.18890.1";
 
  private static int DEFAULT_TRAP_SERVER_PORT = 162;
  private static int DEFAULT_AGENT_PORT = 161;
 
  public static String alarmMessageOid = ALARM_MESSAGE_OID;
  public static String trapId = TRAP_OID;
 
  static void sendTrap(String address, String community,
      String message, int trapType) throws SNMPException {
    sendTrap(address, community, message, trapType, DEFAULT_TRAP_SERVER_PORT);
  }
 
  public static void sendTrap(String address, String community,
      String message, int trapType, int port) throws SNMPException {
    address= address + "/" + port;
    Address targetAddress = GenericAddress.parse(address);
    logger.info("sendig trap to: " + address + ", message: " + message);
   
    CommunityTarget target = new CommunityTarget();
    target.setCommunity(new OctetString(community));
    target.setAddress(targetAddress);
   
    PDUv1 pdu = new PDUv1();
    pdu.setType(PDU.V1TRAP);
    VariableBinding vb = new VariableBinding();
    OID oidMessage = new OID (alarmMessageOid);
    vb.setOid(oidMessage);
    if(message.length() < MAX_ALARM_MESSAGE_SIZE) {
      vb.setVariable(new OctetString(message));
    } else {
      String tmpMessage = message.substring(0,MAX_ALARM_MESSAGE_SIZE);
      logger.info(" message too long " + message  +
          ". send " + tmpMessage);
      vb.setVariable(new OctetString(tmpMessage));
    }
    pdu.add(vb);   
    OID oid  = new OID(trapId);
    if(trapType == CRITICAL_TRAP) {
      pdu.setSpecificTrap(CRITICAL_TRAP);
    } else {
      pdu.setSpecificTrap(WARNING_TRAP);
    }
    pdu.setEnterprise(oid);
    pdu.setGenericTrap(PDUv1.ENTERPRISE_SPECIFIC);
   
    try {
      DefaultUdpTransportMapping udpTransportMap = new
        DefaultUdpTransportMapping();
      Snmp snmp = new Snmp(udpTransportMap);
      ResponseEvent response =  snmp.send(pdu, target);
      logger.debug("trap pdu: " + pdu);
      logger.trace("response: " + response);
     
      snmp.close();
    } catch (IOException e) {
      throw new SNMPException("Cannot send trap. IO exception: "
          + e.getMessage());
    }
  }
 
  public static void snmpSet(String address, String community,
      String oid, int value) throws SNMPException {
    snmpSet(address, community, oid, value, DEFAULT_AGENT_PORT);
  }
 
  public static void snmpSet(String address, String community,
      String oid, int value, int port) throws SNMPException {
    address = address + "/" + port;
    Address targetAddress = GenericAddress.parse(address);
    Snmp snmp;
   
    try {
      TransportMapping transport = new DefaultUdpTransportMapping();
      snmp = new Snmp(transport);
      CommunityTarget target = new CommunityTarget();
      target.setCommunity(new OctetString(community));
      target.setAddress(targetAddress);
      target.setRetries(0);
      target.setTimeout(200);
      target.setVersion(SnmpConstants.version2c);
      PDU pdu = new PDU();
      pdu.add(new VariableBinding(new OID(oid), new Integer32(value)));
      pdu.setType(PDU.SET);
      ResponseListener listener = new ResponseListener() {
        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);
        }
      };
      snmp.send(pdu, target, null, listener);
      snmp.close();
    }
    catch (IOException e) {
      String message = "No set snmp. IO exception: " + e.getMessage();
      logger.error(message);
      throw new SNMPException(message);
    } catch (Exception e) {
      logger.error(e.getMessage());
    }
  }
 
  public static int snmpGet(String address, String community, String oid)
      throws SNMPException {
    return snmpGet(address, community, oid, DEFAULT_AGENT_PORT);
  }
 
  public static int snmpGet(String address, String community,
      String oid, int port) throws SNMPException {
    int ret = 0;   
    address= address + "/" + port;
   
    try {
      Address targetaddress = new UdpAddress(address);
      TransportMapping transport = new DefaultUdpTransportMapping();
      transport.listen();
      CommunityTarget comtarget = new CommunityTarget();
      comtarget.setCommunity(new OctetString(community));
      comtarget.setVersion(SnmpConstants.version1);
      comtarget.setAddress(targetaddress);
      comtarget.setRetries(2);
      comtarget.setTimeout(5000);
      PDU pdu = new PDU();
      ResponseEvent response;
      Snmp snmp;
      pdu.add(new VariableBinding(new OID(oid)));
      pdu.setType(PDU.GET);
      snmp = new Snmp(transport);
      response = snmp.get(pdu,comtarget);
      if(response != null) {
        String errorStatus =
          response.getResponse().getErrorStatusText();
        if(errorStatus.equalsIgnoreCase("Success")) {
          PDU pduresponse = response.getResponse();
          String str =
            pduresponse.getVariableBindings().firstElement().toString();
          if(str.contains("=")) {
            int len = str.indexOf("=");
            str=str.substring(len+1, str.length());
          }
          str = str.trim();
          ret = Integer.parseInt(str);
        }
      } else {
        snmp.close();
        String message = "Nessuna risposta dal sub agent. OID: " + oid +
          ", agent: " + address;
        logger.error("no response by agent. OID: " + oid +
          ", agent: " + address);
        throw new SNMPException(message);   
      }
      snmp.close();
     
    } catch(NumberFormatException e) {
      String message = "Il valore di ritorno no integer per OID: " + oid;
      logger.error("data is no a int cause, NumberFormatException " +
          e.getMessage());
      throw new SNMPException(message);
    } catch (IOException e) {
      String message = "No get snmp. IO exception: " + e.getMessage();
      logger.error(message);
      throw new SNMPException(message);
    } catch (Exception e) {
      logger.error(e.getMessage());
    }
   
    return ret;
 
}
TOP

Related Classes of org.saf.snmp.SNMPHelper

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.