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

📄 snmprequest.java

📁 你个snmp的源码
💻 JAVA
📖 第 1 页 / 共 2 页
字号:

/*_############################################################################
  _##
  _##  SNMP4J-Agent - SnmpRequest.java
  _##
  _##  Copyright 2005-2006  Frank Fock (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.agent.request;

import java.util.*;

import org.snmp4j.*;
import org.snmp4j.agent.security.*;
import org.snmp4j.mp.*;
import org.snmp4j.smi.*;
import org.snmp4j.agent.DefaultMOContextScope;
import org.snmp4j.agent.MOScope;
import org.snmp4j.agent.ManagedObject;
import org.snmp4j.log.LogAdapter;
import org.snmp4j.log.LogFactory;
import org.snmp4j.agent.mo.snmp.CoexistenceInfo;
import org.snmp4j.agent.request.SnmpRequest.SnmpSubRequest;
import org.snmp4j.agent.MOQuery;

/**
 *
 * @author Frank Fock
 * @version 1.0
 */
public class SnmpRequest extends AbstractRequest {

  private static final LogAdapter logger =
      LogFactory.getLogger(SnmpRequest.class);

  public static final OctetString DEFAULT_CONTEXT = new OctetString();

  private CommandResponderEvent requestEvent;
  private CoexistenceInfo coexistenceInfo;

  private PDU response;
  private OctetString viewName;

  private static int nextTransactionID = 0;

  public SnmpRequest(CommandResponderEvent request, CoexistenceInfo cinfo) {
    this.requestEvent = request;
    this.coexistenceInfo = cinfo;
    correctRequestValues();
    this.transactionID = nextTransactionID();
  }

  public static int nextTransactionID() {
    return nextTransactionID++;
  }

  protected synchronized void setupSubRequests() {
    int capacity = requestEvent.getPDU().size();
    int totalRepetitions = (requestEvent.getPDU() instanceof PDUv1) ? 0 :
        repeaterRowSize*requestEvent.getPDU().getMaxRepetitions();
    subrequests = new ArrayList(capacity + totalRepetitions);
    if (response == null) {
      response = createResponse();
    }
    for (int i=0; i<requestEvent.getPDU().size(); i++) {
      SnmpSubRequest subReq =
          new SnmpSubRequest(requestEvent.getPDU().get(i), i);
      addSubRequest(subReq);
    }
    if (logger.isDebugEnabled()) {
      logger.debug("SnmpSubRequests initialized: "+subrequests);
    }
  }

  /**
   * Returns the number of repetitions that are complete.
   * @return
   *    the minimum <code>r</code> for which all
   *    <code>i&lt;r*(pduSize-nonRepeaters)</code> {@link SubRequest}s
   *    returned by {@link #get(int i)} return true on
   *    {@link SubRequest#isComplete()}.
   */
  public synchronized int getCompleteRepetitions() {
    int i = 0;
    for (Iterator it = subrequests.iterator(); it.hasNext(); i++) {
      SnmpSubRequest sreq = (SnmpSubRequest) it.next();
      if (!sreq.isComplete()) {
        return i/getRepeaterCount();
      }
    }
    return i/getRepeaterCount();
  }

  public int getMaxRepetitions() {
    return requestEvent.getPDU().getMaxRepetitions();
  }

  public int getNonRepeaters() {
    return requestEvent.getPDU().getNonRepeaters();
  }

  private void addSubRequest(SubRequest subReq) {
    subrequests.add(subReq);
    response.add(subReq.getVariableBinding());
  }

  protected int getMaxPhase() {
    return (is2PC()) ? PHASE_2PC_CLEANUP : PHASE_1PC;
  }

/*
  public int indexOf(OID oid) {
    /**@todo Diese org.snmp4j.agent.request.Request-Methode implementieren/
    throw new java.lang.UnsupportedOperationException("Methode indexOf() noch nicht implementiert.");
  }

  public int indexOf(OID oid, int startFrom) {

  }
*/

  public int size() {
    return requestEvent.getPDU().size();
  }

  public Object getSource() {
    return requestEvent;
  }

  public CommandResponderEvent getInitiatingEvent() {
    return requestEvent;
  }

  public void setRequestEvent(CommandResponderEvent requestEvent) {
    this.requestEvent = requestEvent;
  }

  protected void assignErrorStatus2Response() {
    int errStatus = getErrorStatus();
    if (requestEvent.getMessageProcessingModel() == MessageProcessingModel.MPv1) {
      switch (errStatus) {
        case SnmpConstants.SNMP_ERROR_NOT_WRITEABLE:
        case SnmpConstants.SNMP_ERROR_NO_ACCESS:
        case SnmpConstants.SNMP_ERROR_NO_CREATION:
        case SnmpConstants.SNMP_ERROR_INCONSISTENT_NAME: {
          response.setErrorStatus(SnmpConstants.SNMP_ERROR_NO_SUCH_NAME);
          break;
        }
        case SnmpConstants.SNMP_ERROR_RESOURCE_UNAVAILABLE:
        case SnmpConstants.SNMP_ERROR_COMMIT_FAILED:
        case SnmpConstants.SNMP_ERROR_UNDO_FAILED: {
          response.setErrorStatus(SnmpConstants.SNMP_ERROR_GENERAL_ERROR);
          break;
        }
        case SnmpConstants.SNMP_ERROR_WRONG_VALUE:
        case SnmpConstants.SNMP_ERROR_WRONG_LENGTH:
        case SnmpConstants.SNMP_ERROR_INCONSISTENT_VALUE:
        case SnmpConstants.SNMP_ERROR_WRONG_TYPE: {
          response.setErrorStatus(SnmpConstants.SNMP_ERROR_BAD_VALUE);
          break;
        }
        default: {
          response.setErrorStatus(errStatus);
        }
      }
      for (int i=0; i<response.size(); i++) {
        VariableBinding vb = response.get(i);
        if (vb.isException()) {
          response.setErrorStatus(PDU.noSuchName);
          response.setErrorIndex(i+1);
          response.set(i, new VariableBinding(vb.getOid()));
          return;
        }
      }
    }
    response.setErrorStatus(errStatus);
    response.setErrorIndex(getErrorIndex());
  }

