View Javadoc
1   /**
2    * This file is part of GoldenGate Project (named also GoldenGate or GG).
3    * 
4    * Copyright 2009, Frederic Bregier, and individual contributors by the @author
5    * tags. See the COPYRIGHT.txt in the distribution for a full listing of
6    * individual contributors.
7    * 
8    * All GoldenGate Project is free software: you can redistribute it and/or
9    * modify it under the terms of the GNU General Public License as published by
10   * the Free Software Foundation, either version 3 of the License, or (at your
11   * option) any later version.
12   * 
13   * GoldenGate is distributed in the hope that it will be useful, but WITHOUT ANY
14   * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
15   * A PARTICULAR PURPOSE. See the GNU General Public License for more details.
16   * 
17   * You should have received a copy of the GNU General Public License along with
18   * GoldenGate . If not, see <http://www.gnu.org/licenses/>.
19   */
20  package goldengate.snmp.test;
21  
22  import java.io.IOException;
23  import java.util.ArrayList;
24  import java.util.List;
25  
26  import org.snmp4j.CommunityTarget;
27  import org.snmp4j.PDU;
28  import org.snmp4j.Snmp;
29  import org.snmp4j.Target;
30  import org.snmp4j.TransportMapping;
31  import org.snmp4j.event.ResponseEvent;
32  import org.snmp4j.event.ResponseListener;
33  import org.snmp4j.mp.SnmpConstants;
34  import org.snmp4j.smi.Address;
35  import org.snmp4j.smi.GenericAddress;
36  import org.snmp4j.smi.OID;
37  import org.snmp4j.smi.OctetString;
38  import org.snmp4j.smi.UdpAddress;
39  import org.snmp4j.smi.VariableBinding;
40  import org.snmp4j.transport.DefaultUdpTransportMapping;
41  import org.snmp4j.util.DefaultPDUFactory;
42  import org.snmp4j.util.TableEvent;
43  import org.snmp4j.util.TableUtils;
44  
45  /**
46   * Simple SNMP Client (for testing purpose)
47   * 
48   * @author Frederic Bregier
49   * 
50   */
51  public class GgSimpleSnmpClient {
52  
53      private String address;
54  
55      private int port;
56  
57      private Snmp snmp;
58  
59      /**
60       * @param clientAddress
61       * @param port
62       */
63      public GgSimpleSnmpClient(String clientAddress, int port) {
64          this.address = clientAddress;
65          this.port = port;
66          try {
67              start();
68          } catch (IOException e) {
69              System.err.println(e);
70              throw new RuntimeException(e);
71          }
72      }
73  
74      // Since snmp4j relies on asynch req/resp we need a listener
75      // for responses which should be closed
76      public void stop() throws IOException {
77          snmp.close();
78      }
79  
80      /**
81       * Start the Snmp session. If you forget the listen() method you will not
82       * get any answers because the communication is asynchronous and the
83       * listen() method listens for answers.
84       * 
85       * @throws IOException
86       **/
87      private void start() throws IOException {
88          UdpAddress upaddress = new UdpAddress(port);
89          System.err.println("Listen: " + upaddress);
90          TransportMapping<UdpAddress> transport = new DefaultUdpTransportMapping(upaddress);
91          snmp = new Snmp(transport);
92          // Do not forget this line!
93          transport.listen();
94      }
95  
96      /**
97       * Method which takes a single OID and returns the response from the agent
98       * as a String.
99       * 
100      * @param oid
101      * @return String
102      * @throws IOException
103      **/
104     public String getAsString(OID oid) throws IOException {
105         ResponseEvent event = get(new OID[] {
106             oid });
107         return event.getResponse().get(0).getVariable().toString();
108     }
109 
110     /**
111      * This method is capable of handling multiple OIDs linked with a listener
112      * 
113      * @param oids
114      * @param listener
115      * 
116      * @throws IOException
117      **/
118     public void getAsString(OID oids, ResponseListener listener) {
119         try {
120             snmp.send(getPDU(new OID[] {
121                 oids }), getTarget(), null, listener);
122         } catch (IOException e) {
123             throw new RuntimeException(e);
124         }
125     }
126 
127     /**
128      * 
129      * @param oids
130      * @return A PDU from oids
131      */
132     private PDU getPDU(OID oids[]) {
133         PDU pdu = new PDU();
134         for (OID oid: oids) {
135             pdu.add(new VariableBinding(oid));
136         }
137 
138         pdu.setType(PDU.GET);
139         return pdu;
140     }
141 
142     /**
143      * This method is capable of handling multiple OIDs
144      * 
145      * @param oids
146      * @return ResponseEvent
147      * @throws IOException
148      **/
149     public ResponseEvent get(OID oids[]) throws IOException {
150         ResponseEvent event = snmp.send(getPDU(oids), getTarget(), null);
151         if (event != null) {
152             return event;
153         }
154         throw new RuntimeException("GET timed out");
155     }
156 
157     /**
158      * This method returns a Target, which contains information about where the
159      * data should be fetched and how.
160      * 
161      * @return
162      **/
163     private Target getTarget() {
164         Address targetAddress = GenericAddress.parse(address);
165         CommunityTarget target = new CommunityTarget();
166         target.setCommunity(new OctetString("public"));
167         target.setAddress(targetAddress);
168         target.setRetries(2);
169         target.setTimeout(1500);
170         target.setVersion(SnmpConstants.version2c);
171         return target;
172     }
173 
174     /**
175      * Normally this would return domain objects or something else than this...
176      */
177     public List<List<String>> getTableAsStrings(OID[] oids) {
178         TableUtils tUtils = new TableUtils(snmp, new DefaultPDUFactory());
179 
180         List<TableEvent> events = tUtils
181                 .getTable(getTarget(), oids, null, null);
182 
183         List<List<String>> list = new ArrayList<List<String>>();
184         for (TableEvent event: events) {
185             if (event.isError()) {
186                 System.err.println(event);
187                 continue;
188                 // throw new
189                 // RuntimeException(event.getErrorMessage(),event.getException());
190             }
191             List<String> strList = new ArrayList<String>();
192             list.add(strList);
193             for (VariableBinding vb: event.getColumns()) {
194                 strList.add(vb.getVariable().toString());
195             }
196         }
197         return list;
198     }
199 
200     public static String extractSingleString(ResponseEvent event) {
201         return event.getResponse().get(0).getVariable().toString();
202     }
203 
204 }