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

📄 pdu.java

📁 snmp zip 包开发snmp协议
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
public int getErrorStatus(){    return errstat;}/**  * Returns the string representation of the error status. * * @return the error string * @see #getErrorStatus */public String getErrorStatusString(){    String errString = "";    if (errstat >= 0)    {        if (errstat < errorStrings.length)        {            errString = errorStrings[errstat];            if (errstat == AsnObject.SNMP_ERR_GENERR                     &&                 isTimedOut() == true)            {                errString = TIMED_OUT;            }        }        else        {            // they much be one of the DECODING*_EXC            if (respException != null)            {                errString = respException.getMessage();            }            else            {                errString = "Decoding Exception";            }        }    }    return errString;}/**  * Returns whether or not this PDU is timed out, i.e. it did not get * a response.  * Its errorStatus will be set to AsnObject.SNMP_ERR_GENERR. * * <p> * Note that a SNMP agent can respond with an errorStatus of  * AsnObject.SNMP_ERR_GENERR as well, so getting a * AsnObject.SNMP_ERR_GENERR does not necessarily mean that the request * is timed out! * </p> * * @return true is the PDU was timed out  * @see #getErrorStatus * @see SnmpConstants#SNMP_ERR_GENERR */public boolean isTimedOut(){    return isTimedOut;}/** * This method will wait until the answer is received, instead of * continue with other stuff. */public boolean waitForSelf(){    // Add an extra second to the waiting. This gives the PDU a chance    // to handle the timeout correctly before this thread wakes up.    long del = 1000;    for (int i=0; i< retry_intervals.length; i++)    {        del += retry_intervals[i];    }    boolean res = waitForSelf(del);    if (AsnObject.debug > 6)    {        System.out.println(getClass().getName() + ".waitForSelf(): " + res);    }    // Should I??    if (!answered)     {        handleNoAnswer();    }    return res;}/**  * Returns the string representation of the PDU. * * @return The string of the PDU */public String toString(){    return toString(false);}/** * Returns the string representation of the PDU with or without the * response varbinds. * * @param withRespVars Include the response varbinds or not * @return The string of the PDU */protected String toString(boolean withRespVars){    StringBuffer buffer = new StringBuffer(getClass().getName());    buffer.append("[");    buffer.append("context=").append(context);    buffer.append(", reqId=").append(req_id);    buffer.append(", msgType=0x").append(SnmpUtilities.toHex(msg_type));    buffer.append(", ");    buffer.append(printVars("reqVarbinds", reqVarbinds));    if (withRespVars == true)    {        buffer.append(", ");        buffer.append(printVars("respVarbinds", respVarbinds));    }    buffer.append("]");    return buffer.toString();}/** * Returns the string representation of the varbinds of the PDU. * * @see #toString(boolean) * @since 4_14 */protected StringBuffer printVars(String title, Vector vars){    StringBuffer buffer = new StringBuffer();    buffer.append(title).append("=");    if (vars != null)    {        int sz = vars.size();        buffer.append("[");        for (int i=0; i<sz; i++)        {            if (i > 0)            {                buffer.append(", ");            }            varbind var = (varbind) vars.elementAt(i);            buffer.append(var.toString());        }        buffer.append("]");    }    else    {        buffer.append("null");    }    return buffer;}synchronized boolean waitForSelf(long delay){    if (!got)    {        try         {            wait(delay);        }         catch (InterruptedException ix)         {            ;        }    }    return answered;}void transmit() {    transmit(true);}void transmit(boolean withRetries) {    if (withRetries == true)    {        int n=0;        answered=false;        while ((!context.isDestroyed()) && (!answered) && (n<retry_intervals.length))        {            sendme();            try             {                Thread.sleep(retry_intervals[n]);            }            catch (java.lang.InterruptedException e) {}            n++;        }                if (!answered)         {            handleNoAnswer();        }    }    else    {        // just send it once. this will only happen if we are in a trap        // or response PDU.        sendme();        answered=true;    }    if (!context.removePdu(req_id))    {        if (AsnObject.debug > 6)        {            System.out.println(getClass().getName() + ".transmit(): Failed to remove "+req_id);        }    }}void setTrans(Transmitter t){    trans = t;}/**  * Returns the message type, this will indicate what kind of request we * are dealing with.  * By default it will be set to the GET_REQ_MSG * * @return The message type  */public byte getMsgType(){    return msg_type;}/**  * Sets the message type, this will indicate what kind of request we * are dealing with.  * By default it will be set to the GET_REQ_MSG * * @param type The message type  */protected void setMsgType(byte type){    msg_type = type;}/** * Sets the error status, indicating what went wrong. * * @param err the error status * @see #getErrorIndex * @see #getErrorStatusString * @see #getErrorStatus */protected void setErrorStatus(int err){    errstat = err;    if (AsnObject.debug > 6)    {        System.out.println(getClass().getName() + ".setErrorStatus(): " + errstat);    }    if (errstat != AsnObject.SNMP_ERR_NOERROR)    {        setResponseException(new AgentException(getErrorStatusString()));    }}/** * Sets the error status and the exception, indicating what went wrong. * * @param err the error status * @param exc the PDU Exception that was thrown whilst decoding * * @see #getErrorIndex * @see #getErrorStatusString * @see #getErrorStatus */protected void setErrorStatus(int err, PduException exc){    errstat = err;    setResponseException(exc);}/** * Sets the error index, this indicates which of the OIDs went wrong. * @param ind the error index * @see #setErrorStatus(int) * @see #getErrorIndex */protected void setErrorIndex(int ind){    errind = ind;}/** * Returns whether or not this type of PDU is expecting some kind of response. * This method is used in AbstractSnmpContext to help determine whether * or not to start a thread that listens for a response when sending this * PDU. * The default is <em>true</em>. * * @return true if a response is expected, false if not. * @since 4_14 */protected boolean isExpectingResponse(){    return true;}/** * This method is called when no answer is received after all * retries. * The application is notified of this. * See also fillin() */private void handleNoAnswer(){    if (AsnObject.debug > 6)    {        System.out.println(getClass().getName() + ".handleNoAnswer()");    }    // it's a lie, but it will prevent this method from    // being called twice    answered=true;     isTimedOut = true;    setErrorStatus(AsnObject.SNMP_ERR_GENERR);    setErrorIndex(0);    setChanged();    tell_them();    clearChanged();    synchronized(this)    {        notify();    }}/** * Fill in the received response.  * @see Pdu#getResponseVarbinds() * */void fillin(AsnPduSequence seq) {    if (answered)     {        if (AsnObject.debug > 6)        {            System.out.println(getClass().getName() + ".fillin(): Got a second answer to request "                + req_id);        }        return;    }    // fillin(null) can be called in case of a Decoding exception    if (seq != null)    {        if (seq.isCorrect == true)        {            int n=-1;            try            {                // Fill in the request id                this.req_id = seq.getReqId();                setErrorStatus(seq.getWhatError());                setErrorIndex(seq.getWhereError());                // The varbinds from the response/report are set in a                // new Vector.                AsnSequence varBind = seq.getVarBind();                int size = varBind.getObjCount();                respVarbinds = new Vector(size, 1);                for (n=0; n<size; n++)                 {                    AsnSequence varSeq = (AsnSequence) varBind.getObj(n);                    varbind vb = new varbind(varSeq);                    respVarbinds.addElement(vb);                    new_value(n, vb);                }                // At this point, I don't know whether I received a                // response and should fill in only the respVarbind or                // whether I received a request (via ListeningContext)                // and I should fill in the reqVarbinds.                // So when reqVarbinds is empty, I clone the                // respVarbinds.                if (reqVarbinds.isEmpty())                {                    reqVarbinds = (Vector) respVarbinds.clone();                }            }            catch (Exception e)            {                // it happens that an agent does not encode the varbind                // list properly. Since we try do decode as much as                // possible there may be wrong elements in this list.                DecodingException exc = new DecodingException(                    "Incorrect varbind list, element " + n);                setErrorStatus(AsnObject.SNMP_ERR_DECODINGASN_EXC, exc);            }        }        else        {            // we couldn't read the whole message            // see AsnObject.AsnReadHeader, isCorrect            DecodingException exc = new DecodingException(                "Incorrect packet. No of bytes received less than packet length.");            setErrorStatus(AsnObject.SNMP_ERR_DECODINGPKTLNGTH_EXC, exc);        }    }    // always do 'setChanged', even if there are no varbinds.    setChanged();    tell_them();    clearChanged();    synchronized(this)    {        got = true;        answered = true;        notify();             // see also handleNoAnswer()        if (trans != null)        {            // free up the transmitter, since             // we are happy with the answer.            // trans may be null if we are receiving a trap.            trans.interruptMe();          }    }}/** * Notify all observers. If a decoding exception had occurred, the argument * will be replaced with the exception.  * * <p> * In the case of an exception, the error status * will be set to one of the decoding errors (see * <code>getErrorStatus</code>) * and passed as the parameter  * <code>arg</code> in the * <code>update(Observable obs, Object arg)</code> * method. * </p> * * @param arg The argument passed to update, can be a PduException. * @see SnmpConstants#SNMP_ERR_DECODING_EXC * @see #getErrorStatus * @see #getResponseVarbinds * @since 4.5 */public void notifyObservers(Object arg){    if (respException != null)    {        super.notifyObservers(respException);    }    else    {        super.notifyObservers(arg);    }}}

⌨️ 快捷键说明

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