⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 messagedispatcherimpl.java

📁 snmp4j 1.8.2版 The org.snmp4j classes are capable of creating, sending, and receiving SNMPv1/v2c/v3
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
      }
      if (!mp.isProtocolVersionSupported(messageProcessingModel)) {
        throw new MessageException("SNMP version "+messageProcessingModel+
                                   " is not supported "+
                                   "by message processing model "+
                                   messageProcessingModel);
      }
      if (transport == null) {
        transport = getTransport(transportAddress);
      }
      if (transport == null) {
        throw new UnsupportedAddressClassException(
            "Unsupported address class (transport mapping): "+
            transportAddress.getClass().getName(),
            transportAddress.getClass());
      }
      else if (pdu.isConfirmedPdu()) {
        checkListening4ConfirmedPDU(pdu, transportAddress, transport);
      }

      // check PDU type
      checkOutgoingMsg(transportAddress, messageProcessingModel, pdu);

      // if request ID is == 0 then create one here, otherwise use the request
      // ID because it may be a resent request.
      PduHandle pduHandle;
      if ((pdu.getRequestID().getValue() == 0) &&
          (pdu.getType() != PDU.RESPONSE)) {
        pduHandle = createPduHandle();
      }
      else {
        pduHandle = new PduHandle(pdu.getRequestID().getValue());
      }

      // assing request ID
      pdu.setRequestID(new Integer32(pduHandle.getTransactionID()));

      // parameters to receive
      GenericAddress destAddress = new GenericAddress();

      BEROutputStream outgoingMessage = new BEROutputStream();
      int status = mp.prepareOutgoingMessage(transportAddress,
                                             transport.getMaxInboundMessageSize(),
                                             messageProcessingModel,
                                             securityModel,
                                             securityName,
                                             securityLevel,
                                             pdu,
                                             expectResponse,
                                             pduHandle,
                                             destAddress,
                                             outgoingMessage);

      if (status == SnmpConstants.SNMP_ERROR_SUCCESS) {
        // inform callback about PDU new handle
        if (pduHandleCallback != null) {
          pduHandleCallback.pduHandleAssigned(pduHandle, pdu);
        }
        byte[] messageBytes = outgoingMessage.getBuffer().array();
        sendMessage(transport, transportAddress, messageBytes);
      }
      else {
        throw new MessageException("Message processing model "+
                                   mp.getID()+" returned error: "+status);
      }
      return pduHandle;
    }
    catch (IndexOutOfBoundsException iobex) {
      throw new MessageException("Unsupported message processing model: "
                                 + messageProcessingModel);
    }
    catch (MessageException mex) {
      if (logger.isDebugEnabled()) {
        mex.printStackTrace();
      }
      throw mex;
    }
    catch (IOException iox) {
      if (logger.isDebugEnabled()) {
        iox.printStackTrace();
      }
      throw new MessageException(iox.getMessage());
    }
  }

  private static void checkListening4ConfirmedPDU(PDU pdu, Address target,
                                                  TransportMapping transport) {
    if ((transport != null) && (!transport.isListening())) {
      logger.warn("Sending confirmed PDU "+pdu+" to target "+target+
                  " although transport mapping "+transport+
                  " is not listening for a response");
    }
  }

  /**
   * Checks outgoing messages for consistency between PDU and target used.
   * @param transportAddress
   *    the target address.
   * @param messageProcessingModel
   *    the message processing model to be used.
   * @param pdu
   *    the PDU to be sent.
   * @throws MessageException
   *    if unrecoverable inconsistencies have been detected.
   */
  protected void checkOutgoingMsg(Address transportAddress,
                                  int messageProcessingModel, PDU pdu)
      throws MessageException
  {
    if (checkOutgoingMsg) {
      if (messageProcessingModel == MessageProcessingModel.MPv1) {
        if (pdu.getType() == PDU.GETBULK) {
          logger.warn("Converting GETBULK PDU to GETNEXT for SNMPv1 target: "+
                      transportAddress);
          pdu.setType(PDU.GETNEXT);
          pdu.setMaxRepetitions(0);
        }
      }
    }
  }

  public int returnResponsePdu(int messageProcessingModel,
                               int securityModel,
                               byte[] securityName,
                               int securityLevel,
                               PDU pdu,
                               int maxSizeResponseScopedPDU,
                               StateReference stateReference,
                               StatusInformation statusInformation)
      throws MessageException
  {
    try {
      MessageProcessingModel mp =
          getMessageProcessingModel(messageProcessingModel);
      if (mp == null) {
        throw new MessageException("Unsupported message processing model: "
                                   + messageProcessingModel);
      }
      TransportMapping transport = stateReference.getTransportMapping();
      if (transport == null) {
        transport = getTransport(stateReference.getAddress());
      }
      if (transport == null) {
        throw new MessageException("Unsupported address class (transport mapping): "+
                                   stateReference.getAddress().getClass().getName());
      }
      BEROutputStream outgoingMessage = new BEROutputStream();
      int status = mp.prepareResponseMessage(messageProcessingModel,
                                             transport.getMaxInboundMessageSize(),
                                             securityModel,
                                             securityName, securityLevel, pdu,
                                             maxSizeResponseScopedPDU,
                                             stateReference,
                                             statusInformation,
                                             outgoingMessage);
      if (status == SnmpConstants.SNMP_MP_OK) {
        sendMessage(transport,
                    stateReference.getAddress(),
                    outgoingMessage.getBuffer().array());
      }
      return status;
    }
    catch (ArrayIndexOutOfBoundsException aex) {
      throw new MessageException("Unsupported message processing model: "
                                 + messageProcessingModel);
    }
    catch (IOException iox) {
      throw new MessageException(iox.getMessage());
    }
  }

  public void releaseStateReference(int messageProcessingModel,
                                    PduHandle pduHandle) {
    MessageProcessingModel mp = getMessageProcessingModel(messageProcessingModel);
    if (mp == null) {
      throw new IllegalArgumentException("Unsupported message processing model: "+
                                         messageProcessingModel);
    }
    mp.releaseStateReference(pduHandle);
  }

  public synchronized void removeCommandResponder(CommandResponder l) {
    if (commandResponderListeners != null && commandResponderListeners.contains(l)) {
      Vector v = (Vector) commandResponderListeners.clone();
      v.removeElement(l);
      commandResponderListeners = v;
    }
  }

  public synchronized void addCommandResponder(CommandResponder l) {
    Vector v = (commandResponderListeners == null) ?
        new Vector(2) : (Vector) commandResponderListeners.clone();
    if (!v.contains(l)) {
      v.addElement(l);
      commandResponderListeners = v;
    }
  }

  /**
   * Fires a <code>CommandResponderEvent</code>. Listeners are called
   * in order of their registration  until a listener has processed the
   * PDU successfully.
   * @param e
   *   a <code>CommandResponderEvent</code> event.
   */
  protected void fireProcessPdu(CommandResponderEvent e) {
    if (commandResponderListeners != null) {
      Vector listeners = commandResponderListeners;
      int count = listeners.size();
      for (int i = 0; i < count; i++) {
        ((CommandResponder) listeners.elementAt(i)).processPdu(e);
        // if event is marked as processed the event is not forwarded to
        // remaining listeners
        if (e.isProcessed()) {
          return;
        }
      }
    }
  }

  /**
   * Gets the <code>MessageProcessingModel</code> for the supplied message
   * processing model ID.
   *
   * @param messageProcessingModel
   *    a message processing model ID
   *    (see {@link MessageProcessingModel#getID()}).
   * @return
   *    a MessageProcessingModel instance if the ID is known, otherwise
   *    <code>null</code>
   */
  public MessageProcessingModel getMessageProcessingModel(int messageProcessingModel) {
    try {
      return (MessageProcessingModel) mpm.get(messageProcessingModel);
    }
    catch (IndexOutOfBoundsException iobex) {
      return null;
    }
  }

  /**
   * Removes a <code>CounterListener</code>.
   * @param counterListener
   *    a previously added <code>CounterListener</code>.
   */
  public synchronized void removeCounterListener(CounterListener counterListener) {
    if (counterListeners != null && counterListeners.contains(counterListener)) {
      Vector v = (Vector) counterListeners.clone();
      v.removeElement(counterListener);
      counterListeners = v;
    }
  }

  /**
   * Adds a <code>CounterListener</code>.
   * @param counterListener
   *    a <code>CounterListener</code> that will be informed when a counter
   *    needs to incremented.
   */
  public synchronized void addCounterListener(CounterListener counterListener) {
    Vector v = (counterListeners == null) ?
        new Vector(2) : (Vector) counterListeners.clone();
    if (!v.contains(counterListener)) {
      v.addElement(counterListener);
      counterListeners = v;
    }
  }

  /**
   * Fires a counter incrementation event.
   * @param event
   *    the <code>CounterEvent</code> containing the OID of the counter
   *    that needs to be incremented.
   */
  protected void fireIncrementCounter(CounterEvent event) {
    if (counterListeners != null) {
      Vector listeners = counterListeners;
      int count = listeners.size();
      for (int i = 0; i < count; i++) {
        ((CounterListener) listeners.elementAt(i)).incrementCounter(event);
      }
    }
  }

  /**
   * Enables or disables the consistency checks for outgoing messages.
   * If the checks are enabled, then GETBULK messages sent to SNMPv1
   * targets will be converted to GETNEXT messages.
   * <p>
   * In general, if an automatically conversion is not possible, an
   * error is thrown when such a message is to be sent.
   * <p>
   * The default is consistency checks enabled.
   *
   * @param checkOutgoingMsg
   *    if <code>true</code> outgoing messages are checked for consistency.
   *    Currently, only the PDU type will be checked against the used SNMP
   *    version. If <code>false</code>, no checks will be performed.
   */
  public void setCheckOutgoingMsg(boolean checkOutgoingMsg) {
    this.checkOutgoingMsg = checkOutgoingMsg;
  }

  /**
   * Returns whether consistency checks for outgoing messages are activated.
   * @return
   *    if <code>true</code> outgoing messages are checked for consistency.
   *    If <code>false</code>, no checks are performed.
   */
  public boolean isCheckOutgoingMsg() {
    return checkOutgoingMsg;
  }

  /**
   * Adds a listener for authentication failure events caused by unauthenticated
   * incoming messages.
   * @param l
   *    the <code>AuthenticationFailureListener</code> to add.
   * @since 1.5
   */
  public synchronized void addAuthenticationFailureListener(
      AuthenticationFailureListener l) {
      Vector v = (authenticationFailureListeners == null) ?
          new Vector(2) : (Vector) authenticationFailureListeners.clone();
      if (!v.contains(l)) {
        v.addElement(l);
        authenticationFailureListeners = v;
      }
  }

  /**
   * Removes an <code>AuthenticationFailureListener</code>.
   * @param l
   *   the <code>AuthenticationFailureListener</code> to remove.
   */
  public synchronized void removeAuthenticationFailureListener(
      AuthenticationFailureListener l) {
      if (authenticationFailureListeners != null &&
          authenticationFailureListeners.contains(l)) {
        Vector v = (Vector) authenticationFailureListeners.clone();
        v.removeElement(l);
        authenticationFailureListeners = v;
      }
  }

  /**
   * Fires an <code>AuthenticationFailureEvent</code> to all registered
   * listeners.
   * @param event
   *    the event to fire.
   */
  protected void fireAuthenticationFailure(AuthenticationFailureEvent event) {
    if (authenticationFailureListeners != null) {
      Vector listeners = authenticationFailureListeners;
      int count = listeners.size();
      for (int i = 0; i < count; i++) {
        ((AuthenticationFailureListener) listeners.elementAt(i)).
            authenticationFailure(event);
      }
    }
  }

  public PduHandle sendPdu(TransportMapping transportMapping,
                           Address transportAddress,
                           int messageProcessingModel,
                           int securityModel, byte[] securityName,
                           int securityLevel, PDU pdu,
                           boolean expectResponse) throws MessageException {
    return sendPdu(transportMapping, transportAddress, messageProcessingModel,
                   securityModel,
                   securityName, securityLevel, pdu, expectResponse, null);
  }

}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -