package org.itx.jspwiki.plugin.snmp; import java.util.Map; import java.util.Observable; import java.util.Observer; import com.ecyrd.jspwiki.WikiContext; import com.ecyrd.jspwiki.plugin.PluginException; import com.ecyrd.jspwiki.plugin.WikiPlugin; import uk.co.westhawk.snmp.stack.AsnObject; import uk.co.westhawk.snmp.stack.GetPdu; import uk.co.westhawk.snmp.stack.Pdu; import uk.co.westhawk.snmp.stack.PduException; import uk.co.westhawk.snmp.stack.SnmpContext; import uk.co.westhawk.snmp.stack.varbind; public class SnmpStatus implements WikiPlugin { protected class Receiver implements Observer { varbind[] vars = null; public void update(Observable obs, Object arg) { GetPdu pdu = (GetPdu) obs; if (pdu.getErrorStatus() == AsnObject.SNMP_ERR_NOERROR) { try { vars = pdu.getResponseVarbinds(); } catch (PduException e) { e.printStackTrace(); } } else { destroyAll(pdu); return; } } } @SuppressWarnings("unchecked") public String execute(WikiContext context, Map params) throws PluginException { SnmpContext snmpcontext; GetPdu pdu = null; Receiver receiver; StringBuffer out = new StringBuffer(); String host = getStringParameter(params,"host","127.0.0.1"); String port = getStringParameter(params,"port","161"); String comm = getStringParameter(params,"comm","public"); String oid = getStringParameter(params,"oid","1.3.6.1.2.1.1.1.0"); String nonvalue = getStringParameter(params,"nonvalue","service not available"); try { snmpcontext = createContext(host, Integer.parseInt(port), "udp", comm); receiver = new Receiver(); pdu = createPdu(snmpcontext, new varbind(oid), receiver); pdu.send(); } catch (java.io.IOException exc) { destroyAll(pdu); return out.toString(); } catch (uk.co.westhawk.snmp.stack.PduException exc) { destroyAll(pdu); return out.toString(); } for(int i=0;(i<100) && (receiver.vars == null);i++) try { System.out.println("Wait for "); Thread.sleep(10); } catch (InterruptedException e) { } if (receiver.vars != null) for (varbind v : receiver.vars) { out.append(v.getValue()); } else out.append(nonvalue); destroyAll(pdu); return out.toString(); } private synchronized void destroyAll(Pdu pdu) { if (pdu == null) { System.out.println("Strange destroy!!!"); return; } pdu.deleteObservers(); pdu.getContext().destroy(); } @SuppressWarnings("unchecked") private String getStringParameter(Map params, String str, String def) { String value = (String) params.get(str); if (value == null) { value = def; } return value; } protected SnmpContext createContext(String host, int port, String socketType, String community) throws java.io.IOException { SnmpContext con = new SnmpContext(host, port, socketType); con.setCommunity(community); return con; } protected GetPdu createPdu(SnmpContext snmpcontext, varbind var, Observer obs) { GetPdu newPdu = new GetPdu(snmpcontext); newPdu.addOid(var); newPdu.addObserver(obs); return newPdu; } }