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

📄 commandprocessor.java

📁 用snmp4j实现的agent,代码比较多,但是很值得一看,尤其是对于要用SNMP监控信息的编程者,可以仔细研究一下里面的代码.
💻 JAVA
📖 第 1 页 / 共 3 页
字号:
            case Request.PHASE_2PC_COMMIT: {
              commit(context, request, server);
              break;
            }
            case Request.PHASE_2PC_UNDO: {
              undo(context, request, server);
              break;
            }
            case Request.PHASE_2PC_CLEANUP: {
              cleanup(context, request, server);
              return;
            }
          }
          if (!request.isPhaseComplete()) {
            // request needs to be reprocessed later!
            return;
          }
        }
      }
      catch (Exception ex) {
        if (logger.isDebugEnabled()) {
          ex.printStackTrace();
        }
        logger.error("Failed to process SET request, trying to clean it up...",
                     ex);
        if (SNMP4JSettings.isFowardRuntimeExceptions()) {
          throw new RuntimeException(ex);
        }
      }
      cleanup(context, request, server);
    }

    protected void undo(OctetString context, Request request,
                        MOServer server) {
      try {
        SubRequestIterator it = (SubRequestIterator) request.iterator();
        while (it.hasNext()) {
          SubRequest sreq =  it.nextSubRequest();
          if (sreq.isComplete()) {
            continue;
          }
          OID oid = sreq.getVariableBinding().getOid();
          ManagedObject mo = sreq.getTargetMO();
          if (mo == null) {
            DefaultMOContextScope scope =
                new DefaultMOContextScope(context, oid, true, oid, true);
            mo = server.lookup(new DefaultMOQuery(scope, true, request));
          }
          if (mo == null) {
            sreq.getStatus().setErrorStatus(PDU.undoFailed);
            continue;
          }
          try {
            mo.undo(sreq);
          }
          catch (Exception moex) {
            if (logger.isDebugEnabled()) {
              moex.printStackTrace();
            }
            logger.error(moex);
            if (sreq.getStatus().getErrorStatus() == PDU.noError) {
              sreq.getStatus().setErrorStatus(PDU.undoFailed);
            }
            if (SNMP4JSettings.isFowardRuntimeExceptions()) {
              throw new RuntimeException(moex);
            }
          }
        }
      }
      catch (NoSuchElementException nsex) {
        if (logger.isDebugEnabled()) {
          nsex.printStackTrace();
        }
        logger.error("Cannot find sub-request: ", nsex);
        request.setErrorStatus(PDU.genErr);
      }
    }

    protected void commit(OctetString context, Request request,
                          MOServer server) {
      try {
        SubRequestIterator it = (SubRequestIterator) request.iterator();
        while ((request.getErrorStatus() == PDU.noError) && (it.hasNext())) {
          SubRequest sreq =  it.nextSubRequest();
          if (sreq.isComplete()) {
            continue;
          }
          OID oid = sreq.getVariableBinding().getOid();
          ManagedObject mo = sreq.getTargetMO();
          if (mo == null) {
            DefaultMOContextScope scope =
                new DefaultMOContextScope(context, oid, true, oid, true);
            mo = server.lookup(new DefaultMOQuery(scope, true, request));
          }
          if (mo == null) {
            sreq.getStatus().setErrorStatus(PDU.commitFailed);
            continue;
          }
          try {
            mo.commit(sreq);
          }
          catch (Exception moex) {
            if (logger.isDebugEnabled()) {
              moex.printStackTrace();
            }
            logger.error(moex);
            if (sreq.getStatus().getErrorStatus() == PDU.noError) {
              sreq.getStatus().setErrorStatus(PDU.commitFailed);
            }
            if (SNMP4JSettings.isFowardRuntimeExceptions()) {
              throw new RuntimeException(moex);
            }
          }
        }
      }
      catch (NoSuchElementException nsex) {
        if (logger.isDebugEnabled()) {
          nsex.printStackTrace();
        }
        logger.error("Cannot find sub-request: ", nsex);
        request.setErrorStatus(PDU.genErr);
      }
    }

    protected void cleanup(OctetString context, Request request,
                           MOServer server) {
      try {
        SubRequestIterator it = (SubRequestIterator) request.iterator();
        while (it.hasNext()) {
          SubRequest sreq =  it.nextSubRequest();
          if (sreq.isComplete()) {
            continue;
          }
          OID oid = sreq.getVariableBinding().getOid();
          ManagedObject mo = sreq.getTargetMO();
          if (mo == null) {
            DefaultMOContextScope scope =
                new DefaultMOContextScope(context, oid, true, oid, true);
            mo = server.lookup(new DefaultMOQuery(scope));
          }
          if (mo == null) {
            sreq.completed();
            continue;
          }
          server.unlock(sreq.getRequest(), mo);
          try {
            mo.cleanup(sreq);
            sreq.getStatus().setPhaseComplete(true);
          }
          catch (Exception moex) {
            if (logger.isDebugEnabled()) {
              moex.printStackTrace();
            }
            logger.error(moex);
            if (SNMP4JSettings.isFowardRuntimeExceptions()) {
              throw new RuntimeException(moex);
            }
          }
        }
      }
      catch (NoSuchElementException nsex) {
        logger.error("Cannot find sub-request: ", nsex);
        if (logger.isDebugEnabled()) {
          nsex.printStackTrace();
        }
      }
    }

    public boolean isSupported(int pduType) {
      return (pduType == PDU.SET);
    }

  }

  class GetHandler implements RequestHandler {

    public boolean isSupported(int pduType) {
      return (pduType == PDU.GET);
    }

    public void processPdu(Request request, MOServer server) {
      initRequestPhase(request);
      OctetString context = request.getContext();
      try {
        SubRequestIterator it = (SubRequestIterator) request.iterator();
        while (it.hasNext()) {
          SubRequest sreq =  it.nextSubRequest();
          MOScope scope = sreq.getScope();
          MOQuery query = sreq.getQuery();
          if (query == null) {
            query = new VACMQuery(context,
                                  scope.getLowerBound(),
                                  scope.isLowerIncluded(),
                                  scope.getUpperBound(),
                                  scope.isUpperIncluded(),
                                  request.getViewName());
            sreq.setQuery(query);
          }
          ManagedObject mo = server.lookup(query);
          if (mo == null) {
            sreq.getVariableBinding().setVariable(Null.noSuchObject);
            sreq.getStatus().setPhaseComplete(true);
            continue;
          }
          try {
            mo.get(sreq);
            if ((request.getMessageProcessingModel() == MPv1.ID) &&
                (sreq.getVariableBinding().getSyntax() ==
                 SMIConstants.SYNTAX_COUNTER64)) {
              sreq.getVariableBinding().setVariable(Null.noSuchInstance);
            }
          }
          catch (Exception moex) {
            if (logger.isDebugEnabled()) {
              moex.printStackTrace();
            }
            logger.warn(moex);
            if (sreq.getStatus().getErrorStatus() == PDU.noError) {
              sreq.getStatus().setErrorStatus(PDU.genErr);
            }
            if (SNMP4JSettings.isFowardRuntimeExceptions()) {
              throw new RuntimeException(moex);
            }
          }
        }
      }
      catch (NoSuchElementException nsex) {
        if (logger.isDebugEnabled()) {
          nsex.printStackTrace();
        }
        logger.error("SubRequest not found");
        request.setErrorStatus(PDU.genErr);
      }
    }

  }

  class GetBulkHandler implements RequestHandler {

    public boolean isSupported(int pduType) {
      return (pduType == PDU.GETBULK);
    }

    public void processPdu(Request request, MOServer server) {
      initRequestPhase(request);
      OctetString context = request.getContext();
      SnmpRequest req = (SnmpRequest)request;
      int nonRep = req.getNonRepeaters();
      try {
        SubRequestIterator it = (SubRequestIterator) request.iterator();
        int i = 0;
        // non repeaters
        for (; ((i < nonRep) && it.hasNext()); i++) {
          SubRequest sreq =  it.nextSubRequest();
          if (!sreq.isComplete()) {
            processNextSubRequest(request, server, context, sreq);
          }
        }
        // repetitions
        for (; it.hasNext(); i++) {
          SubRequest sreq =  it.nextSubRequest();
          if (!sreq.isComplete()) {
            processNextSubRequest(request, server, context, sreq);
            sreq.updateNextRepetition();
          }
        }
      }
      catch (NoSuchElementException nsex) {
        if (logger.isDebugEnabled()) {
          nsex.printStackTrace();
        }
        logger.error("SubRequest not found");
        request.setErrorStatus(PDU.genErr);
      }
    }
  }

  class VACMQuery extends DefaultMOQuery {

    private OctetString viewName;

    /**
     * Creates a VACMQuery for read-only access.
     * @param context
     *   the context for the query, an empty OctetString denotes the default
     *   context.
     * @param lowerBound
     *   the lower bound OID.
     * @param isLowerIncluded
     *   indicates whether the lower bound should be included or not.
     * @param upperBound
     *   the upper bound OID or <code>null</code> if no upper bound is
     *   specified.
     * @param isUpperIncluded
     *   indicates whether the upper bound should be included or not.
     * @param viewName
     *   the view name to use for the query.
     * @deprecated
     *   Use a constructor with <code>source</code> reference parameter instead.
     */
    public VACMQuery(OctetString context,
                     OID lowerBound, boolean isLowerIncluded,
                     OID upperBound, boolean isUpperIncluded,
                     OctetString viewName) {
      super(new DefaultMOContextScope(context,
                                      lowerBound, isLowerIncluded,
                                      upperBound, isUpperIncluded));
      this.viewName = viewName;
    }

    /**
     * Creates a VACMQuery for read-only access.
     * @param context
     *   the context for the query, an empty OctetString denotes the default
     *   context.
     * @param lowerBound
     *   the lower bound OID.
     * @param isLowerIncluded
     *   indicates whether the lower bound should be included or not.
     * @param upperBound
     *   the upper bound OID or <code>null</code> if no upper bound is
     *   specified.
     * @param isUpperIncluded
     *   indicates whether the upper bound should be included or not.
     * @param viewName
     *   the view name to use for the query.
     * @param isWriteAccessIntended
     *   indicates if this query is issued on behalf of a SNMP SET request
     *   or not.
     * @param source
     *   the source ({@link Request}) object on whose behalf this query is
     *   executed.
     * @since 1.1
     */
    public VACMQuery(OctetString context,
                     OID lowerBound, boolean isLowerIncluded,
                     OID upperBound, boolean isUpperIncluded,
                     OctetString viewName,
                     boolean isWriteAccessIntended,
                     Object source) {
      super(new DefaultMOContextScope(context,
                                      lowerBound, isLowerIncluded,
                                      upperBound, isUpperIncluded),
            isWriteAccessIntended, source);
      this.viewName = viewName;
    }

    public boolean isSearchQuery() {
      MOContextScope scope = getScope();
      return ((!scope.isLowerIncluded()) &&
              ((scope.getUpperBound() == null) ||
               (!scope.getUpperBound().equals(scope.getLowerBound()))));
    }

    public boolean matchesQuery(ManagedObject managedObject) {
      OID oid;
      if (isSearchQuery()) {
         oid = managedObject.find(getScope());
         if (oid == null) {
           return false;
         }
      }
      else {
        oid = getScope().getLowerBound();
      }
      return (vacm.isAccessAllowed(viewName, oid) == VACM.VACM_OK);
    }

    public boolean isAccessAllowed(OID oid) {
      return (vacm.isAccessAllowed(viewName, oid) == VACM.VACM_OK);
    }

    public String toString() {
      return super.toString()+
          "[viewName="+viewName+"]";
    }

  }

  static class DefaultRequestFactory implements RequestFactory {
    public Request createRequest(EventObject initiatingEvent,
                                 CoexistenceInfo cinfo) {
      return new SnmpRequest((CommandResponderEvent)initiatingEvent, cinfo);
    }

  }

}

⌨️ 快捷键说明

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