  private PDU createResponse() {
    PDU resp = (PDU) requestEvent.getPDU().clone();
    resp.clear();
    resp.setType(PDU.RESPONSE);
    resp.setRequestID(requestEvent.getPDU().getRequestID());
    resp.setErrorIndex(0);
    resp.setErrorStatus(PDU.noError);
    return resp;
  }

  private void correctRequestValues() {
    PDU request = requestEvent.getPDU();
    if (!(request instanceof PDUv1)) {
      if (request.getMaxRepetitions() < 0) {
        request.setMaxRepetitions(0);
      }
      if (request.getNonRepeaters() < 0) {
        request.setNonRepeaters(0);
      }
      repeaterStartIndex = request.getNonRepeaters();
      repeaterRowSize =
          Math.max(request.size() - repeaterStartIndex, 0);
    }
    else {
      repeaterStartIndex = 0;
      repeaterRowSize = request.size();
    }
  }

  public PDU getResponsePDU() {
    return (PDU) getResponse();
  }

  public Object getResponse() {
    if (response == null) {
      response = createResponse();
    }
    assignErrorStatus2Response();
    return response;
  }

  /**
   * iterator
   *
   * @return Iterator
   */
  public Iterator iterator() {
    initSubRequests();
    return new SnmpSubRequestIterator();
  }

  protected boolean is2PC() {
    return (requestEvent.getPDU().getType() == PDU.SET);
  }

  public OctetString getContext() {
    if (coexistenceInfo != null) {
      return coexistenceInfo.getContextName();
    }
    else if (requestEvent.getPDU() instanceof ScopedPDU) {
      return ((ScopedPDU)requestEvent.getPDU()).getContextName();
    }
    return DEFAULT_CONTEXT;
  }

  public OctetString getViewName() {
    return viewName;
  }

  public void setViewName(OctetString viewName) {
    this.viewName = viewName;
  }

  public int getSecurityLevel() {
    return requestEvent.getSecurityLevel();
  }

  public int getSecurityModel() {
    return requestEvent.getSecurityModel();
  }

  public OctetString getSecurityName() {
    return new OctetString(requestEvent.getSecurityName());
  }

  public int getViewType() {
    return getViewType(requestEvent.getPDU().getType());
  }

  /**
   * Returns the VACM view type for the supplied PDU type.
   * @param pduType
   *    a PDU type.
   * @return
   *    the corresponding VACM view type.
   */
  public static final int getViewType(int pduType) {
    switch (pduType) {
      case PDU.GETNEXT:
      case PDU.GET:
      case PDU.GETBULK: {
        return VACM.VIEW_READ;
      }
      case PDU.INFORM:
      case PDU.TRAP:
      case PDU.V1TRAP: {
        return VACM.VIEW_NOTIFY;
      }
      default: {
        return VACM.VIEW_WRITE;
      }
    }
  }

  protected synchronized void addRepeaterSubRequest() {
    int predecessorIndex = subrequests.size() - repeaterRowSize;
    SnmpSubRequest sreq =
        new SnmpSubRequest((SnmpSubRequest)subrequests.get(predecessorIndex),
                           subrequests.size());
    addSubRequest(sreq);
  }

  public int getErrorIndex() {
    if (errorStatus == SnmpConstants.SNMP_ERROR_SUCCESS) {
      return 0;
    }
    initSubRequests();
    int index = 1;
    for (Iterator it = subrequests.iterator(); it.hasNext(); index++) {
      SubRequest sreq = (SubRequest) it.next();
      if (sreq.getStatus().getErrorStatus() != SnmpConstants.SNMP_ERROR_SUCCESS) {
        return index;
      }
    }
    return 0;
  }


  public int getTransactionID() {
    return transactionID;
  }

  public CoexistenceInfo getCoexistenceInfo() {
    return coexistenceInfo;
  }

  /**
   * Returns the last repetition row that is complete (regarding the number
   * of elements in the row) before the given subrequest index.
   * @param upperBoundIndex
   *    the maximum sub-request index within the row to return.
   * @return
   *    a sub list of the sub-requests list that contains the row's elements.
   *    If no such row exists <code>null</code> is returned.
   */
  private List lastRow(int upperBoundIndex) {
    if ((repeaterRowSize == 0) || (upperBoundIndex <= repeaterStartIndex)) {
      return null;
    }
    int rows = (upperBoundIndex - repeaterStartIndex) / repeaterRowSize;
    int startIndex = repeaterStartIndex + (repeaterRowSize*(rows-1));

⌨️ 快捷键说明

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