?? snmp.java
字號:
/*_############################################################################
_##
_## SNMP4J - Snmp.java
_##
_## Copyright 2003-2007 Frank Fock and Jochen Katz (SNMP4J.org)
_##
_## Licensed under the Apache License, Version 2.0 (the "License");
_## you may not use this file except in compliance with the License.
_## You may obtain a copy of the License at
_##
_## http://www.apache.org/licenses/LICENSE-2.0
_##
_## Unless required by applicable law or agreed to in writing, software
_## distributed under the License is distributed on an "AS IS" BASIS,
_## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
_## See the License for the specific language governing permissions and
_## limitations under the License.
_##
_##########################################################################*/
package org.snmp4j;
import java.io.IOException;
import java.util.*;
import org.snmp4j.event.*;
import org.snmp4j.log.*;
import org.snmp4j.mp.*;
import org.snmp4j.security.*;
import org.snmp4j.smi.*;
import org.snmp4j.transport.TransportMappings;
import org.snmp4j.transport.ConnectionOrientedTransportMapping;
/**
* The <code>Snmp</code> class is the core of SNMP4J. It provides functions to
* send and receive SNMP PDUs. All SNMP PDU types can be send. Confirmed
* PDUs can be sent synchronously and asynchronously.
* <p>
* The <code>Snmp</code> class is transport protocol independent. Support for
* a specific {@link TransportMapping} instance is added by calling the
* {@link #addTransportMapping(TransportMapping transportMapping)} method or
* creating a <code>Snmp</code> instance by using the non-default constructor
* with the corresponding transport mapping. Transport mappings are used
* for incoming and outgoing messages.
* <p>
* To setup a default SNMP session for UDP transport and with SNMPv3 support
* the following code snippet can be used:
* <p>
* <pre>
* Address targetAddress = GenericAddress.parse("udp:127.0.0.1/161");
* TransportMapping transport = new DefaultUdpTransportMapping();
* snmp = new Snmp(transport);
* USM usm = new USM(SecurityProtocols.getInstance(),
* new OctetString(MPv3.createLocalEngineID()), 0);
* SecurityModels.getInstance().addSecurityModel(usm);
* transport.listen();
* </pre>
* <p>
* How a synchronous SNMPv3 message with authentication and privacy is then
* sent illustrates the following code snippet:
* <p>
* <pre>
* // add user to the USM
* snmp.getUSM().addUser(new OctetString("MD5DES"),
* new UsmUser(new OctetString("MD5DES"),
* AuthMD5.ID,
* new OctetString("MD5DESUserAuthPassword"),
* PrivDES.ID,
* new OctetString("MD5DESUserPrivPassword")));
* // create the target
* UserTarget target = new UserTarget();
* target.setAddress(targetAddress);
* target.setRetries(1);
* target.setTimeout(5000);
* target.setVersion(SnmpConstants.version3);
* target.setSecurityLevel(SecurityLevel.AUTH_PRIV);
* target.setSecurityName(new OctetString("MD5DES"));
*
* // create the PDU
* PDU pdu = new ScopedPDU();
* pdu.add(new VariableBinding(new OID("1.3.6")));
* pdu.setType(PDU.GETNEXT);
*
* // send the PDU
* ResponseEvent response = snmp.send(pdu, target);
* // extract the response PDU (could be null if timed out)
* PDU responsePDU = response.getResponse();
* // extract the address used by the agent to send the response:
* Address peerAddress = response.getPeerAddress();
* </pre>
* <p>
* An asynchronous SNMPv1 request is sent by the following code:
* <pre>
* // setting up target
* CommunityTarget target = new CommunityTarget();
* target.setCommunity(new OctetString("public"));
* target.setAddress(targetAddress);
* target.setRetries(2);
* target.setTimeout(1500);
* target.setVersion(SnmpConstants.version1);
* // creating PDU
* PDU pdu = new PDU();
* pdu.add(new VariableBinding(new OID(new int[] {1,3,6,1,2,1,1,1})));
* pdu.add(new VariableBinding(new OID(new int[] {1,3,6,1,2,1,1,2})));
* pdu.setType(PDU.GETNEXT);
* // sending request
* 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);
* System.out.println("Received response PDU is: "+event.getResponse());
* }
* };
* snmp.sendPDU(pdu, target, null, listener);
* </pre>
* </p>
* Traps (notifications) and other SNMP PDUs can be received by adding the
* folling code to the first code snippet above:
* <pre>
* CommandResponder trapPrinter = new CommandResponder() {
* public synchronized void processPdu(CommandResponderEvent e) {
* PDU command = e.getPdu();
* if (command != null) {
* System.out.println(command.toString());
* }
* }
* };
* snmp.addCommandResponder(trapPrinter);
* </pre>
* </p>
*
* @author Frank Fock
* @version 1.8
*/
public class Snmp implements Session, CommandResponder {
private static final LogAdapter logger = LogFactory.getLogger(Snmp.class);
// Message processing implementation
private MessageDispatcher messageDispatcher;
/**
* The <code>pendingRequests</code> table contains pending requests
* accessed trough the key <code>PduHandle</code>
*/
private Hashtable pendingRequests = new Hashtable(50);
/**
* The <code>asyncRequests</code> table contains pending requests
* accessed trough the key userObject
*/
private Hashtable asyncRequests = new Hashtable(50);
// Timer for retrying pending requests
private Timer timer = new Timer(true);
// Listeners for request and trap PDUs
private transient Vector commandResponderListeners;
private TimeoutModel timeoutModel = new DefaultTimeoutModel();
// Dispatcher for notification listeners - not needed by default
private NotificationDispatcher notificationDispatcher = null;
// Default ReportHandler
private ReportHandler reportHandler = new ReportProcessor();
/**
* Creates a <code>Snmp</code> instance that uses a
* <code>MessageDispatcherImpl</code> with no message processing
* models and no security protols (by default). You will have to add
* those by calling the appropriate methods on
* {@link #getMessageDispatcher()}.
* <p>
* At least one transport mapping has to be added before {@link #listen()}
* is called in order to be able to send and receive SNMP messages.
*/
public Snmp() {
this.messageDispatcher = new MessageDispatcherImpl();
}
/**
* Interface for handling reports.
*
* @author Frank Fock
* @version 1.6
* @since 1.6
*/
public static interface ReportHandler {
void processReport(PduHandle pduHandle, CommandResponderEvent event);
}
protected final void initMessageDispatcher() {
this.messageDispatcher.addCommandResponder(this);
this.messageDispatcher.addMessageProcessingModel(new MPv2c());
this.messageDispatcher.addMessageProcessingModel(new MPv1());
this.messageDispatcher.addMessageProcessingModel(new MPv3());
SecurityProtocols.getInstance().addDefaultProtocols();
}
/**
* Creates a <code>Snmp</code> instance that uses a
* <code>MessageDispatcherImpl</code> with all supported message processing
* models and the default security protols for dispatching.
*
* @param transportMapping TransportMapping
* the initial <code>TransportMapping</code>. You can add more or remove
* the same later.
*/
public Snmp(TransportMapping transportMapping) {
this();
initMessageDispatcher();
if (transportMapping != null) {
addTransportMapping(transportMapping);
}
}
/**
* Creates a <code>Snmp</code> instance by supplying a <code>
* MessageDispatcher</code> and a <code>TransportMapping</code>.
* <p>
* As of version 1.1, the supplied message dispatcher is not altered
* in terms of adding any message processing models to it. This has to be
* done now outside the Snmp class.
*
* @param messageDispatcher
* a <code>MessageDispatcher</code> instance that will be used to
* dispatch incoming and outgoing messages.
* @param transportMapping
* the initial <code>TransportMapping</code>,
* which may be <code>null</code>. You can add or remove transport
* mappings later using {@link #addTransportMapping} and
* {@link #removeTransportMapping} respectively.
*/
public Snmp(MessageDispatcher messageDispatcher,
TransportMapping transportMapping) {
this.messageDispatcher = messageDispatcher;
this.messageDispatcher.addCommandResponder(this);
if (transportMapping != null) {
addTransportMapping(transportMapping);
}
}
/**
* Creates a <code>Snmp</code> instance by supplying a <code>
* MessageDispatcher</code>.
* <p>
* The supplied message dispatcher is not altered
* in terms of adding any message processing models to it. This has to be
* done now outside the Snmp class.
* </p>
* <p>
* Do not forget to add at least one transport mapping before calling the
* listen method!
* </p>
* @param messageDispatcher
* a <code>MessageDispatcher</code> instance that will be used to
* dispatch incoming and outgoing messages.
* @since 1.5
*/
public Snmp(MessageDispatcher messageDispatcher) {
this.messageDispatcher = messageDispatcher;
this.messageDispatcher.addCommandResponder(this);
}
/**
* Returns the message dispatcher associated with this SNMP session.
* @return
* a <code>MessageDispatcher</code> instance.
* @since 1.1
*/
public MessageDispatcher getMessageDispatcher() {
return messageDispatcher;
}
/**
* Adds a <code>TransportMapping</code> to this SNMP session.
* @param transportMapping
* a <code>TransportMapping</code> instance.
*/
public void addTransportMapping(TransportMapping transportMapping) {
// connect transport mapping with message dispatcher
messageDispatcher.addTransportMapping(transportMapping);
transportMapping.addTransportListener(messageDispatcher);
}
/**
* Removes the specified transport mapping from this SNMP session.
* If the transport mapping is not currently part of this SNMP session,
* this method will have no effect.
* @param transportMapping
* a previously added <code>TransportMapping</code>.
*/
public void removeTransportMapping(TransportMapping transportMapping) {
messageDispatcher.removeTransportMapping(transportMapping);
transportMapping.removeTransportListener(messageDispatcher);
}
/**
* Adds a notification listener to this Snmp instance. Calling this method
* will create a transport mapping for the specified listening address and
* registers the provided <code>CommandResponder</code> with the internal
* <code>NotificationDispatcher</code>.
*
* @param listenAddress
* the <code>Address</code> denoting the transport end-point
* (interface and port) to listen for incoming notifications.
* @param listener
* the <code>CommandResponder</code> instance that should handle
* the received notifications.
* @return
* <code>true</code> if registration was successful and <code>false</code>
* if, for example, the transport mapping for the listen address could not
* be created.
* @since 1.6
*/
public synchronized boolean addNotificationListener(Address listenAddress,
CommandResponder listener)
{
TransportMapping tm =
TransportMappings.getInstance().createTransportMapping(listenAddress);
if (tm == null) {
if (logger.isInfoEnabled()) {
logger.info("Failed to add notification listener for address: "+
listenAddress);
}
return false;
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -